Home | History | Annotate | Download | only in dist
      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 /* Use posix_fallocate() if it is available
   24113 */
   24114 #if !defined(HAVE_POSIX_FALLOCATE) \
   24115       && (_XOPEN_SOURCE >= 600 || _POSIX_C_SOURCE >= 200112L)
   24116 # define HAVE_POSIX_FALLOCATE 1
   24117 #endif
   24118 
   24119 /*
   24120 ** There are various methods for file locking used for concurrency
   24121 ** control:
   24122 **
   24123 **   1. POSIX locking (the default),
   24124 **   2. No locking,
   24125 **   3. Dot-file locking,
   24126 **   4. flock() locking,
   24127 **   5. AFP locking (OSX only),
   24128 **   6. Named POSIX semaphores (VXWorks only),
   24129 **   7. proxy locking. (OSX only)
   24130 **
   24131 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
   24132 ** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
   24133 ** selection of the appropriate locking style based on the filesystem
   24134 ** where the database is located.
   24135 */
   24136 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
   24137 #  if defined(__APPLE__)
   24138 #    define SQLITE_ENABLE_LOCKING_STYLE 1
   24139 #  else
   24140 #    define SQLITE_ENABLE_LOCKING_STYLE 0
   24141 #  endif
   24142 #endif
   24143 
   24144 /*
   24145 ** Define the OS_VXWORKS pre-processor macro to 1 if building on
   24146 ** vxworks, or 0 otherwise.
   24147 */
   24148 #ifndef OS_VXWORKS
   24149 #  if defined(__RTP__) || defined(_WRS_KERNEL)
   24150 #    define OS_VXWORKS 1
   24151 #  else
   24152 #    define OS_VXWORKS 0
   24153 #  endif
   24154 #endif
   24155 
   24156 /*
   24157 ** standard include files.
   24158 */
   24159 #include <sys/types.h>
   24160 #include <sys/stat.h>
   24161 #include <fcntl.h>
   24162 #include <unistd.h>
   24163 /* #include <time.h> */
   24164 #include <sys/time.h>
   24165 #include <errno.h>
   24166 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
   24167 # include <sys/mman.h>
   24168 #endif
   24169 
   24170 #if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
   24171 # include <sys/ioctl.h>
   24172 # if OS_VXWORKS
   24173 #  include <semaphore.h>
   24174 #  include <limits.h>
   24175 # else
   24176 #  include <sys/file.h>
   24177 #  include <sys/param.h>
   24178 # endif
   24179 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
   24180 
   24181 #if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
   24182 # include <sys/mount.h>
   24183 #endif
   24184 
   24185 #ifdef HAVE_UTIME
   24186 # include <utime.h>
   24187 #endif
   24188 
   24189 /*
   24190 ** Allowed values of unixFile.fsFlags
   24191 */
   24192 #define SQLITE_FSFLAGS_IS_MSDOS     0x1
   24193 
   24194 /*
   24195 ** If we are to be thread-safe, include the pthreads header and define
   24196 ** the SQLITE_UNIX_THREADS macro.
   24197 */
   24198 #if SQLITE_THREADSAFE
   24199 /* # include <pthread.h> */
   24200 # define SQLITE_UNIX_THREADS 1
   24201 #endif
   24202 
   24203 /*
   24204 ** Default permissions when creating a new file
   24205 */
   24206 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
   24207 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
   24208 #endif
   24209 
   24210 /*
   24211 ** Default permissions when creating auto proxy dir
   24212 */
   24213 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
   24214 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
   24215 #endif
   24216 
   24217 /*
   24218 ** Maximum supported path-length.
   24219 */
   24220 #define MAX_PATHNAME 512
   24221 
   24222 /*
   24223 ** Only set the lastErrno if the error code is a real error and not
   24224 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
   24225 */
   24226 #define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
   24227 
   24228 /* Forward references */
   24229 typedef struct unixShm unixShm;               /* Connection shared memory */
   24230 typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
   24231 typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
   24232 typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
   24233 
   24234 /*
   24235 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
   24236 ** cannot be closed immediately. In these cases, instances of the following
   24237 ** structure are used to store the file descriptor while waiting for an
   24238 ** opportunity to either close or reuse it.
   24239 */
   24240 struct UnixUnusedFd {
   24241   int fd;                   /* File descriptor to close */
   24242   int flags;                /* Flags this file descriptor was opened with */
   24243   UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
   24244 };
   24245 
   24246 /*
   24247 ** The unixFile structure is subclass of sqlite3_file specific to the unix
   24248 ** VFS implementations.
   24249 */
   24250 typedef struct unixFile unixFile;
   24251 struct unixFile {
   24252   sqlite3_io_methods const *pMethod;  /* Always the first entry */
   24253   sqlite3_vfs *pVfs;                  /* The VFS that created this unixFile */
   24254   unixInodeInfo *pInode;              /* Info about locks on this inode */
   24255   int h;                              /* The file descriptor */
   24256   unsigned char eFileLock;            /* The type of lock held on this fd */
   24257   unsigned short int ctrlFlags;       /* Behavioral bits.  UNIXFILE_* flags */
   24258   int lastErrno;                      /* The unix errno from last I/O error */
   24259   void *lockingContext;               /* Locking style specific state */
   24260   UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
   24261   const char *zPath;                  /* Name of the file */
   24262   unixShm *pShm;                      /* Shared memory segment information */
   24263   int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
   24264 #if SQLITE_MAX_MMAP_SIZE>0
   24265   int nFetchOut;                      /* Number of outstanding xFetch refs */
   24266   sqlite3_int64 mmapSize;             /* Usable size of mapping at pMapRegion */
   24267   sqlite3_int64 mmapSizeActual;       /* Actual size of mapping at pMapRegion */
   24268   sqlite3_int64 mmapSizeMax;          /* Configured FCNTL_MMAP_SIZE value */
   24269   void *pMapRegion;                   /* Memory mapped region */
   24270 #endif
   24271 #ifdef __QNXNTO__
   24272   int sectorSize;                     /* Device sector size */
   24273   int deviceCharacteristics;          /* Precomputed device characteristics */
   24274 #endif
   24275 #if SQLITE_ENABLE_LOCKING_STYLE
   24276   int openFlags;                      /* The flags specified at open() */
   24277 #endif
   24278 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
   24279   unsigned fsFlags;                   /* cached details from statfs() */
   24280 #endif
   24281 #if OS_VXWORKS
   24282   struct vxworksFileId *pId;          /* Unique file ID */
   24283 #endif
   24284 #ifdef SQLITE_DEBUG
   24285   /* The next group of variables are used to track whether or not the
   24286   ** transaction counter in bytes 24-27 of database files are updated
   24287   ** whenever any part of the database changes.  An assertion fault will
   24288   ** occur if a file is updated without also updating the transaction
   24289   ** counter.  This test is made to avoid new problems similar to the
   24290   ** one described by ticket #3584.
   24291   */
   24292   unsigned char transCntrChng;   /* True if the transaction counter changed */
   24293   unsigned char dbUpdate;        /* True if any part of database file changed */
   24294   unsigned char inNormalWrite;   /* True if in a normal write operation */
   24295 
   24296 #endif
   24297 
   24298 #ifdef SQLITE_TEST
   24299   /* In test mode, increase the size of this structure a bit so that
   24300   ** it is larger than the struct CrashFile defined in test6.c.
   24301   */
   24302   char aPadding[32];
   24303 #endif
   24304 };
   24305 
   24306 /* This variable holds the process id (pid) from when the xRandomness()
   24307 ** method was called.  If xOpen() is called from a different process id,
   24308 ** indicating that a fork() has occurred, the PRNG will be reset.
   24309 */
   24310 static int randomnessPid = 0;
   24311 
   24312 /*
   24313 ** Allowed values for the unixFile.ctrlFlags bitmask:
   24314 */
   24315 #define UNIXFILE_EXCL        0x01     /* Connections from one process only */
   24316 #define UNIXFILE_RDONLY      0x02     /* Connection is read only */
   24317 #define UNIXFILE_PERSIST_WAL 0x04     /* Persistent WAL mode */
   24318 #ifndef SQLITE_DISABLE_DIRSYNC
   24319 # define UNIXFILE_DIRSYNC    0x08     /* Directory sync needed */
   24320 #else
   24321 # define UNIXFILE_DIRSYNC    0x00
   24322 #endif
   24323 #define UNIXFILE_PSOW        0x10     /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
   24324 #define UNIXFILE_DELETE      0x20     /* Delete on close */
   24325 #define UNIXFILE_URI         0x40     /* Filename might have query parameters */
   24326 #define UNIXFILE_NOLOCK      0x80     /* Do no file locking */
   24327 #define UNIXFILE_WARNED    0x0100     /* verifyDbFile() warnings have been issued */
   24328 
   24329 /*
   24330 ** Include code that is common to all os_*.c files
   24331 */
   24332 /************** Include os_common.h in the middle of os_unix.c ***************/
   24333 /************** Begin file os_common.h ***************************************/
   24334 /*
   24335 ** 2004 May 22
   24336 **
   24337 ** The author disclaims copyright to this source code.  In place of
   24338 ** a legal notice, here is a blessing:
   24339 **
   24340 **    May you do good and not evil.
   24341 **    May you find forgiveness for yourself and forgive others.
   24342 **    May you share freely, never taking more than you give.
   24343 **
   24344 ******************************************************************************
   24345 **
   24346 ** This file contains macros and a little bit of code that is common to
   24347 ** all of the platform-specific files (os_*.c) and is #included into those
   24348 ** files.
   24349 **
   24350 ** This file should be #included by the os_*.c files only.  It is not a
   24351 ** general purpose header file.
   24352 */
   24353 #ifndef _OS_COMMON_H_
   24354 #define _OS_COMMON_H_
   24355 
   24356 /*
   24357 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
   24358 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
   24359 ** switch.  The following code should catch this problem at compile-time.
   24360 */
   24361 #ifdef MEMORY_DEBUG
   24362 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
   24363 #endif
   24364 
   24365 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
   24366 # ifndef SQLITE_DEBUG_OS_TRACE
   24367 #   define SQLITE_DEBUG_OS_TRACE 0
   24368 # endif
   24369   int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
   24370 # define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
   24371 #else
   24372 # define OSTRACE(X)
   24373 #endif
   24374 
   24375 /*
   24376 ** Macros for performance tracing.  Normally turned off.  Only works
   24377 ** on i486 hardware.
   24378 */
   24379 #ifdef SQLITE_PERFORMANCE_TRACE
   24380 
   24381 /*
   24382 ** hwtime.h contains inline assembler code for implementing
   24383 ** high-performance timing routines.
   24384 */
   24385 /************** Include hwtime.h in the middle of os_common.h ****************/
   24386 /************** Begin file hwtime.h ******************************************/
   24387 /*
   24388 ** 2008 May 27
   24389 **
   24390 ** The author disclaims copyright to this source code.  In place of
   24391 ** a legal notice, here is a blessing:
   24392 **
   24393 **    May you do good and not evil.
   24394 **    May you find forgiveness for yourself and forgive others.
   24395 **    May you share freely, never taking more than you give.
   24396 **
   24397 ******************************************************************************
   24398 **
   24399 ** This file contains inline asm code for retrieving "high-performance"
   24400 ** counters for x86 class CPUs.
   24401 */
   24402 #ifndef _HWTIME_H_
   24403 #define _HWTIME_H_
   24404 
   24405 /*
   24406 ** The following routine only works on pentium-class (or newer) processors.
   24407 ** It uses the RDTSC opcode to read the cycle count value out of the
   24408 ** processor and returns that value.  This can be used for high-res
   24409 ** profiling.
   24410 */
   24411 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
   24412       (defined(i386) || defined(__i386__) || defined(_M_IX86))
   24413 
   24414   #if defined(__GNUC__)
   24415 
   24416   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   24417      unsigned int lo, hi;
   24418      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
   24419      return (sqlite_uint64)hi << 32 | lo;
   24420   }
   24421 
   24422   #elif defined(_MSC_VER)
   24423 
   24424   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
   24425      __asm {
   24426         rdtsc
   24427         ret       ; return value at EDX:EAX
   24428      }
   24429   }
   24430 
   24431   #endif
   24432 
   24433 #elif (defined(__GNUC__) && defined(__x86_64__))
   24434 
   24435   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   24436       unsigned long val;
   24437       __asm__ __volatile__ ("rdtsc" : "=A" (val));
   24438       return val;
   24439   }
   24440 
   24441 #elif (defined(__GNUC__) && defined(__ppc__))
   24442 
   24443   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   24444       unsigned long long retval;
   24445       unsigned long junk;
   24446       __asm__ __volatile__ ("\n\
   24447           1:      mftbu   %1\n\
   24448                   mftb    %L0\n\
   24449                   mftbu   %0\n\
   24450                   cmpw    %0,%1\n\
   24451                   bne     1b"
   24452                   : "=r" (retval), "=r" (junk));
   24453       return retval;
   24454   }
   24455 
   24456 #else
   24457 
   24458   #error Need implementation of sqlite3Hwtime() for your platform.
   24459 
   24460   /*
   24461   ** To compile without implementing sqlite3Hwtime() for your platform,
   24462   ** you can remove the above #error and use the following
   24463   ** stub function.  You will lose timing support for many
   24464   ** of the debugging and testing utilities, but it should at
   24465   ** least compile and run.
   24466   */
   24467 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
   24468 
   24469 #endif
   24470 
   24471 #endif /* !defined(_HWTIME_H_) */
   24472 
   24473 /************** End of hwtime.h **********************************************/
   24474 /************** Continuing where we left off in os_common.h ******************/
   24475 
   24476 static sqlite_uint64 g_start;
   24477 static sqlite_uint64 g_elapsed;
   24478 #define TIMER_START       g_start=sqlite3Hwtime()
   24479 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
   24480 #define TIMER_ELAPSED     g_elapsed
   24481 #else
   24482 #define TIMER_START
   24483 #define TIMER_END
   24484 #define TIMER_ELAPSED     ((sqlite_uint64)0)
   24485 #endif
   24486 
   24487 /*
   24488 ** If we compile with the SQLITE_TEST macro set, then the following block
   24489 ** of code will give us the ability to simulate a disk I/O error.  This
   24490 ** is used for testing the I/O recovery logic.
   24491 */
   24492 #ifdef SQLITE_TEST
   24493 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
   24494 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
   24495 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
   24496 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
   24497 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
   24498 SQLITE_API int sqlite3_diskfull_pending = 0;
   24499 SQLITE_API int sqlite3_diskfull = 0;
   24500 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
   24501 #define SimulateIOError(CODE)  \
   24502   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
   24503        || sqlite3_io_error_pending-- == 1 )  \
   24504               { local_ioerr(); CODE; }
   24505 static void local_ioerr(){
   24506   IOTRACE(("IOERR\n"));
   24507   sqlite3_io_error_hit++;
   24508   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
   24509 }
   24510 #define SimulateDiskfullError(CODE) \
   24511    if( sqlite3_diskfull_pending ){ \
   24512      if( sqlite3_diskfull_pending == 1 ){ \
   24513        local_ioerr(); \
   24514        sqlite3_diskfull = 1; \
   24515        sqlite3_io_error_hit = 1; \
   24516        CODE; \
   24517      }else{ \
   24518        sqlite3_diskfull_pending--; \
   24519      } \
   24520    }
   24521 #else
   24522 #define SimulateIOErrorBenign(X)
   24523 #define SimulateIOError(A)
   24524 #define SimulateDiskfullError(A)
   24525 #endif
   24526 
   24527 /*
   24528 ** When testing, keep a count of the number of open files.
   24529 */
   24530 #ifdef SQLITE_TEST
   24531 SQLITE_API int sqlite3_open_file_count = 0;
   24532 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
   24533 #else
   24534 #define OpenCounter(X)
   24535 #endif
   24536 
   24537 #endif /* !defined(_OS_COMMON_H_) */
   24538 
   24539 /************** End of os_common.h *******************************************/
   24540 /************** Continuing where we left off in os_unix.c ********************/
   24541 
   24542 /*
   24543 ** Define various macros that are missing from some systems.
   24544 */
   24545 #ifndef O_LARGEFILE
   24546 # define O_LARGEFILE 0
   24547 #endif
   24548 #ifdef SQLITE_DISABLE_LFS
   24549 # undef O_LARGEFILE
   24550 # define O_LARGEFILE 0
   24551 #endif
   24552 #ifndef O_NOFOLLOW
   24553 # define O_NOFOLLOW 0
   24554 #endif
   24555 #ifndef O_BINARY
   24556 # define O_BINARY 0
   24557 #endif
   24558 
   24559 /*
   24560 ** The threadid macro resolves to the thread-id or to 0.  Used for
   24561 ** testing and debugging only.
   24562 */
   24563 #if SQLITE_THREADSAFE
   24564 #define threadid pthread_self()
   24565 #else
   24566 #define threadid 0
   24567 #endif
   24568 
   24569 /*
   24570 ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
   24571 */
   24572 #if !defined(HAVE_MREMAP)
   24573 # if defined(__linux__) && defined(_GNU_SOURCE)
   24574 #  define HAVE_MREMAP 1
   24575 # else
   24576 #  define HAVE_MREMAP 0
   24577 # endif
   24578 #endif
   24579 
   24580 /*
   24581 ** Different Unix systems declare open() in different ways.  Same use
   24582 ** open(const char*,int,mode_t).  Others use open(const char*,int,...).
   24583 ** The difference is important when using a pointer to the function.
   24584 **
   24585 ** The safest way to deal with the problem is to always use this wrapper
   24586 ** which always has the same well-defined interface.
   24587 */
   24588 static int posixOpen(const char *zFile, int flags, int mode){
   24589   return open(zFile, flags, mode);
   24590 }
   24591 
   24592 /*
   24593 ** On some systems, calls to fchown() will trigger a message in a security
   24594 ** log if they come from non-root processes.  So avoid calling fchown() if
   24595 ** we are not running as root.
   24596 */
   24597 static int posixFchown(int fd, uid_t uid, gid_t gid){
   24598 #if OS_VXWORKS
   24599   return 0;
   24600 #else
   24601   return geteuid() ? 0 : fchown(fd,uid,gid);
   24602 #endif
   24603 }
   24604 
   24605 /* Forward reference */
   24606 static int openDirectory(const char*, int*);
   24607 static int unixGetpagesize(void);
   24608 
   24609 /*
   24610 ** Many system calls are accessed through pointer-to-functions so that
   24611 ** they may be overridden at runtime to facilitate fault injection during
   24612 ** testing and sandboxing.  The following array holds the names and pointers
   24613 ** to all overrideable system calls.
   24614 */
   24615 static struct unix_syscall {
   24616   const char *zName;            /* Name of the system call */
   24617   sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
   24618   sqlite3_syscall_ptr pDefault; /* Default value */
   24619 } aSyscall[] = {
   24620   { "open",         (sqlite3_syscall_ptr)posixOpen,  0  },
   24621 #define osOpen      ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
   24622 
   24623   { "close",        (sqlite3_syscall_ptr)close,      0  },
   24624 #define osClose     ((int(*)(int))aSyscall[1].pCurrent)
   24625 
   24626   { "access",       (sqlite3_syscall_ptr)access,     0  },
   24627 #define osAccess    ((int(*)(const char*,int))aSyscall[2].pCurrent)
   24628 
   24629   { "getcwd",       (sqlite3_syscall_ptr)getcwd,     0  },
   24630 #define osGetcwd    ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
   24631 
   24632   { "stat",         (sqlite3_syscall_ptr)stat,       0  },
   24633 #define osStat      ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
   24634 
   24635 /*
   24636 ** The DJGPP compiler environment looks mostly like Unix, but it
   24637 ** lacks the fcntl() system call.  So redefine fcntl() to be something
   24638 ** that always succeeds.  This means that locking does not occur under
   24639 ** DJGPP.  But it is DOS - what did you expect?
   24640 */
   24641 #ifdef __DJGPP__
   24642   { "fstat",        0,                 0  },
   24643 #define osFstat(a,b,c)    0
   24644 #else
   24645   { "fstat",        (sqlite3_syscall_ptr)fstat,      0  },
   24646 #define osFstat     ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
   24647 #endif
   24648 
   24649   { "ftruncate",    (sqlite3_syscall_ptr)ftruncate,  0  },
   24650 #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
   24651 
   24652   { "fcntl",        (sqlite3_syscall_ptr)fcntl,      0  },
   24653 #define osFcntl     ((int(*)(int,int,...))aSyscall[7].pCurrent)
   24654 
   24655   { "read",         (sqlite3_syscall_ptr)read,       0  },
   24656 #define osRead      ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
   24657 
   24658 #if defined(USE_PREAD) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
   24659   { "pread",        (sqlite3_syscall_ptr)pread,      0  },
   24660 #else
   24661   { "pread",        (sqlite3_syscall_ptr)0,          0  },
   24662 #endif
   24663 #define osPread     ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
   24664 
   24665 #if defined(USE_PREAD64)
   24666   { "pread64",      (sqlite3_syscall_ptr)pread64,    0  },
   24667 #else
   24668   { "pread64",      (sqlite3_syscall_ptr)0,          0  },
   24669 #endif
   24670 #ifdef ANDROID
   24671 // Bionic defines pread64 using off64_t rather than off_t.
   24672 #define osPread64   ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
   24673 #else
   24674 #define osPread64   ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
   24675 #endif
   24676 
   24677   { "write",        (sqlite3_syscall_ptr)write,      0  },
   24678 #define osWrite     ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
   24679 
   24680 #if defined(USE_PREAD) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
   24681   { "pwrite",       (sqlite3_syscall_ptr)pwrite,     0  },
   24682 #else
   24683   { "pwrite",       (sqlite3_syscall_ptr)0,          0  },
   24684 #endif
   24685 #define osPwrite    ((ssize_t(*)(int,const void*,size_t,off_t))\
   24686                     aSyscall[12].pCurrent)
   24687 
   24688 #if defined(USE_PREAD64)
   24689   { "pwrite64",     (sqlite3_syscall_ptr)pwrite64,   0  },
   24690 #else
   24691   { "pwrite64",     (sqlite3_syscall_ptr)0,          0  },
   24692 #endif
   24693 #ifdef ANDROID
   24694 // Bionic defines pwrite64 using off64_t rather than off_t.
   24695 #define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off64_t))\
   24696                     aSyscall[13].pCurrent)
   24697 #else
   24698 #define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off_t))\
   24699                     aSyscall[13].pCurrent)
   24700 #endif
   24701 
   24702   { "fchmod",       (sqlite3_syscall_ptr)fchmod,     0  },
   24703 #define osFchmod    ((int(*)(int,mode_t))aSyscall[14].pCurrent)
   24704 
   24705 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
   24706   { "fallocate",    (sqlite3_syscall_ptr)posix_fallocate,  0 },
   24707 #else
   24708   { "fallocate",    (sqlite3_syscall_ptr)0,                0 },
   24709 #endif
   24710 #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
   24711 
   24712   { "unlink",       (sqlite3_syscall_ptr)unlink,           0 },
   24713 #define osUnlink    ((int(*)(const char*))aSyscall[16].pCurrent)
   24714 
   24715   { "openDirectory",    (sqlite3_syscall_ptr)openDirectory,      0 },
   24716 #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
   24717 
   24718   { "mkdir",        (sqlite3_syscall_ptr)mkdir,           0 },
   24719 #define osMkdir     ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
   24720 
   24721   { "rmdir",        (sqlite3_syscall_ptr)rmdir,           0 },
   24722 #define osRmdir     ((int(*)(const char*))aSyscall[19].pCurrent)
   24723 
   24724   { "fchown",       (sqlite3_syscall_ptr)posixFchown,     0 },
   24725 #define osFchown    ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
   24726 
   24727 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
   24728   { "mmap",       (sqlite3_syscall_ptr)mmap,     0 },
   24729 #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
   24730 
   24731   { "munmap",       (sqlite3_syscall_ptr)munmap,          0 },
   24732 #define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
   24733 
   24734 #if HAVE_MREMAP
   24735   { "mremap",       (sqlite3_syscall_ptr)mremap,          0 },
   24736 #else
   24737   { "mremap",       (sqlite3_syscall_ptr)0,               0 },
   24738 #endif
   24739 #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
   24740   { "getpagesize",  (sqlite3_syscall_ptr)unixGetpagesize, 0 },
   24741 #define osGetpagesize ((int(*)(void))aSyscall[24].pCurrent)
   24742 
   24743 #endif
   24744 
   24745 }; /* End of the overrideable system calls */
   24746 
   24747 /*
   24748 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
   24749 ** "unix" VFSes.  Return SQLITE_OK opon successfully updating the
   24750 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
   24751 ** system call named zName.
   24752 */
   24753 static int unixSetSystemCall(
   24754   sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
   24755   const char *zName,            /* Name of system call to override */
   24756   sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
   24757 ){
   24758   unsigned int i;
   24759   int rc = SQLITE_NOTFOUND;
   24760 
   24761   UNUSED_PARAMETER(pNotUsed);
   24762   if( zName==0 ){
   24763     /* If no zName is given, restore all system calls to their default
   24764     ** settings and return NULL
   24765     */
   24766     rc = SQLITE_OK;
   24767     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
   24768       if( aSyscall[i].pDefault ){
   24769         aSyscall[i].pCurrent = aSyscall[i].pDefault;
   24770       }
   24771     }
   24772   }else{
   24773     /* If zName is specified, operate on only the one system call
   24774     ** specified.
   24775     */
   24776     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
   24777       if( strcmp(zName, aSyscall[i].zName)==0 ){
   24778         if( aSyscall[i].pDefault==0 ){
   24779           aSyscall[i].pDefault = aSyscall[i].pCurrent;
   24780         }
   24781         rc = SQLITE_OK;
   24782         if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
   24783         aSyscall[i].pCurrent = pNewFunc;
   24784         break;
   24785       }
   24786     }
   24787   }
   24788   return rc;
   24789 }
   24790 
   24791 /*
   24792 ** Return the value of a system call.  Return NULL if zName is not a
   24793 ** recognized system call name.  NULL is also returned if the system call
   24794 ** is currently undefined.
   24795 */
   24796 static sqlite3_syscall_ptr unixGetSystemCall(
   24797   sqlite3_vfs *pNotUsed,
   24798   const char *zName
   24799 ){
   24800   unsigned int i;
   24801 
   24802   UNUSED_PARAMETER(pNotUsed);
   24803   for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
   24804     if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
   24805   }
   24806   return 0;
   24807 }
   24808 
   24809 /*
   24810 ** Return the name of the first system call after zName.  If zName==NULL
   24811 ** then return the name of the first system call.  Return NULL if zName
   24812 ** is the last system call or if zName is not the name of a valid
   24813 ** system call.
   24814 */
   24815 static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
   24816   int i = -1;
   24817 
   24818   UNUSED_PARAMETER(p);
   24819   if( zName ){
   24820     for(i=0; i<ArraySize(aSyscall)-1; i++){
   24821       if( strcmp(zName, aSyscall[i].zName)==0 ) break;
   24822     }
   24823   }
   24824   for(i++; i<ArraySize(aSyscall); i++){
   24825     if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
   24826   }
   24827   return 0;
   24828 }
   24829 
   24830 /*
   24831 ** Do not accept any file descriptor less than this value, in order to avoid
   24832 ** opening database file using file descriptors that are commonly used for
   24833 ** standard input, output, and error.
   24834 */
   24835 #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
   24836 # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
   24837 #endif
   24838 
   24839 /*
   24840 ** Invoke open().  Do so multiple times, until it either succeeds or
   24841 ** fails for some reason other than EINTR.
   24842 **
   24843 ** If the file creation mode "m" is 0 then set it to the default for
   24844 ** SQLite.  The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
   24845 ** 0644) as modified by the system umask.  If m is not 0, then
   24846 ** make the file creation mode be exactly m ignoring the umask.
   24847 **
   24848 ** The m parameter will be non-zero only when creating -wal, -journal,
   24849 ** and -shm files.  We want those files to have *exactly* the same
   24850 ** permissions as their original database, unadulterated by the umask.
   24851 ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
   24852 ** transaction crashes and leaves behind hot journals, then any
   24853 ** process that is able to write to the database will also be able to
   24854 ** recover the hot journals.
   24855 */
   24856 static int robust_open(const char *z, int f, mode_t m){
   24857   int fd;
   24858   mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
   24859   while(1){
   24860 #if defined(O_CLOEXEC)
   24861     fd = osOpen(z,f|O_CLOEXEC,m2);
   24862 #else
   24863     fd = osOpen(z,f,m2);
   24864 #endif
   24865     if( fd<0 ){
   24866       if( errno==EINTR ) continue;
   24867       break;
   24868     }
   24869     if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
   24870     osClose(fd);
   24871     sqlite3_log(SQLITE_WARNING,
   24872                 "attempt to open \"%s\" as file descriptor %d", z, fd);
   24873     fd = -1;
   24874     if( osOpen("/dev/null", f, m)<0 ) break;
   24875   }
   24876   if( fd>=0 ){
   24877     if( m!=0 ){
   24878       struct stat statbuf;
   24879       if( osFstat(fd, &statbuf)==0
   24880        && statbuf.st_size==0
   24881        && (statbuf.st_mode&0777)!=m
   24882       ){
   24883         osFchmod(fd, m);
   24884       }
   24885     }
   24886 #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
   24887     osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
   24888 #endif
   24889   }
   24890   return fd;
   24891 }
   24892 
   24893 /*
   24894 ** Helper functions to obtain and relinquish the global mutex. The
   24895 ** global mutex is used to protect the unixInodeInfo and
   24896 ** vxworksFileId objects used by this file, all of which may be
   24897 ** shared by multiple threads.
   24898 **
   24899 ** Function unixMutexHeld() is used to assert() that the global mutex
   24900 ** is held when required. This function is only used as part of assert()
   24901 ** statements. e.g.
   24902 **
   24903 **   unixEnterMutex()
   24904 **     assert( unixMutexHeld() );
   24905 **   unixEnterLeave()
   24906 */
   24907 static void unixEnterMutex(void){
   24908   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   24909 }
   24910 static void unixLeaveMutex(void){
   24911   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   24912 }
   24913 #ifdef SQLITE_DEBUG
   24914 static int unixMutexHeld(void) {
   24915   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   24916 }
   24917 #endif
   24918 
   24919 
   24920 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
   24921 /*
   24922 ** Helper function for printing out trace information from debugging
   24923 ** binaries. This returns the string represetation of the supplied
   24924 ** integer lock-type.
   24925 */
   24926 static const char *azFileLock(int eFileLock){
   24927   switch( eFileLock ){
   24928     case NO_LOCK: return "NONE";
   24929     case SHARED_LOCK: return "SHARED";
   24930     case RESERVED_LOCK: return "RESERVED";
   24931     case PENDING_LOCK: return "PENDING";
   24932     case EXCLUSIVE_LOCK: return "EXCLUSIVE";
   24933   }
   24934   return "ERROR";
   24935 }
   24936 #endif
   24937 
   24938 #ifdef SQLITE_LOCK_TRACE
   24939 /*
   24940 ** Print out information about all locking operations.
   24941 **
   24942 ** This routine is used for troubleshooting locks on multithreaded
   24943 ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
   24944 ** command-line option on the compiler.  This code is normally
   24945 ** turned off.
   24946 */
   24947 static int lockTrace(int fd, int op, struct flock *p){
   24948   char *zOpName, *zType;
   24949   int s;
   24950   int savedErrno;
   24951   if( op==F_GETLK ){
   24952     zOpName = "GETLK";
   24953   }else if( op==F_SETLK ){
   24954     zOpName = "SETLK";
   24955   }else{
   24956     s = osFcntl(fd, op, p);
   24957     sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
   24958     return s;
   24959   }
   24960   if( p->l_type==F_RDLCK ){
   24961     zType = "RDLCK";
   24962   }else if( p->l_type==F_WRLCK ){
   24963     zType = "WRLCK";
   24964   }else if( p->l_type==F_UNLCK ){
   24965     zType = "UNLCK";
   24966   }else{
   24967     assert( 0 );
   24968   }
   24969   assert( p->l_whence==SEEK_SET );
   24970   s = osFcntl(fd, op, p);
   24971   savedErrno = errno;
   24972   sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
   24973      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
   24974      (int)p->l_pid, s);
   24975   if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
   24976     struct flock l2;
   24977     l2 = *p;
   24978     osFcntl(fd, F_GETLK, &l2);
   24979     if( l2.l_type==F_RDLCK ){
   24980       zType = "RDLCK";
   24981     }else if( l2.l_type==F_WRLCK ){
   24982       zType = "WRLCK";
   24983     }else if( l2.l_type==F_UNLCK ){
   24984       zType = "UNLCK";
   24985     }else{
   24986       assert( 0 );
   24987     }
   24988     sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
   24989        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
   24990   }
   24991   errno = savedErrno;
   24992   return s;
   24993 }
   24994 #undef osFcntl
   24995 #define osFcntl lockTrace
   24996 #endif /* SQLITE_LOCK_TRACE */
   24997 
   24998 /*
   24999 ** Retry ftruncate() calls that fail due to EINTR
   25000 */
   25001 static int robust_ftruncate(int h, sqlite3_int64 sz){
   25002   int rc;
   25003   do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
   25004   return rc;
   25005 }
   25006 
   25007 /*
   25008 ** This routine translates a standard POSIX errno code into something
   25009 ** useful to the clients of the sqlite3 functions.  Specifically, it is
   25010 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
   25011 ** and a variety of "please close the file descriptor NOW" errors into
   25012 ** SQLITE_IOERR
   25013 **
   25014 ** Errors during initialization of locks, or file system support for locks,
   25015 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
   25016 */
   25017 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
   25018   switch (posixError) {
   25019 #if 0
   25020   /* At one point this code was not commented out. In theory, this branch
   25021   ** should never be hit, as this function should only be called after
   25022   ** a locking-related function (i.e. fcntl()) has returned non-zero with
   25023   ** the value of errno as the first argument. Since a system call has failed,
   25024   ** errno should be non-zero.
   25025   **
   25026   ** Despite this, if errno really is zero, we still don't want to return
   25027   ** SQLITE_OK. The system call failed, and *some* SQLite error should be
   25028   ** propagated back to the caller. Commenting this branch out means errno==0
   25029   ** will be handled by the "default:" case below.
   25030   */
   25031   case 0:
   25032     return SQLITE_OK;
   25033 #endif
   25034 
   25035   case EAGAIN:
   25036   case ETIMEDOUT:
   25037   case EBUSY:
   25038   case EINTR:
   25039   case ENOLCK:
   25040     /* random NFS retry error, unless during file system support
   25041      * introspection, in which it actually means what it says */
   25042     return SQLITE_BUSY;
   25043 
   25044   case EACCES:
   25045     /* EACCES is like EAGAIN during locking operations, but not any other time*/
   25046     if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
   25047         (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
   25048         (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
   25049         (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
   25050       return SQLITE_BUSY;
   25051     }
   25052     /* else fall through */
   25053   case EPERM:
   25054     return SQLITE_PERM;
   25055 
   25056 #if EOPNOTSUPP!=ENOTSUP
   25057   case EOPNOTSUPP:
   25058     /* something went terribly awry, unless during file system support
   25059      * introspection, in which it actually means what it says */
   25060 #endif
   25061 #ifdef ENOTSUP
   25062   case ENOTSUP:
   25063     /* invalid fd, unless during file system support introspection, in which
   25064      * it actually means what it says */
   25065 #endif
   25066   case EIO:
   25067   case EBADF:
   25068   case EINVAL:
   25069   case ENOTCONN:
   25070   case ENODEV:
   25071   case ENXIO:
   25072   case ENOENT:
   25073 #ifdef ESTALE                     /* ESTALE is not defined on Interix systems */
   25074   case ESTALE:
   25075 #endif
   25076   case ENOSYS:
   25077     /* these should force the client to close the file and reconnect */
   25078 
   25079   default:
   25080     return sqliteIOErr;
   25081   }
   25082 }
   25083 
   25084 
   25085 /******************************************************************************
   25086 ****************** Begin Unique File ID Utility Used By VxWorks ***************
   25087 **
   25088 ** On most versions of unix, we can get a unique ID for a file by concatenating
   25089 ** the device number and the inode number.  But this does not work on VxWorks.
   25090 ** On VxWorks, a unique file id must be based on the canonical filename.
   25091 **
   25092 ** A pointer to an instance of the following structure can be used as a
   25093 ** unique file ID in VxWorks.  Each instance of this structure contains
   25094 ** a copy of the canonical filename.  There is also a reference count.
   25095 ** The structure is reclaimed when the number of pointers to it drops to
   25096 ** zero.
   25097 **
   25098 ** There are never very many files open at one time and lookups are not
   25099 ** a performance-critical path, so it is sufficient to put these
   25100 ** structures on a linked list.
   25101 */
   25102 struct vxworksFileId {
   25103   struct vxworksFileId *pNext;  /* Next in a list of them all */
   25104   int nRef;                     /* Number of references to this one */
   25105   int nName;                    /* Length of the zCanonicalName[] string */
   25106   char *zCanonicalName;         /* Canonical filename */
   25107 };
   25108 
   25109 #if OS_VXWORKS
   25110 /*
   25111 ** All unique filenames are held on a linked list headed by this
   25112 ** variable:
   25113 */
   25114 static struct vxworksFileId *vxworksFileList = 0;
   25115 
   25116 /*
   25117 ** Simplify a filename into its canonical form
   25118 ** by making the following changes:
   25119 **
   25120 **  * removing any trailing and duplicate /
   25121 **  * convert /./ into just /
   25122 **  * convert /A/../ where A is any simple name into just /
   25123 **
   25124 ** Changes are made in-place.  Return the new name length.
   25125 **
   25126 ** The original filename is in z[0..n-1].  Return the number of
   25127 ** characters in the simplified name.
   25128 */
   25129 static int vxworksSimplifyName(char *z, int n){
   25130   int i, j;
   25131   while( n>1 && z[n-1]=='/' ){ n--; }
   25132   for(i=j=0; i<n; i++){
   25133     if( z[i]=='/' ){
   25134       if( z[i+1]=='/' ) continue;
   25135       if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
   25136         i += 1;
   25137         continue;
   25138       }
   25139       if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
   25140         while( j>0 && z[j-1]!='/' ){ j--; }
   25141         if( j>0 ){ j--; }
   25142         i += 2;
   25143         continue;
   25144       }
   25145     }
   25146     z[j++] = z[i];
   25147   }
   25148   z[j] = 0;
   25149   return j;
   25150 }
   25151 
   25152 /*
   25153 ** Find a unique file ID for the given absolute pathname.  Return
   25154 ** a pointer to the vxworksFileId object.  This pointer is the unique
   25155 ** file ID.
   25156 **
   25157 ** The nRef field of the vxworksFileId object is incremented before
   25158 ** the object is returned.  A new vxworksFileId object is created
   25159 ** and added to the global list if necessary.
   25160 **
   25161 ** If a memory allocation error occurs, return NULL.
   25162 */
   25163 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
   25164   struct vxworksFileId *pNew;         /* search key and new file ID */
   25165   struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
   25166   int n;                              /* Length of zAbsoluteName string */
   25167 
   25168   assert( zAbsoluteName[0]=='/' );
   25169   n = (int)strlen(zAbsoluteName);
   25170   pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
   25171   if( pNew==0 ) return 0;
   25172   pNew->zCanonicalName = (char*)&pNew[1];
   25173   memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
   25174   n = vxworksSimplifyName(pNew->zCanonicalName, n);
   25175 
   25176   /* Search for an existing entry that matching the canonical name.
   25177   ** If found, increment the reference count and return a pointer to
   25178   ** the existing file ID.
   25179   */
   25180   unixEnterMutex();
   25181   for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
   25182     if( pCandidate->nName==n
   25183      && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
   25184     ){
   25185        sqlite3_free(pNew);
   25186        pCandidate->nRef++;
   25187        unixLeaveMutex();
   25188        return pCandidate;
   25189     }
   25190   }
   25191 
   25192   /* No match was found.  We will make a new file ID */
   25193   pNew->nRef = 1;
   25194   pNew->nName = n;
   25195   pNew->pNext = vxworksFileList;
   25196   vxworksFileList = pNew;
   25197   unixLeaveMutex();
   25198   return pNew;
   25199 }
   25200 
   25201 /*
   25202 ** Decrement the reference count on a vxworksFileId object.  Free
   25203 ** the object when the reference count reaches zero.
   25204 */
   25205 static void vxworksReleaseFileId(struct vxworksFileId *pId){
   25206   unixEnterMutex();
   25207   assert( pId->nRef>0 );
   25208   pId->nRef--;
   25209   if( pId->nRef==0 ){
   25210     struct vxworksFileId **pp;
   25211     for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
   25212     assert( *pp==pId );
   25213     *pp = pId->pNext;
   25214     sqlite3_free(pId);
   25215   }
   25216   unixLeaveMutex();
   25217 }
   25218 #endif /* OS_VXWORKS */
   25219 /*************** End of Unique File ID Utility Used By VxWorks ****************
   25220 ******************************************************************************/
   25221 
   25222 
   25223 /******************************************************************************
   25224 *************************** Posix Advisory Locking ****************************
   25225 **
   25226 ** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
   25227 ** section 6.5.2.2 lines 483 through 490 specify that when a process
   25228 ** sets or clears a lock, that operation overrides any prior locks set
   25229 ** by the same process.  It does not explicitly say so, but this implies
   25230 ** that it overrides locks set by the same process using a different
   25231 ** file descriptor.  Consider this test case:
   25232 **
   25233 **       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
   25234 **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
   25235 **
   25236 ** Suppose ./file1 and ./file2 are really the same file (because
   25237 ** one is a hard or symbolic link to the other) then if you set
   25238 ** an exclusive lock on fd1, then try to get an exclusive lock
   25239 ** on fd2, it works.  I would have expected the second lock to
   25240 ** fail since there was already a lock on the file due to fd1.
   25241 ** But not so.  Since both locks came from the same process, the
   25242 ** second overrides the first, even though they were on different
   25243 ** file descriptors opened on different file names.
   25244 **
   25245 ** This means that we cannot use POSIX locks to synchronize file access
   25246 ** among competing threads of the same process.  POSIX locks will work fine
   25247 ** to synchronize access for threads in separate processes, but not
   25248 ** threads within the same process.
   25249 **
   25250 ** To work around the problem, SQLite has to manage file locks internally
   25251 ** on its own.  Whenever a new database is opened, we have to find the
   25252 ** specific inode of the database file (the inode is determined by the
   25253 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
   25254 ** and check for locks already existing on that inode.  When locks are
   25255 ** created or removed, we have to look at our own internal record of the
   25256 ** locks to see if another thread has previously set a lock on that same
   25257 ** inode.
   25258 **
   25259 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
   25260 ** For VxWorks, we have to use the alternative unique ID system based on
   25261 ** canonical filename and implemented in the previous division.)
   25262 **
   25263 ** The sqlite3_file structure for POSIX is no longer just an integer file
   25264 ** descriptor.  It is now a structure that holds the integer file
   25265 ** descriptor and a pointer to a structure that describes the internal
   25266 ** locks on the corresponding inode.  There is one locking structure
   25267 ** per inode, so if the same inode is opened twice, both unixFile structures
   25268 ** point to the same locking structure.  The locking structure keeps
   25269 ** a reference count (so we will know when to delete it) and a "cnt"
   25270 ** field that tells us its internal lock status.  cnt==0 means the
   25271 ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
   25272 ** cnt>0 means there are cnt shared locks on the file.
   25273 **
   25274 ** Any attempt to lock or unlock a file first checks the locking
   25275 ** structure.  The fcntl() system call is only invoked to set a
   25276 ** POSIX lock if the internal lock structure transitions between
   25277 ** a locked and an unlocked state.
   25278 **
   25279 ** But wait:  there are yet more problems with POSIX advisory locks.
   25280 **
   25281 ** If you close a file descriptor that points to a file that has locks,
   25282 ** all locks on that file that are owned by the current process are
   25283 ** released.  To work around this problem, each unixInodeInfo object
   25284 ** maintains a count of the number of pending locks on tha inode.
   25285 ** When an attempt is made to close an unixFile, if there are
   25286 ** other unixFile open on the same inode that are holding locks, the call
   25287 ** to close() the file descriptor is deferred until all of the locks clear.
   25288 ** The unixInodeInfo structure keeps a list of file descriptors that need to
   25289 ** be closed and that list is walked (and cleared) when the last lock
   25290 ** clears.
   25291 **
   25292 ** Yet another problem:  LinuxThreads do not play well with posix locks.
   25293 **
   25294 ** Many older versions of linux use the LinuxThreads library which is
   25295 ** not posix compliant.  Under LinuxThreads, a lock created by thread
   25296 ** A cannot be modified or overridden by a different thread B.
   25297 ** Only thread A can modify the lock.  Locking behavior is correct
   25298 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
   25299 ** on linux - with NPTL a lock created by thread A can override locks
   25300 ** in thread B.  But there is no way to know at compile-time which
   25301 ** threading library is being used.  So there is no way to know at
   25302 ** compile-time whether or not thread A can override locks on thread B.
   25303 ** One has to do a run-time check to discover the behavior of the
   25304 ** current process.
   25305 **
   25306 ** SQLite used to support LinuxThreads.  But support for LinuxThreads
   25307 ** was dropped beginning with version 3.7.0.  SQLite will still work with
   25308 ** LinuxThreads provided that (1) there is no more than one connection
   25309 ** per database file in the same process and (2) database connections
   25310 ** do not move across threads.
   25311 */
   25312 
   25313 /*
   25314 ** An instance of the following structure serves as the key used
   25315 ** to locate a particular unixInodeInfo object.
   25316 */
   25317 struct unixFileId {
   25318   dev_t dev;                  /* Device number */
   25319 #if OS_VXWORKS
   25320   struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
   25321 #else
   25322   ino_t ino;                  /* Inode number */
   25323 #endif
   25324 };
   25325 
   25326 /*
   25327 ** An instance of the following structure is allocated for each open
   25328 ** inode.  Or, on LinuxThreads, there is one of these structures for
   25329 ** each inode opened by each thread.
   25330 **
   25331 ** A single inode can have multiple file descriptors, so each unixFile
   25332 ** structure contains a pointer to an instance of this object and this
   25333 ** object keeps a count of the number of unixFile pointing to it.
   25334 */
   25335 struct unixInodeInfo {
   25336   struct unixFileId fileId;       /* The lookup key */
   25337   int nShared;                    /* Number of SHARED locks held */
   25338   unsigned char eFileLock;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
   25339   unsigned char bProcessLock;     /* An exclusive process lock is held */
   25340   int nRef;                       /* Number of pointers to this structure */
   25341   unixShmNode *pShmNode;          /* Shared memory associated with this inode */
   25342   int nLock;                      /* Number of outstanding file locks */
   25343   UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
   25344   unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
   25345   unixInodeInfo *pPrev;           /*    .... doubly linked */
   25346 #if SQLITE_ENABLE_LOCKING_STYLE
   25347   unsigned long long sharedByte;  /* for AFP simulated shared lock */
   25348 #endif
   25349 #if OS_VXWORKS
   25350   sem_t *pSem;                    /* Named POSIX semaphore */
   25351   char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
   25352 #endif
   25353 };
   25354 
   25355 /*
   25356 ** A lists of all unixInodeInfo objects.
   25357 */
   25358 static unixInodeInfo *inodeList = 0;
   25359 
   25360 /*
   25361 **
   25362 ** This function - unixLogError_x(), is only ever called via the macro
   25363 ** unixLogError().
   25364 **
   25365 ** It is invoked after an error occurs in an OS function and errno has been
   25366 ** set. It logs a message using sqlite3_log() containing the current value of
   25367 ** errno and, if possible, the human-readable equivalent from strerror() or
   25368 ** strerror_r().
   25369 **
   25370 ** The first argument passed to the macro should be the error code that
   25371 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
   25372 ** The two subsequent arguments should be the name of the OS function that
   25373 ** failed (e.g. "unlink", "open") and the associated file-system path,
   25374 ** if any.
   25375 */
   25376 #define unixLogError(a,b,c)     unixLogErrorAtLine(a,b,c,__LINE__)
   25377 static int unixLogErrorAtLine(
   25378   int errcode,                    /* SQLite error code */
   25379   const char *zFunc,              /* Name of OS function that failed */
   25380   const char *zPath,              /* File path associated with error */
   25381   int iLine                       /* Source line number where error occurred */
   25382 ){
   25383   char *zErr;                     /* Message from strerror() or equivalent */
   25384   int iErrno = errno;             /* Saved syscall error number */
   25385 
   25386   /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
   25387   ** the strerror() function to obtain the human-readable error message
   25388   ** equivalent to errno. Otherwise, use strerror_r().
   25389   */
   25390 #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
   25391   char aErr[80];
   25392   memset(aErr, 0, sizeof(aErr));
   25393   zErr = aErr;
   25394 
   25395   /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
   25396   ** assume that the system provides the GNU version of strerror_r() that
   25397   ** returns a pointer to a buffer containing the error message. That pointer
   25398   ** may point to aErr[], or it may point to some static storage somewhere.
   25399   ** Otherwise, assume that the system provides the POSIX version of
   25400   ** strerror_r(), which always writes an error message into aErr[].
   25401   **
   25402   ** If the code incorrectly assumes that it is the POSIX version that is
   25403   ** available, the error message will often be an empty string. Not a
   25404   ** huge problem. Incorrectly concluding that the GNU version is available
   25405   ** could lead to a segfault though.
   25406   */
   25407 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
   25408   zErr =
   25409 # endif
   25410   strerror_r(iErrno, aErr, sizeof(aErr)-1);
   25411 
   25412 #elif SQLITE_THREADSAFE
   25413   /* This is a threadsafe build, but strerror_r() is not available. */
   25414   zErr = "";
   25415 #else
   25416   /* Non-threadsafe build, use strerror(). */
   25417   zErr = strerror(iErrno);
   25418 #endif
   25419 
   25420   if( zPath==0 ) zPath = "";
   25421   sqlite3_log(errcode,
   25422       "os_unix.c:%d: (%d) %s(%s) - %s",
   25423       iLine, iErrno, zFunc, zPath, zErr
   25424   );
   25425 
   25426   return errcode;
   25427 }
   25428 
   25429 /*
   25430 ** Close a file descriptor.
   25431 **
   25432 ** We assume that close() almost always works, since it is only in a
   25433 ** very sick application or on a very sick platform that it might fail.
   25434 ** If it does fail, simply leak the file descriptor, but do log the
   25435 ** error.
   25436 **
   25437 ** Note that it is not safe to retry close() after EINTR since the
   25438 ** file descriptor might have already been reused by another thread.
   25439 ** So we don't even try to recover from an EINTR.  Just log the error
   25440 ** and move on.
   25441 */
   25442 static void robust_close(unixFile *pFile, int h, int lineno){
   25443   if( osClose(h) ){
   25444     unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
   25445                        pFile ? pFile->zPath : 0, lineno);
   25446   }
   25447 }
   25448 
   25449 /*
   25450 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
   25451 */
   25452 static void closePendingFds(unixFile *pFile){
   25453   unixInodeInfo *pInode = pFile->pInode;
   25454   UnixUnusedFd *p;
   25455   UnixUnusedFd *pNext;
   25456   for(p=pInode->pUnused; p; p=pNext){
   25457     pNext = p->pNext;
   25458     robust_close(pFile, p->fd, __LINE__);
   25459     sqlite3_free(p);
   25460   }
   25461   pInode->pUnused = 0;
   25462 }
   25463 
   25464 /*
   25465 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
   25466 **
   25467 ** The mutex entered using the unixEnterMutex() function must be held
   25468 ** when this function is called.
   25469 */
   25470 static void releaseInodeInfo(unixFile *pFile){
   25471   unixInodeInfo *pInode = pFile->pInode;
   25472   assert( unixMutexHeld() );
   25473   if( ALWAYS(pInode) ){
   25474     pInode->nRef--;
   25475     if( pInode->nRef==0 ){
   25476       assert( pInode->pShmNode==0 );
   25477       closePendingFds(pFile);
   25478       if( pInode->pPrev ){
   25479         assert( pInode->pPrev->pNext==pInode );
   25480         pInode->pPrev->pNext = pInode->pNext;
   25481       }else{
   25482         assert( inodeList==pInode );
   25483         inodeList = pInode->pNext;
   25484       }
   25485       if( pInode->pNext ){
   25486         assert( pInode->pNext->pPrev==pInode );
   25487         pInode->pNext->pPrev = pInode->pPrev;
   25488       }
   25489       sqlite3_free(pInode);
   25490     }
   25491   }
   25492 }
   25493 
   25494 /*
   25495 ** Given a file descriptor, locate the unixInodeInfo object that
   25496 ** describes that file descriptor.  Create a new one if necessary.  The
   25497 ** return value might be uninitialized if an error occurs.
   25498 **
   25499 ** The mutex entered using the unixEnterMutex() function must be held
   25500 ** when this function is called.
   25501 **
   25502 ** Return an appropriate error code.
   25503 */
   25504 static int findInodeInfo(
   25505   unixFile *pFile,               /* Unix file with file desc used in the key */
   25506   unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
   25507 ){
   25508   int rc;                        /* System call return code */
   25509   int fd;                        /* The file descriptor for pFile */
   25510   struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
   25511   struct stat statbuf;           /* Low-level file information */
   25512   unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
   25513 
   25514   assert( unixMutexHeld() );
   25515 
   25516   /* Get low-level information about the file that we can used to
   25517   ** create a unique name for the file.
   25518   */
   25519   fd = pFile->h;
   25520   rc = osFstat(fd, &statbuf);
   25521   if( rc!=0 ){
   25522     pFile->lastErrno = errno;
   25523 #ifdef EOVERFLOW
   25524     if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
   25525 #endif
   25526     return SQLITE_IOERR;
   25527   }
   25528 
   25529 #ifdef __APPLE__
   25530   /* On OS X on an msdos filesystem, the inode number is reported
   25531   ** incorrectly for zero-size files.  See ticket #3260.  To work
   25532   ** around this problem (we consider it a bug in OS X, not SQLite)
   25533   ** we always increase the file size to 1 by writing a single byte
   25534   ** prior to accessing the inode number.  The one byte written is
   25535   ** an ASCII 'S' character which also happens to be the first byte
   25536   ** in the header of every SQLite database.  In this way, if there
   25537   ** is a race condition such that another thread has already populated
   25538   ** the first page of the database, no damage is done.
   25539   */
   25540   if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
   25541     do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
   25542     if( rc!=1 ){
   25543       pFile->lastErrno = errno;
   25544       return SQLITE_IOERR;
   25545     }
   25546     rc = osFstat(fd, &statbuf);
   25547     if( rc!=0 ){
   25548       pFile->lastErrno = errno;
   25549       return SQLITE_IOERR;
   25550     }
   25551   }
   25552 #endif
   25553 
   25554   memset(&fileId, 0, sizeof(fileId));
   25555   fileId.dev = statbuf.st_dev;
   25556 #if OS_VXWORKS
   25557   fileId.pId = pFile->pId;
   25558 #else
   25559   fileId.ino = statbuf.st_ino;
   25560 #endif
   25561   pInode = inodeList;
   25562   while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
   25563     pInode = pInode->pNext;
   25564   }
   25565   if( pInode==0 ){
   25566     pInode = sqlite3_malloc( sizeof(*pInode) );
   25567     if( pInode==0 ){
   25568       return SQLITE_NOMEM;
   25569     }
   25570     memset(pInode, 0, sizeof(*pInode));
   25571     memcpy(&pInode->fileId, &fileId, sizeof(fileId));
   25572     pInode->nRef = 1;
   25573     pInode->pNext = inodeList;
   25574     pInode->pPrev = 0;
   25575     if( inodeList ) inodeList->pPrev = pInode;
   25576     inodeList = pInode;
   25577   }else{
   25578     pInode->nRef++;
   25579   }
   25580   *ppInode = pInode;
   25581   return SQLITE_OK;
   25582 }
   25583 
   25584 /*
   25585 ** Return TRUE if pFile has been renamed or unlinked since it was first opened.
   25586 */
   25587 static int fileHasMoved(unixFile *pFile){
   25588 #if OS_VXWORKS
   25589   return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
   25590 #else
   25591   struct stat buf;
   25592   return pFile->pInode!=0 &&
   25593       (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
   25594 #endif
   25595 }
   25596 
   25597 
   25598 /*
   25599 ** Check a unixFile that is a database.  Verify the following:
   25600 **
   25601 ** (1) There is exactly one hard link on the file
   25602 ** (2) The file is not a symbolic link
   25603 ** (3) The file has not been renamed or unlinked
   25604 **
   25605 ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
   25606 */
   25607 static void verifyDbFile(unixFile *pFile){
   25608   struct stat buf;
   25609   int rc;
   25610   if( pFile->ctrlFlags & UNIXFILE_WARNED ){
   25611     /* One or more of the following warnings have already been issued.  Do not
   25612     ** repeat them so as not to clutter the error log */
   25613     return;
   25614   }
   25615   rc = osFstat(pFile->h, &buf);
   25616   if( rc!=0 ){
   25617     sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
   25618     pFile->ctrlFlags |= UNIXFILE_WARNED;
   25619     return;
   25620   }
   25621   if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
   25622     sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
   25623     pFile->ctrlFlags |= UNIXFILE_WARNED;
   25624     return;
   25625   }
   25626   if( buf.st_nlink>1 ){
   25627     sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
   25628     pFile->ctrlFlags |= UNIXFILE_WARNED;
   25629     return;
   25630   }
   25631   if( fileHasMoved(pFile) ){
   25632     sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
   25633     pFile->ctrlFlags |= UNIXFILE_WARNED;
   25634     return;
   25635   }
   25636 }
   25637 
   25638 
   25639 /*
   25640 ** This routine checks if there is a RESERVED lock held on the specified
   25641 ** file by this or any other process. If such a lock is held, set *pResOut
   25642 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   25643 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   25644 */
   25645 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
   25646   int rc = SQLITE_OK;
   25647   int reserved = 0;
   25648   unixFile *pFile = (unixFile*)id;
   25649 
   25650   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   25651 
   25652   assert( pFile );
   25653   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
   25654 
   25655   /* Check if a thread in this process holds such a lock */
   25656   if( pFile->pInode->eFileLock>SHARED_LOCK ){
   25657     reserved = 1;
   25658   }
   25659 
   25660   /* Otherwise see if some other process holds it.
   25661   */
   25662 #ifndef __DJGPP__
   25663   if( !reserved && !pFile->pInode->bProcessLock ){
   25664     struct flock lock;
   25665     lock.l_whence = SEEK_SET;
   25666     lock.l_start = RESERVED_BYTE;
   25667     lock.l_len = 1;
   25668     lock.l_type = F_WRLCK;
   25669     if( osFcntl(pFile->h, F_GETLK, &lock) ){
   25670       rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
   25671       pFile->lastErrno = errno;
   25672     } else if( lock.l_type!=F_UNLCK ){
   25673       reserved = 1;
   25674     }
   25675   }
   25676 #endif
   25677 
   25678   unixLeaveMutex();
   25679   OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
   25680 
   25681   *pResOut = reserved;
   25682   return rc;
   25683 }
   25684 
   25685 /*
   25686 ** Attempt to set a system-lock on the file pFile.  The lock is
   25687 ** described by pLock.
   25688 **
   25689 ** If the pFile was opened read/write from unix-excl, then the only lock
   25690 ** ever obtained is an exclusive lock, and it is obtained exactly once
   25691 ** the first time any lock is attempted.  All subsequent system locking
   25692 ** operations become no-ops.  Locking operations still happen internally,
   25693 ** in order to coordinate access between separate database connections
   25694 ** within this process, but all of that is handled in memory and the
   25695 ** operating system does not participate.
   25696 **
   25697 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
   25698 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
   25699 ** and is read-only.
   25700 **
   25701 ** Zero is returned if the call completes successfully, or -1 if a call
   25702 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
   25703 */
   25704 static int unixFileLock(unixFile *pFile, struct flock *pLock){
   25705   int rc;
   25706   unixInodeInfo *pInode = pFile->pInode;
   25707   assert( unixMutexHeld() );
   25708   assert( pInode!=0 );
   25709   if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
   25710    && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
   25711   ){
   25712     if( pInode->bProcessLock==0 ){
   25713       struct flock lock;
   25714       assert( pInode->nLock==0 );
   25715       lock.l_whence = SEEK_SET;
   25716       lock.l_start = SHARED_FIRST;
   25717       lock.l_len = SHARED_SIZE;
   25718       lock.l_type = F_WRLCK;
   25719       rc = osFcntl(pFile->h, F_SETLK, &lock);
   25720       if( rc<0 ) return rc;
   25721       pInode->bProcessLock = 1;
   25722       pInode->nLock++;
   25723     }else{
   25724       rc = 0;
   25725     }
   25726   }else{
   25727     rc = osFcntl(pFile->h, F_SETLK, pLock);
   25728   }
   25729   return rc;
   25730 }
   25731 
   25732 /*
   25733 ** Lock the file with the lock specified by parameter eFileLock - one
   25734 ** of the following:
   25735 **
   25736 **     (1) SHARED_LOCK
   25737 **     (2) RESERVED_LOCK
   25738 **     (3) PENDING_LOCK
   25739 **     (4) EXCLUSIVE_LOCK
   25740 **
   25741 ** Sometimes when requesting one lock state, additional lock states
   25742 ** are inserted in between.  The locking might fail on one of the later
   25743 ** transitions leaving the lock state different from what it started but
   25744 ** still short of its goal.  The following chart shows the allowed
   25745 ** transitions and the inserted intermediate states:
   25746 **
   25747 **    UNLOCKED -> SHARED
   25748 **    SHARED -> RESERVED
   25749 **    SHARED -> (PENDING) -> EXCLUSIVE
   25750 **    RESERVED -> (PENDING) -> EXCLUSIVE
   25751 **    PENDING -> EXCLUSIVE
   25752 **
   25753 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   25754 ** routine to lower a locking level.
   25755 */
   25756 static int unixLock(sqlite3_file *id, int eFileLock){
   25757   /* The following describes the implementation of the various locks and
   25758   ** lock transitions in terms of the POSIX advisory shared and exclusive
   25759   ** lock primitives (called read-locks and write-locks below, to avoid
   25760   ** confusion with SQLite lock names). The algorithms are complicated
   25761   ** slightly in order to be compatible with windows systems simultaneously
   25762   ** accessing the same database file, in case that is ever required.
   25763   **
   25764   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
   25765   ** byte', each single bytes at well known offsets, and the 'shared byte
   25766   ** range', a range of 510 bytes at a well known offset.
   25767   **
   25768   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
   25769   ** byte'.  If this is successful, a random byte from the 'shared byte
   25770   ** range' is read-locked and the lock on the 'pending byte' released.
   25771   **
   25772   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
   25773   ** A RESERVED lock is implemented by grabbing a write-lock on the
   25774   ** 'reserved byte'.
   25775   **
   25776   ** A process may only obtain a PENDING lock after it has obtained a
   25777   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
   25778   ** on the 'pending byte'. This ensures that no new SHARED locks can be
   25779   ** obtained, but existing SHARED locks are allowed to persist. A process
   25780   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
   25781   ** This property is used by the algorithm for rolling back a journal file
   25782   ** after a crash.
   25783   **
   25784   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
   25785   ** implemented by obtaining a write-lock on the entire 'shared byte
   25786   ** range'. Since all other locks require a read-lock on one of the bytes
   25787   ** within this range, this ensures that no other locks are held on the
   25788   ** database.
   25789   **
   25790   ** The reason a single byte cannot be used instead of the 'shared byte
   25791   ** range' is that some versions of windows do not support read-locks. By
   25792   ** locking a random byte from a range, concurrent SHARED locks may exist
   25793   ** even if the locking primitive used is always a write-lock.
   25794   */
   25795   int rc = SQLITE_OK;
   25796   unixFile *pFile = (unixFile*)id;
   25797   unixInodeInfo *pInode;
   25798   struct flock lock;
   25799   int tErrno = 0;
   25800 
   25801   assert( pFile );
   25802   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
   25803       azFileLock(eFileLock), azFileLock(pFile->eFileLock),
   25804       azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
   25805 
   25806   /* If there is already a lock of this type or more restrictive on the
   25807   ** unixFile, do nothing. Don't use the end_lock: exit path, as
   25808   ** unixEnterMutex() hasn't been called yet.
   25809   */
   25810   if( pFile->eFileLock>=eFileLock ){
   25811     OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
   25812             azFileLock(eFileLock)));
   25813     return SQLITE_OK;
   25814   }
   25815 
   25816   /* Make sure the locking sequence is correct.
   25817   **  (1) We never move from unlocked to anything higher than shared lock.
   25818   **  (2) SQLite never explicitly requests a pendig lock.
   25819   **  (3) A shared lock is always held when a reserve lock is requested.
   25820   */
   25821   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
   25822   assert( eFileLock!=PENDING_LOCK );
   25823   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
   25824 
   25825   /* This mutex is needed because pFile->pInode is shared across threads
   25826   */
   25827   unixEnterMutex();
   25828   pInode = pFile->pInode;
   25829 
   25830   /* If some thread using this PID has a lock via a different unixFile*
   25831   ** handle that precludes the requested lock, return BUSY.
   25832   */
   25833   if( (pFile->eFileLock!=pInode->eFileLock &&
   25834           (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
   25835   ){
   25836     rc = SQLITE_BUSY;
   25837     goto end_lock;
   25838   }
   25839 
   25840   /* If a SHARED lock is requested, and some thread using this PID already
   25841   ** has a SHARED or RESERVED lock, then increment reference counts and
   25842   ** return SQLITE_OK.
   25843   */
   25844   if( eFileLock==SHARED_LOCK &&
   25845       (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
   25846     assert( eFileLock==SHARED_LOCK );
   25847     assert( pFile->eFileLock==0 );
   25848     assert( pInode->nShared>0 );
   25849     pFile->eFileLock = SHARED_LOCK;
   25850     pInode->nShared++;
   25851     pInode->nLock++;
   25852     goto end_lock;
   25853   }
   25854 
   25855 
   25856   /* A PENDING lock is needed before acquiring a SHARED lock and before
   25857   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
   25858   ** be released.
   25859   */
   25860   lock.l_len = 1L;
   25861   lock.l_whence = SEEK_SET;
   25862   if( eFileLock==SHARED_LOCK
   25863       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
   25864   ){
   25865     lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
   25866     lock.l_start = PENDING_BYTE;
   25867     if( unixFileLock(pFile, &lock) ){
   25868       tErrno = errno;
   25869       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   25870       if( rc!=SQLITE_BUSY ){
   25871         pFile->lastErrno = tErrno;
   25872       }
   25873       goto end_lock;
   25874     }
   25875   }
   25876 
   25877 
   25878   /* If control gets to this point, then actually go ahead and make
   25879   ** operating system calls for the specified lock.
   25880   */
   25881   if( eFileLock==SHARED_LOCK ){
   25882     assert( pInode->nShared==0 );
   25883     assert( pInode->eFileLock==0 );
   25884     assert( rc==SQLITE_OK );
   25885 
   25886     /* Now get the read-lock */
   25887     lock.l_start = SHARED_FIRST;
   25888     lock.l_len = SHARED_SIZE;
   25889     if( unixFileLock(pFile, &lock) ){
   25890       tErrno = errno;
   25891       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   25892     }
   25893 
   25894     /* Drop the temporary PENDING lock */
   25895     lock.l_start = PENDING_BYTE;
   25896     lock.l_len = 1L;
   25897     lock.l_type = F_UNLCK;
   25898     if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
   25899       /* This could happen with a network mount */
   25900       tErrno = errno;
   25901       rc = SQLITE_IOERR_UNLOCK;
   25902     }
   25903 
   25904     if( rc ){
   25905       if( rc!=SQLITE_BUSY ){
   25906         pFile->lastErrno = tErrno;
   25907       }
   25908       goto end_lock;
   25909     }else{
   25910       pFile->eFileLock = SHARED_LOCK;
   25911       pInode->nLock++;
   25912       pInode->nShared = 1;
   25913     }
   25914   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
   25915     /* We are trying for an exclusive lock but another thread in this
   25916     ** same process is still holding a shared lock. */
   25917     rc = SQLITE_BUSY;
   25918   }else{
   25919     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
   25920     ** assumed that there is a SHARED or greater lock on the file
   25921     ** already.
   25922     */
   25923     assert( 0!=pFile->eFileLock );
   25924     lock.l_type = F_WRLCK;
   25925 
   25926     assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
   25927     if( eFileLock==RESERVED_LOCK ){
   25928       lock.l_start = RESERVED_BYTE;
   25929       lock.l_len = 1L;
   25930     }else{
   25931       lock.l_start = SHARED_FIRST;
   25932       lock.l_len = SHARED_SIZE;
   25933     }
   25934 
   25935     if( unixFileLock(pFile, &lock) ){
   25936       tErrno = errno;
   25937       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   25938       if( rc!=SQLITE_BUSY ){
   25939         pFile->lastErrno = tErrno;
   25940       }
   25941     }
   25942   }
   25943 
   25944 
   25945 #ifdef SQLITE_DEBUG
   25946   /* Set up the transaction-counter change checking flags when
   25947   ** transitioning from a SHARED to a RESERVED lock.  The change
   25948   ** from SHARED to RESERVED marks the beginning of a normal
   25949   ** write operation (not a hot journal rollback).
   25950   */
   25951   if( rc==SQLITE_OK
   25952    && pFile->eFileLock<=SHARED_LOCK
   25953    && eFileLock==RESERVED_LOCK
   25954   ){
   25955     pFile->transCntrChng = 0;
   25956     pFile->dbUpdate = 0;
   25957     pFile->inNormalWrite = 1;
   25958   }
   25959 #endif
   25960 
   25961 
   25962   if( rc==SQLITE_OK ){
   25963     pFile->eFileLock = eFileLock;
   25964     pInode->eFileLock = eFileLock;
   25965   }else if( eFileLock==EXCLUSIVE_LOCK ){
   25966     pFile->eFileLock = PENDING_LOCK;
   25967     pInode->eFileLock = PENDING_LOCK;
   25968   }
   25969 
   25970 end_lock:
   25971   unixLeaveMutex();
   25972   OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
   25973       rc==SQLITE_OK ? "ok" : "failed"));
   25974   return rc;
   25975 }
   25976 
   25977 /*
   25978 ** Add the file descriptor used by file handle pFile to the corresponding
   25979 ** pUnused list.
   25980 */
   25981 static void setPendingFd(unixFile *pFile){
   25982   unixInodeInfo *pInode = pFile->pInode;
   25983   UnixUnusedFd *p = pFile->pUnused;
   25984   p->pNext = pInode->pUnused;
   25985   pInode->pUnused = p;
   25986   pFile->h = -1;
   25987   pFile->pUnused = 0;
   25988 }
   25989 
   25990 /*
   25991 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   25992 ** must be either NO_LOCK or SHARED_LOCK.
   25993 **
   25994 ** If the locking level of the file descriptor is already at or below
   25995 ** the requested locking level, this routine is a no-op.
   25996 **
   25997 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
   25998 ** the byte range is divided into 2 parts and the first part is unlocked then
   25999 ** set to a read lock, then the other part is simply unlocked.  This works
   26000 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
   26001 ** remove the write lock on a region when a read lock is set.
   26002 */
   26003 static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
   26004   unixFile *pFile = (unixFile*)id;
   26005   unixInodeInfo *pInode;
   26006   struct flock lock;
   26007   int rc = SQLITE_OK;
   26008 
   26009   assert( pFile );
   26010   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
   26011       pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
   26012       getpid()));
   26013 
   26014   assert( eFileLock<=SHARED_LOCK );
   26015   if( pFile->eFileLock<=eFileLock ){
   26016     return SQLITE_OK;
   26017   }
   26018   unixEnterMutex();
   26019   pInode = pFile->pInode;
   26020   assert( pInode->nShared!=0 );
   26021   if( pFile->eFileLock>SHARED_LOCK ){
   26022     assert( pInode->eFileLock==pFile->eFileLock );
   26023 
   26024 #ifdef SQLITE_DEBUG
   26025     /* When reducing a lock such that other processes can start
   26026     ** reading the database file again, make sure that the
   26027     ** transaction counter was updated if any part of the database
   26028     ** file changed.  If the transaction counter is not updated,
   26029     ** other connections to the same file might not realize that
   26030     ** the file has changed and hence might not know to flush their
   26031     ** cache.  The use of a stale cache can lead to database corruption.
   26032     */
   26033     pFile->inNormalWrite = 0;
   26034 #endif
   26035 
   26036     /* downgrading to a shared lock on NFS involves clearing the write lock
   26037     ** before establishing the readlock - to avoid a race condition we downgrade
   26038     ** the lock in 2 blocks, so that part of the range will be covered by a
   26039     ** write lock until the rest is covered by a read lock:
   26040     **  1:   [WWWWW]
   26041     **  2:   [....W]
   26042     **  3:   [RRRRW]
   26043     **  4:   [RRRR.]
   26044     */
   26045     if( eFileLock==SHARED_LOCK ){
   26046 
   26047 #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
   26048       (void)handleNFSUnlock;
   26049       assert( handleNFSUnlock==0 );
   26050 #endif
   26051 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   26052       if( handleNFSUnlock ){
   26053         int tErrno;               /* Error code from system call errors */
   26054         off_t divSize = SHARED_SIZE - 1;
   26055 
   26056         lock.l_type = F_UNLCK;
   26057         lock.l_whence = SEEK_SET;
   26058         lock.l_start = SHARED_FIRST;
   26059         lock.l_len = divSize;
   26060         if( unixFileLock(pFile, &lock)==(-1) ){
   26061           tErrno = errno;
   26062           rc = SQLITE_IOERR_UNLOCK;
   26063           if( IS_LOCK_ERROR(rc) ){
   26064             pFile->lastErrno = tErrno;
   26065           }
   26066           goto end_unlock;
   26067         }
   26068         lock.l_type = F_RDLCK;
   26069         lock.l_whence = SEEK_SET;
   26070         lock.l_start = SHARED_FIRST;
   26071         lock.l_len = divSize;
   26072         if( unixFileLock(pFile, &lock)==(-1) ){
   26073           tErrno = errno;
   26074           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
   26075           if( IS_LOCK_ERROR(rc) ){
   26076             pFile->lastErrno = tErrno;
   26077           }
   26078           goto end_unlock;
   26079         }
   26080         lock.l_type = F_UNLCK;
   26081         lock.l_whence = SEEK_SET;
   26082         lock.l_start = SHARED_FIRST+divSize;
   26083         lock.l_len = SHARED_SIZE-divSize;
   26084         if( unixFileLock(pFile, &lock)==(-1) ){
   26085           tErrno = errno;
   26086           rc = SQLITE_IOERR_UNLOCK;
   26087           if( IS_LOCK_ERROR(rc) ){
   26088             pFile->lastErrno = tErrno;
   26089           }
   26090           goto end_unlock;
   26091         }
   26092       }else
   26093 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
   26094       {
   26095         lock.l_type = F_RDLCK;
   26096         lock.l_whence = SEEK_SET;
   26097         lock.l_start = SHARED_FIRST;
   26098         lock.l_len = SHARED_SIZE;
   26099         if( unixFileLock(pFile, &lock) ){
   26100           /* In theory, the call to unixFileLock() cannot fail because another
   26101           ** process is holding an incompatible lock. If it does, this
   26102           ** indicates that the other process is not following the locking
   26103           ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
   26104           ** SQLITE_BUSY would confuse the upper layer (in practice it causes
   26105           ** an assert to fail). */
   26106           rc = SQLITE_IOERR_RDLOCK;
   26107           pFile->lastErrno = errno;
   26108           goto end_unlock;
   26109         }
   26110       }
   26111     }
   26112     lock.l_type = F_UNLCK;
   26113     lock.l_whence = SEEK_SET;
   26114     lock.l_start = PENDING_BYTE;
   26115     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
   26116     if( unixFileLock(pFile, &lock)==0 ){
   26117       pInode->eFileLock = SHARED_LOCK;
   26118     }else{
   26119       rc = SQLITE_IOERR_UNLOCK;
   26120       pFile->lastErrno = errno;
   26121       goto end_unlock;
   26122     }
   26123   }
   26124   if( eFileLock==NO_LOCK ){
   26125     /* Decrement the shared lock counter.  Release the lock using an
   26126     ** OS call only when all threads in this same process have released
   26127     ** the lock.
   26128     */
   26129     pInode->nShared--;
   26130     if( pInode->nShared==0 ){
   26131       lock.l_type = F_UNLCK;
   26132       lock.l_whence = SEEK_SET;
   26133       lock.l_start = lock.l_len = 0L;
   26134       if( unixFileLock(pFile, &lock)==0 ){
   26135         pInode->eFileLock = NO_LOCK;
   26136       }else{
   26137         rc = SQLITE_IOERR_UNLOCK;
   26138         pFile->lastErrno = errno;
   26139         pInode->eFileLock = NO_LOCK;
   26140         pFile->eFileLock = NO_LOCK;
   26141       }
   26142     }
   26143 
   26144     /* Decrement the count of locks against this same file.  When the
   26145     ** count reaches zero, close any other file descriptors whose close
   26146     ** was deferred because of outstanding locks.
   26147     */
   26148     pInode->nLock--;
   26149     assert( pInode->nLock>=0 );
   26150     if( pInode->nLock==0 ){
   26151       closePendingFds(pFile);
   26152     }
   26153   }
   26154 
   26155 end_unlock:
   26156   unixLeaveMutex();
   26157   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
   26158   return rc;
   26159 }
   26160 
   26161 /*
   26162 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   26163 ** must be either NO_LOCK or SHARED_LOCK.
   26164 **
   26165 ** If the locking level of the file descriptor is already at or below
   26166 ** the requested locking level, this routine is a no-op.
   26167 */
   26168 static int unixUnlock(sqlite3_file *id, int eFileLock){
   26169 #if SQLITE_MAX_MMAP_SIZE>0
   26170   assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
   26171 #endif
   26172   return posixUnlock(id, eFileLock, 0);
   26173 }
   26174 
   26175 #if SQLITE_MAX_MMAP_SIZE>0
   26176 static int unixMapfile(unixFile *pFd, i64 nByte);
   26177 static void unixUnmapfile(unixFile *pFd);
   26178 #endif
   26179 
   26180 /*
   26181 ** This function performs the parts of the "close file" operation
   26182 ** common to all locking schemes. It closes the directory and file
   26183 ** handles, if they are valid, and sets all fields of the unixFile
   26184 ** structure to 0.
   26185 **
   26186 ** It is *not* necessary to hold the mutex when this routine is called,
   26187 ** even on VxWorks.  A mutex will be acquired on VxWorks by the
   26188 ** vxworksReleaseFileId() routine.
   26189 */
   26190 static int closeUnixFile(sqlite3_file *id){
   26191   unixFile *pFile = (unixFile*)id;
   26192 #if SQLITE_MAX_MMAP_SIZE>0
   26193   unixUnmapfile(pFile);
   26194 #endif
   26195   if( pFile->h>=0 ){
   26196     robust_close(pFile, pFile->h, __LINE__);
   26197     pFile->h = -1;
   26198   }
   26199 #if OS_VXWORKS
   26200   if( pFile->pId ){
   26201     if( pFile->ctrlFlags & UNIXFILE_DELETE ){
   26202       osUnlink(pFile->pId->zCanonicalName);
   26203     }
   26204     vxworksReleaseFileId(pFile->pId);
   26205     pFile->pId = 0;
   26206   }
   26207 #endif
   26208 #ifdef SQLITE_UNLINK_AFTER_CLOSE
   26209   if( pFile->ctrlFlags & UNIXFILE_DELETE ){
   26210     osUnlink(pFile->zPath);
   26211     sqlite3_free(*(char**)&pFile->zPath);
   26212     pFile->zPath = 0;
   26213   }
   26214 #endif
   26215   OSTRACE(("CLOSE   %-3d\n", pFile->h));
   26216   OpenCounter(-1);
   26217   sqlite3_free(pFile->pUnused);
   26218   memset(pFile, 0, sizeof(unixFile));
   26219   return SQLITE_OK;
   26220 }
   26221 
   26222 /*
   26223 ** Close a file.
   26224 */
   26225 static int unixClose(sqlite3_file *id){
   26226   int rc = SQLITE_OK;
   26227   unixFile *pFile = (unixFile *)id;
   26228   verifyDbFile(pFile);
   26229   unixUnlock(id, NO_LOCK);
   26230   unixEnterMutex();
   26231 
   26232   /* unixFile.pInode is always valid here. Otherwise, a different close
   26233   ** routine (e.g. nolockClose()) would be called instead.
   26234   */
   26235   assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
   26236   if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
   26237     /* If there are outstanding locks, do not actually close the file just
   26238     ** yet because that would clear those locks.  Instead, add the file
   26239     ** descriptor to pInode->pUnused list.  It will be automatically closed
   26240     ** when the last lock is cleared.
   26241     */
   26242     setPendingFd(pFile);
   26243   }
   26244   releaseInodeInfo(pFile);
   26245   rc = closeUnixFile(id);
   26246   unixLeaveMutex();
   26247   return rc;
   26248 }
   26249 
   26250 /************** End of the posix advisory lock implementation *****************
   26251 ******************************************************************************/
   26252 
   26253 /******************************************************************************
   26254 ****************************** No-op Locking **********************************
   26255 **
   26256 ** Of the various locking implementations available, this is by far the
   26257 ** simplest:  locking is ignored.  No attempt is made to lock the database
   26258 ** file for reading or writing.
   26259 **
   26260 ** This locking mode is appropriate for use on read-only databases
   26261 ** (ex: databases that are burned into CD-ROM, for example.)  It can
   26262 ** also be used if the application employs some external mechanism to
   26263 ** prevent simultaneous access of the same database by two or more
   26264 ** database connections.  But there is a serious risk of database
   26265 ** corruption if this locking mode is used in situations where multiple
   26266 ** database connections are accessing the same database file at the same
   26267 ** time and one or more of those connections are writing.
   26268 */
   26269 
   26270 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
   26271   UNUSED_PARAMETER(NotUsed);
   26272   *pResOut = 0;
   26273   return SQLITE_OK;
   26274 }
   26275 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
   26276   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   26277   return SQLITE_OK;
   26278 }
   26279 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
   26280   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   26281   return SQLITE_OK;
   26282 }
   26283 
   26284 /*
   26285 ** Close the file.
   26286 */
   26287 static int nolockClose(sqlite3_file *id) {
   26288   return closeUnixFile(id);
   26289 }
   26290 
   26291 /******************* End of the no-op lock implementation *********************
   26292 ******************************************************************************/
   26293 
   26294 /******************************************************************************
   26295 ************************* Begin dot-file Locking ******************************
   26296 **
   26297 ** The dotfile locking implementation uses the existence of separate lock
   26298 ** files (really a directory) to control access to the database.  This works
   26299 ** on just about every filesystem imaginable.  But there are serious downsides:
   26300 **
   26301 **    (1)  There is zero concurrency.  A single reader blocks all other
   26302 **         connections from reading or writing the database.
   26303 **
   26304 **    (2)  An application crash or power loss can leave stale lock files
   26305 **         sitting around that need to be cleared manually.
   26306 **
   26307 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
   26308 ** other locking strategy is available.
   26309 **
   26310 ** Dotfile locking works by creating a subdirectory in the same directory as
   26311 ** the database and with the same name but with a ".lock" extension added.
   26312 ** The existence of a lock directory implies an EXCLUSIVE lock.  All other
   26313 ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
   26314 */
   26315 
   26316 /*
   26317 ** The file suffix added to the data base filename in order to create the
   26318 ** lock directory.
   26319 */
   26320 #define DOTLOCK_SUFFIX ".lock"
   26321 
   26322 /*
   26323 ** This routine checks if there is a RESERVED lock held on the specified
   26324 ** file by this or any other process. If such a lock is held, set *pResOut
   26325 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   26326 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   26327 **
   26328 ** In dotfile locking, either a lock exists or it does not.  So in this
   26329 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
   26330 ** is held on the file and false if the file is unlocked.
   26331 */
   26332 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
   26333   int rc = SQLITE_OK;
   26334   int reserved = 0;
   26335   unixFile *pFile = (unixFile*)id;
   26336 
   26337   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   26338 
   26339   assert( pFile );
   26340 
   26341   /* Check if a thread in this process holds such a lock */
   26342   if( pFile->eFileLock>SHARED_LOCK ){
   26343     /* Either this connection or some other connection in the same process
   26344     ** holds a lock on the file.  No need to check further. */
   26345     reserved = 1;
   26346   }else{
   26347     /* The lock is held if and only if the lockfile exists */
   26348     const char *zLockFile = (const char*)pFile->lockingContext;
   26349     reserved = osAccess(zLockFile, 0)==0;
   26350   }
   26351   OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
   26352   *pResOut = reserved;
   26353   return rc;
   26354 }
   26355 
   26356 /*
   26357 ** Lock the file with the lock specified by parameter eFileLock - one
   26358 ** of the following:
   26359 **
   26360 **     (1) SHARED_LOCK
   26361 **     (2) RESERVED_LOCK
   26362 **     (3) PENDING_LOCK
   26363 **     (4) EXCLUSIVE_LOCK
   26364 **
   26365 ** Sometimes when requesting one lock state, additional lock states
   26366 ** are inserted in between.  The locking might fail on one of the later
   26367 ** transitions leaving the lock state different from what it started but
   26368 ** still short of its goal.  The following chart shows the allowed
   26369 ** transitions and the inserted intermediate states:
   26370 **
   26371 **    UNLOCKED -> SHARED
   26372 **    SHARED -> RESERVED
   26373 **    SHARED -> (PENDING) -> EXCLUSIVE
   26374 **    RESERVED -> (PENDING) -> EXCLUSIVE
   26375 **    PENDING -> EXCLUSIVE
   26376 **
   26377 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   26378 ** routine to lower a locking level.
   26379 **
   26380 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
   26381 ** But we track the other locking levels internally.
   26382 */
   26383 static int dotlockLock(sqlite3_file *id, int eFileLock) {
   26384   unixFile *pFile = (unixFile*)id;
   26385   char *zLockFile = (char *)pFile->lockingContext;
   26386   int rc = SQLITE_OK;
   26387 
   26388 
   26389   /* If we have any lock, then the lock file already exists.  All we have
   26390   ** to do is adjust our internal record of the lock level.
   26391   */
   26392   if( pFile->eFileLock > NO_LOCK ){
   26393     pFile->eFileLock = eFileLock;
   26394     /* Always update the timestamp on the old file */
   26395 #ifdef HAVE_UTIME
   26396     utime(zLockFile, NULL);
   26397 #else
   26398     utimes(zLockFile, NULL);
   26399 #endif
   26400     return SQLITE_OK;
   26401   }
   26402 
   26403   /* grab an exclusive lock */
   26404   rc = osMkdir(zLockFile, 0777);
   26405   if( rc<0 ){
   26406     /* failed to open/create the lock directory */
   26407     int tErrno = errno;
   26408     if( EEXIST == tErrno ){
   26409       rc = SQLITE_BUSY;
   26410     } else {
   26411       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   26412       if( IS_LOCK_ERROR(rc) ){
   26413         pFile->lastErrno = tErrno;
   26414       }
   26415     }
   26416     return rc;
   26417   }
   26418 
   26419   /* got it, set the type and return ok */
   26420   pFile->eFileLock = eFileLock;
   26421   return rc;
   26422 }
   26423 
   26424 /*
   26425 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   26426 ** must be either NO_LOCK or SHARED_LOCK.
   26427 **
   26428 ** If the locking level of the file descriptor is already at or below
   26429 ** the requested locking level, this routine is a no-op.
   26430 **
   26431 ** When the locking level reaches NO_LOCK, delete the lock file.
   26432 */
   26433 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
   26434   unixFile *pFile = (unixFile*)id;
   26435   char *zLockFile = (char *)pFile->lockingContext;
   26436   int rc;
   26437 
   26438   assert( pFile );
   26439   OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
   26440            pFile->eFileLock, getpid()));
   26441   assert( eFileLock<=SHARED_LOCK );
   26442 
   26443   /* no-op if possible */
   26444   if( pFile->eFileLock==eFileLock ){
   26445     return SQLITE_OK;
   26446   }
   26447 
   26448   /* To downgrade to shared, simply update our internal notion of the
   26449   ** lock state.  No need to mess with the file on disk.
   26450   */
   26451   if( eFileLock==SHARED_LOCK ){
   26452     pFile->eFileLock = SHARED_LOCK;
   26453     return SQLITE_OK;
   26454   }
   26455 
   26456   /* To fully unlock the database, delete the lock file */
   26457   assert( eFileLock==NO_LOCK );
   26458   rc = osRmdir(zLockFile);
   26459   if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
   26460   if( rc<0 ){
   26461     int tErrno = errno;
   26462     rc = 0;
   26463     if( ENOENT != tErrno ){
   26464       rc = SQLITE_IOERR_UNLOCK;
   26465     }
   26466     if( IS_LOCK_ERROR(rc) ){
   26467       pFile->lastErrno = tErrno;
   26468     }
   26469     return rc;
   26470   }
   26471   pFile->eFileLock = NO_LOCK;
   26472   return SQLITE_OK;
   26473 }
   26474 
   26475 /*
   26476 ** Close a file.  Make sure the lock has been released before closing.
   26477 */
   26478 static int dotlockClose(sqlite3_file *id) {
   26479   int rc = SQLITE_OK;
   26480   if( id ){
   26481     unixFile *pFile = (unixFile*)id;
   26482     dotlockUnlock(id, NO_LOCK);
   26483     sqlite3_free(pFile->lockingContext);
   26484     rc = closeUnixFile(id);
   26485   }
   26486   return rc;
   26487 }
   26488 /****************** End of the dot-file lock implementation *******************
   26489 ******************************************************************************/
   26490 
   26491 /******************************************************************************
   26492 ************************** Begin flock Locking ********************************
   26493 **
   26494 ** Use the flock() system call to do file locking.
   26495 **
   26496 ** flock() locking is like dot-file locking in that the various
   26497 ** fine-grain locking levels supported by SQLite are collapsed into
   26498 ** a single exclusive lock.  In other words, SHARED, RESERVED, and
   26499 ** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
   26500 ** still works when you do this, but concurrency is reduced since
   26501 ** only a single process can be reading the database at a time.
   26502 **
   26503 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
   26504 ** compiling for VXWORKS.
   26505 */
   26506 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
   26507 
   26508 /*
   26509 ** Retry flock() calls that fail with EINTR
   26510 */
   26511 #ifdef EINTR
   26512 static int robust_flock(int fd, int op){
   26513   int rc;
   26514   do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
   26515   return rc;
   26516 }
   26517 #else
   26518 # define robust_flock(a,b) flock(a,b)
   26519 #endif
   26520 
   26521 
   26522 /*
   26523 ** This routine checks if there is a RESERVED lock held on the specified
   26524 ** file by this or any other process. If such a lock is held, set *pResOut
   26525 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   26526 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   26527 */
   26528 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
   26529   int rc = SQLITE_OK;
   26530   int reserved = 0;
   26531   unixFile *pFile = (unixFile*)id;
   26532 
   26533   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   26534 
   26535   assert( pFile );
   26536 
   26537   /* Check if a thread in this process holds such a lock */
   26538   if( pFile->eFileLock>SHARED_LOCK ){
   26539     reserved = 1;
   26540   }
   26541 
   26542   /* Otherwise see if some other process holds it. */
   26543   if( !reserved ){
   26544     /* attempt to get the lock */
   26545     int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
   26546     if( !lrc ){
   26547       /* got the lock, unlock it */
   26548       lrc = robust_flock(pFile->h, LOCK_UN);
   26549       if ( lrc ) {
   26550         int tErrno = errno;
   26551         /* unlock failed with an error */
   26552         lrc = SQLITE_IOERR_UNLOCK;
   26553         if( IS_LOCK_ERROR(lrc) ){
   26554           pFile->lastErrno = tErrno;
   26555           rc = lrc;
   26556         }
   26557       }
   26558     } else {
   26559       int tErrno = errno;
   26560       reserved = 1;
   26561       /* someone else might have it reserved */
   26562       lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   26563       if( IS_LOCK_ERROR(lrc) ){
   26564         pFile->lastErrno = tErrno;
   26565         rc = lrc;
   26566       }
   26567     }
   26568   }
   26569   OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
   26570 
   26571 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
   26572   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
   26573     rc = SQLITE_OK;
   26574     reserved=1;
   26575   }
   26576 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
   26577   *pResOut = reserved;
   26578   return rc;
   26579 }
   26580 
   26581 /*
   26582 ** Lock the file with the lock specified by parameter eFileLock - one
   26583 ** of the following:
   26584 **
   26585 **     (1) SHARED_LOCK
   26586 **     (2) RESERVED_LOCK
   26587 **     (3) PENDING_LOCK
   26588 **     (4) EXCLUSIVE_LOCK
   26589 **
   26590 ** Sometimes when requesting one lock state, additional lock states
   26591 ** are inserted in between.  The locking might fail on one of the later
   26592 ** transitions leaving the lock state different from what it started but
   26593 ** still short of its goal.  The following chart shows the allowed
   26594 ** transitions and the inserted intermediate states:
   26595 **
   26596 **    UNLOCKED -> SHARED
   26597 **    SHARED -> RESERVED
   26598 **    SHARED -> (PENDING) -> EXCLUSIVE
   26599 **    RESERVED -> (PENDING) -> EXCLUSIVE
   26600 **    PENDING -> EXCLUSIVE
   26601 **
   26602 ** flock() only really support EXCLUSIVE locks.  We track intermediate
   26603 ** lock states in the sqlite3_file structure, but all locks SHARED or
   26604 ** above are really EXCLUSIVE locks and exclude all other processes from
   26605 ** access the file.
   26606 **
   26607 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   26608 ** routine to lower a locking level.
   26609 */
   26610 static int flockLock(sqlite3_file *id, int eFileLock) {
   26611   int rc = SQLITE_OK;
   26612   unixFile *pFile = (unixFile*)id;
   26613 
   26614   assert( pFile );
   26615 
   26616   /* if we already have a lock, it is exclusive.
   26617   ** Just adjust level and punt on outta here. */
   26618   if (pFile->eFileLock > NO_LOCK) {
   26619     pFile->eFileLock = eFileLock;
   26620     return SQLITE_OK;
   26621   }
   26622 
   26623   /* grab an exclusive lock */
   26624 
   26625   if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
   26626     int tErrno = errno;
   26627     /* didn't get, must be busy */
   26628     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   26629     if( IS_LOCK_ERROR(rc) ){
   26630       pFile->lastErrno = tErrno;
   26631     }
   26632   } else {
   26633     /* got it, set the type and return ok */
   26634     pFile->eFileLock = eFileLock;
   26635   }
   26636   OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
   26637            rc==SQLITE_OK ? "ok" : "failed"));
   26638 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
   26639   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
   26640     rc = SQLITE_BUSY;
   26641   }
   26642 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
   26643   return rc;
   26644 }
   26645 
   26646 
   26647 /*
   26648 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   26649 ** must be either NO_LOCK or SHARED_LOCK.
   26650 **
   26651 ** If the locking level of the file descriptor is already at or below
   26652 ** the requested locking level, this routine is a no-op.
   26653 */
   26654 static int flockUnlock(sqlite3_file *id, int eFileLock) {
   26655   unixFile *pFile = (unixFile*)id;
   26656 
   26657   assert( pFile );
   26658   OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
   26659            pFile->eFileLock, getpid()));
   26660   assert( eFileLock<=SHARED_LOCK );
   26661 
   26662   /* no-op if possible */
   26663   if( pFile->eFileLock==eFileLock ){
   26664     return SQLITE_OK;
   26665   }
   26666 
   26667   /* shared can just be set because we always have an exclusive */
   26668   if (eFileLock==SHARED_LOCK) {
   26669     pFile->eFileLock = eFileLock;
   26670     return SQLITE_OK;
   26671   }
   26672 
   26673   /* no, really, unlock. */
   26674   if( robust_flock(pFile->h, LOCK_UN) ){
   26675 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
   26676     return SQLITE_OK;
   26677 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
   26678     return SQLITE_IOERR_UNLOCK;
   26679   }else{
   26680     pFile->eFileLock = NO_LOCK;
   26681     return SQLITE_OK;
   26682   }
   26683 }
   26684 
   26685 /*
   26686 ** Close a file.
   26687 */
   26688 static int flockClose(sqlite3_file *id) {
   26689   int rc = SQLITE_OK;
   26690   if( id ){
   26691     flockUnlock(id, NO_LOCK);
   26692     rc = closeUnixFile(id);
   26693   }
   26694   return rc;
   26695 }
   26696 
   26697 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
   26698 
   26699 /******************* End of the flock lock implementation *********************
   26700 ******************************************************************************/
   26701 
   26702 /******************************************************************************
   26703 ************************ Begin Named Semaphore Locking ************************
   26704 **
   26705 ** Named semaphore locking is only supported on VxWorks.
   26706 **
   26707 ** Semaphore locking is like dot-lock and flock in that it really only
   26708 ** supports EXCLUSIVE locking.  Only a single process can read or write
   26709 ** the database file at a time.  This reduces potential concurrency, but
   26710 ** makes the lock implementation much easier.
   26711 */
   26712 #if OS_VXWORKS
   26713 
   26714 /*
   26715 ** This routine checks if there is a RESERVED lock held on the specified
   26716 ** file by this or any other process. If such a lock is held, set *pResOut
   26717 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   26718 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   26719 */
   26720 static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
   26721   int rc = SQLITE_OK;
   26722   int reserved = 0;
   26723   unixFile *pFile = (unixFile*)id;
   26724 
   26725   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   26726 
   26727   assert( pFile );
   26728 
   26729   /* Check if a thread in this process holds such a lock */
   26730   if( pFile->eFileLock>SHARED_LOCK ){
   26731     reserved = 1;
   26732   }
   26733 
   26734   /* Otherwise see if some other process holds it. */
   26735   if( !reserved ){
   26736     sem_t *pSem = pFile->pInode->pSem;
   26737 
   26738     if( sem_trywait(pSem)==-1 ){
   26739       int tErrno = errno;
   26740       if( EAGAIN != tErrno ){
   26741         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
   26742         pFile->lastErrno = tErrno;
   26743       } else {
   26744         /* someone else has the lock when we are in NO_LOCK */
   26745         reserved = (pFile->eFileLock < SHARED_LOCK);
   26746       }
   26747     }else{
   26748       /* we could have it if we want it */
   26749       sem_post(pSem);
   26750     }
   26751   }
   26752   OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
   26753 
   26754   *pResOut = reserved;
   26755   return rc;
   26756 }
   26757 
   26758 /*
   26759 ** Lock the file with the lock specified by parameter eFileLock - one
   26760 ** of the following:
   26761 **
   26762 **     (1) SHARED_LOCK
   26763 **     (2) RESERVED_LOCK
   26764 **     (3) PENDING_LOCK
   26765 **     (4) EXCLUSIVE_LOCK
   26766 **
   26767 ** Sometimes when requesting one lock state, additional lock states
   26768 ** are inserted in between.  The locking might fail on one of the later
   26769 ** transitions leaving the lock state different from what it started but
   26770 ** still short of its goal.  The following chart shows the allowed
   26771 ** transitions and the inserted intermediate states:
   26772 **
   26773 **    UNLOCKED -> SHARED
   26774 **    SHARED -> RESERVED
   26775 **    SHARED -> (PENDING) -> EXCLUSIVE
   26776 **    RESERVED -> (PENDING) -> EXCLUSIVE
   26777 **    PENDING -> EXCLUSIVE
   26778 **
   26779 ** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
   26780 ** lock states in the sqlite3_file structure, but all locks SHARED or
   26781 ** above are really EXCLUSIVE locks and exclude all other processes from
   26782 ** access the file.
   26783 **
   26784 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   26785 ** routine to lower a locking level.
   26786 */
   26787 static int semLock(sqlite3_file *id, int eFileLock) {
   26788   unixFile *pFile = (unixFile*)id;
   26789   sem_t *pSem = pFile->pInode->pSem;
   26790   int rc = SQLITE_OK;
   26791 
   26792   /* if we already have a lock, it is exclusive.
   26793   ** Just adjust level and punt on outta here. */
   26794   if (pFile->eFileLock > NO_LOCK) {
   26795     pFile->eFileLock = eFileLock;
   26796     rc = SQLITE_OK;
   26797     goto sem_end_lock;
   26798   }
   26799 
   26800   /* lock semaphore now but bail out when already locked. */
   26801   if( sem_trywait(pSem)==-1 ){
   26802     rc = SQLITE_BUSY;
   26803     goto sem_end_lock;
   26804   }
   26805 
   26806   /* got it, set the type and return ok */
   26807   pFile->eFileLock = eFileLock;
   26808 
   26809  sem_end_lock:
   26810   return rc;
   26811 }
   26812 
   26813 /*
   26814 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   26815 ** must be either NO_LOCK or SHARED_LOCK.
   26816 **
   26817 ** If the locking level of the file descriptor is already at or below
   26818 ** the requested locking level, this routine is a no-op.
   26819 */
   26820 static int semUnlock(sqlite3_file *id, int eFileLock) {
   26821   unixFile *pFile = (unixFile*)id;
   26822   sem_t *pSem = pFile->pInode->pSem;
   26823 
   26824   assert( pFile );
   26825   assert( pSem );
   26826   OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
   26827            pFile->eFileLock, getpid()));
   26828   assert( eFileLock<=SHARED_LOCK );
   26829 
   26830   /* no-op if possible */
   26831   if( pFile->eFileLock==eFileLock ){
   26832     return SQLITE_OK;
   26833   }
   26834 
   26835   /* shared can just be set because we always have an exclusive */
   26836   if (eFileLock==SHARED_LOCK) {
   26837     pFile->eFileLock = eFileLock;
   26838     return SQLITE_OK;
   26839   }
   26840 
   26841   /* no, really unlock. */
   26842   if ( sem_post(pSem)==-1 ) {
   26843     int rc, tErrno = errno;
   26844     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
   26845     if( IS_LOCK_ERROR(rc) ){
   26846       pFile->lastErrno = tErrno;
   26847     }
   26848     return rc;
   26849   }
   26850   pFile->eFileLock = NO_LOCK;
   26851   return SQLITE_OK;
   26852 }
   26853 
   26854 /*
   26855  ** Close a file.
   26856  */
   26857 static int semClose(sqlite3_file *id) {
   26858   if( id ){
   26859     unixFile *pFile = (unixFile*)id;
   26860     semUnlock(id, NO_LOCK);
   26861     assert( pFile );
   26862     unixEnterMutex();
   26863     releaseInodeInfo(pFile);
   26864     unixLeaveMutex();
   26865     closeUnixFile(id);
   26866   }
   26867   return SQLITE_OK;
   26868 }
   26869 
   26870 #endif /* OS_VXWORKS */
   26871 /*
   26872 ** Named semaphore locking is only available on VxWorks.
   26873 **
   26874 *************** End of the named semaphore lock implementation ****************
   26875 ******************************************************************************/
   26876 
   26877 
   26878 /******************************************************************************
   26879 *************************** Begin AFP Locking *********************************
   26880 **
   26881 ** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
   26882 ** on Apple Macintosh computers - both OS9 and OSX.
   26883 **
   26884 ** Third-party implementations of AFP are available.  But this code here
   26885 ** only works on OSX.
   26886 */
   26887 
   26888 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   26889 /*
   26890 ** The afpLockingContext structure contains all afp lock specific state
   26891 */
   26892 typedef struct afpLockingContext afpLockingContext;
   26893 struct afpLockingContext {
   26894   int reserved;
   26895   const char *dbPath;             /* Name of the open file */
   26896 };
   26897 
   26898 struct ByteRangeLockPB2
   26899 {
   26900   unsigned long long offset;        /* offset to first byte to lock */
   26901   unsigned long long length;        /* nbr of bytes to lock */
   26902   unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
   26903   unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
   26904   unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
   26905   int fd;                           /* file desc to assoc this lock with */
   26906 };
   26907 
   26908 #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
   26909 
   26910 /*
   26911 ** This is a utility for setting or clearing a bit-range lock on an
   26912 ** AFP filesystem.
   26913 **
   26914 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
   26915 */
   26916 static int afpSetLock(
   26917   const char *path,              /* Name of the file to be locked or unlocked */
   26918   unixFile *pFile,               /* Open file descriptor on path */
   26919   unsigned long long offset,     /* First byte to be locked */
   26920   unsigned long long length,     /* Number of bytes to lock */
   26921   int setLockFlag                /* True to set lock.  False to clear lock */
   26922 ){
   26923   struct ByteRangeLockPB2 pb;
   26924   int err;
   26925 
   26926   pb.unLockFlag = setLockFlag ? 0 : 1;
   26927   pb.startEndFlag = 0;
   26928   pb.offset = offset;
   26929   pb.length = length;
   26930   pb.fd = pFile->h;
   26931 
   26932   OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
   26933     (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
   26934     offset, length));
   26935   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
   26936   if ( err==-1 ) {
   26937     int rc;
   26938     int tErrno = errno;
   26939     OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
   26940              path, tErrno, strerror(tErrno)));
   26941 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
   26942     rc = SQLITE_BUSY;
   26943 #else
   26944     rc = sqliteErrorFromPosixError(tErrno,
   26945                     setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
   26946 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
   26947     if( IS_LOCK_ERROR(rc) ){
   26948       pFile->lastErrno = tErrno;
   26949     }
   26950     return rc;
   26951   } else {
   26952     return SQLITE_OK;
   26953   }
   26954 }
   26955 
   26956 /*
   26957 ** This routine checks if there is a RESERVED lock held on the specified
   26958 ** file by this or any other process. If such a lock is held, set *pResOut
   26959 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   26960 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   26961 */
   26962 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
   26963   int rc = SQLITE_OK;
   26964   int reserved = 0;
   26965   unixFile *pFile = (unixFile*)id;
   26966   afpLockingContext *context;
   26967 
   26968   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   26969 
   26970   assert( pFile );
   26971   context = (afpLockingContext *) pFile->lockingContext;
   26972   if( context->reserved ){
   26973     *pResOut = 1;
   26974     return SQLITE_OK;
   26975   }
   26976   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
   26977 
   26978   /* Check if a thread in this process holds such a lock */
   26979   if( pFile->pInode->eFileLock>SHARED_LOCK ){
   26980     reserved = 1;
   26981   }
   26982 
   26983   /* Otherwise see if some other process holds it.
   26984    */
   26985   if( !reserved ){
   26986     /* lock the RESERVED byte */
   26987     int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
   26988     if( SQLITE_OK==lrc ){
   26989       /* if we succeeded in taking the reserved lock, unlock it to restore
   26990       ** the original state */
   26991       lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
   26992     } else {
   26993       /* if we failed to get the lock then someone else must have it */
   26994       reserved = 1;
   26995     }
   26996     if( IS_LOCK_ERROR(lrc) ){
   26997       rc=lrc;
   26998     }
   26999   }
   27000 
   27001   unixLeaveMutex();
   27002   OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
   27003 
   27004   *pResOut = reserved;
   27005   return rc;
   27006 }
   27007 
   27008 /*
   27009 ** Lock the file with the lock specified by parameter eFileLock - one
   27010 ** of the following:
   27011 **
   27012 **     (1) SHARED_LOCK
   27013 **     (2) RESERVED_LOCK
   27014 **     (3) PENDING_LOCK
   27015 **     (4) EXCLUSIVE_LOCK
   27016 **
   27017 ** Sometimes when requesting one lock state, additional lock states
   27018 ** are inserted in between.  The locking might fail on one of the later
   27019 ** transitions leaving the lock state different from what it started but
   27020 ** still short of its goal.  The following chart shows the allowed
   27021 ** transitions and the inserted intermediate states:
   27022 **
   27023 **    UNLOCKED -> SHARED
   27024 **    SHARED -> RESERVED
   27025 **    SHARED -> (PENDING) -> EXCLUSIVE
   27026 **    RESERVED -> (PENDING) -> EXCLUSIVE
   27027 **    PENDING -> EXCLUSIVE
   27028 **
   27029 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   27030 ** routine to lower a locking level.
   27031 */
   27032 static int afpLock(sqlite3_file *id, int eFileLock){
   27033   int rc = SQLITE_OK;
   27034   unixFile *pFile = (unixFile*)id;
   27035   unixInodeInfo *pInode = pFile->pInode;
   27036   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
   27037 
   27038   assert( pFile );
   27039   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
   27040            azFileLock(eFileLock), azFileLock(pFile->eFileLock),
   27041            azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
   27042 
   27043   /* If there is already a lock of this type or more restrictive on the
   27044   ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
   27045   ** unixEnterMutex() hasn't been called yet.
   27046   */
   27047   if( pFile->eFileLock>=eFileLock ){
   27048     OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
   27049            azFileLock(eFileLock)));
   27050     return SQLITE_OK;
   27051   }
   27052 
   27053   /* Make sure the locking sequence is correct
   27054   **  (1) We never move from unlocked to anything higher than shared lock.
   27055   **  (2) SQLite never explicitly requests a pendig lock.
   27056   **  (3) A shared lock is always held when a reserve lock is requested.
   27057   */
   27058   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
   27059   assert( eFileLock!=PENDING_LOCK );
   27060   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
   27061 
   27062   /* This mutex is needed because pFile->pInode is shared across threads
   27063   */
   27064   unixEnterMutex();
   27065   pInode = pFile->pInode;
   27066 
   27067   /* If some thread using this PID has a lock via a different unixFile*
   27068   ** handle that precludes the requested lock, return BUSY.
   27069   */
   27070   if( (pFile->eFileLock!=pInode->eFileLock &&
   27071        (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
   27072      ){
   27073     rc = SQLITE_BUSY;
   27074     goto afp_end_lock;
   27075   }
   27076 
   27077   /* If a SHARED lock is requested, and some thread using this PID already
   27078   ** has a SHARED or RESERVED lock, then increment reference counts and
   27079   ** return SQLITE_OK.
   27080   */
   27081   if( eFileLock==SHARED_LOCK &&
   27082      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
   27083     assert( eFileLock==SHARED_LOCK );
   27084     assert( pFile->eFileLock==0 );
   27085     assert( pInode->nShared>0 );
   27086     pFile->eFileLock = SHARED_LOCK;
   27087     pInode->nShared++;
   27088     pInode->nLock++;
   27089     goto afp_end_lock;
   27090   }
   27091 
   27092   /* A PENDING lock is needed before acquiring a SHARED lock and before
   27093   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
   27094   ** be released.
   27095   */
   27096   if( eFileLock==SHARED_LOCK
   27097       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
   27098   ){
   27099     int failed;
   27100     failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
   27101     if (failed) {
   27102       rc = failed;
   27103       goto afp_end_lock;
   27104     }
   27105   }
   27106 
   27107   /* If control gets to this point, then actually go ahead and make
   27108   ** operating system calls for the specified lock.
   27109   */
   27110   if( eFileLock==SHARED_LOCK ){
   27111     int lrc1, lrc2, lrc1Errno = 0;
   27112     long lk, mask;
   27113 
   27114     assert( pInode->nShared==0 );
   27115     assert( pInode->eFileLock==0 );
   27116 
   27117     mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
   27118     /* Now get the read-lock SHARED_LOCK */
   27119     /* note that the quality of the randomness doesn't matter that much */
   27120     lk = random();
   27121     pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
   27122     lrc1 = afpSetLock(context->dbPath, pFile,
   27123           SHARED_FIRST+pInode->sharedByte, 1, 1);
   27124     if( IS_LOCK_ERROR(lrc1) ){
   27125       lrc1Errno = pFile->lastErrno;
   27126     }
   27127     /* Drop the temporary PENDING lock */
   27128     lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
   27129 
   27130     if( IS_LOCK_ERROR(lrc1) ) {
   27131       pFile->lastErrno = lrc1Errno;
   27132       rc = lrc1;
   27133       goto afp_end_lock;
   27134     } else if( IS_LOCK_ERROR(lrc2) ){
   27135       rc = lrc2;
   27136       goto afp_end_lock;
   27137     } else if( lrc1 != SQLITE_OK ) {
   27138       rc = lrc1;
   27139     } else {
   27140       pFile->eFileLock = SHARED_LOCK;
   27141       pInode->nLock++;
   27142       pInode->nShared = 1;
   27143     }
   27144   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
   27145     /* We are trying for an exclusive lock but another thread in this
   27146      ** same process is still holding a shared lock. */
   27147     rc = SQLITE_BUSY;
   27148   }else{
   27149     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
   27150     ** assumed that there is a SHARED or greater lock on the file
   27151     ** already.
   27152     */
   27153     int failed = 0;
   27154     assert( 0!=pFile->eFileLock );
   27155     if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
   27156         /* Acquire a RESERVED lock */
   27157         failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
   27158       if( !failed ){
   27159         context->reserved = 1;
   27160       }
   27161     }
   27162     if (!failed && eFileLock == EXCLUSIVE_LOCK) {
   27163       /* Acquire an EXCLUSIVE lock */
   27164 
   27165       /* Remove the shared lock before trying the range.  we'll need to
   27166       ** reestablish the shared lock if we can't get the  afpUnlock
   27167       */
   27168       if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
   27169                          pInode->sharedByte, 1, 0)) ){
   27170         int failed2 = SQLITE_OK;
   27171         /* now attemmpt to get the exclusive lock range */
   27172         failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
   27173                                SHARED_SIZE, 1);
   27174         if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
   27175                        SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
   27176           /* Can't reestablish the shared lock.  Sqlite can't deal, this is
   27177           ** a critical I/O error
   27178           */
   27179           rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
   27180                SQLITE_IOERR_LOCK;
   27181           goto afp_end_lock;
   27182         }
   27183       }else{
   27184         rc = failed;
   27185       }
   27186     }
   27187     if( failed ){
   27188       rc = failed;
   27189     }
   27190   }
   27191 
   27192   if( rc==SQLITE_OK ){
   27193     pFile->eFileLock = eFileLock;
   27194     pInode->eFileLock = eFileLock;
   27195   }else if( eFileLock==EXCLUSIVE_LOCK ){
   27196     pFile->eFileLock = PENDING_LOCK;
   27197     pInode->eFileLock = PENDING_LOCK;
   27198   }
   27199 
   27200 afp_end_lock:
   27201   unixLeaveMutex();
   27202   OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
   27203          rc==SQLITE_OK ? "ok" : "failed"));
   27204   return rc;
   27205 }
   27206 
   27207 /*
   27208 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   27209 ** must be either NO_LOCK or SHARED_LOCK.
   27210 **
   27211 ** If the locking level of the file descriptor is already at or below
   27212 ** the requested locking level, this routine is a no-op.
   27213 */
   27214 static int afpUnlock(sqlite3_file *id, int eFileLock) {
   27215   int rc = SQLITE_OK;
   27216   unixFile *pFile = (unixFile*)id;
   27217   unixInodeInfo *pInode;
   27218   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
   27219   int skipShared = 0;
   27220 #ifdef SQLITE_TEST
   27221   int h = pFile->h;
   27222 #endif
   27223 
   27224   assert( pFile );
   27225   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
   27226            pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
   27227            getpid()));
   27228 
   27229   assert( eFileLock<=SHARED_LOCK );
   27230   if( pFile->eFileLock<=eFileLock ){
   27231     return SQLITE_OK;
   27232   }
   27233   unixEnterMutex();
   27234   pInode = pFile->pInode;
   27235   assert( pInode->nShared!=0 );
   27236   if( pFile->eFileLock>SHARED_LOCK ){
   27237     assert( pInode->eFileLock==pFile->eFileLock );
   27238     SimulateIOErrorBenign(1);
   27239     SimulateIOError( h=(-1) )
   27240     SimulateIOErrorBenign(0);
   27241 
   27242 #ifdef SQLITE_DEBUG
   27243     /* When reducing a lock such that other processes can start
   27244     ** reading the database file again, make sure that the
   27245     ** transaction counter was updated if any part of the database
   27246     ** file changed.  If the transaction counter is not updated,
   27247     ** other connections to the same file might not realize that
   27248     ** the file has changed and hence might not know to flush their
   27249     ** cache.  The use of a stale cache can lead to database corruption.
   27250     */
   27251     assert( pFile->inNormalWrite==0
   27252            || pFile->dbUpdate==0
   27253            || pFile->transCntrChng==1 );
   27254     pFile->inNormalWrite = 0;
   27255 #endif
   27256 
   27257     if( pFile->eFileLock==EXCLUSIVE_LOCK ){
   27258       rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
   27259       if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
   27260         /* only re-establish the shared lock if necessary */
   27261         int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
   27262         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
   27263       } else {
   27264         skipShared = 1;
   27265       }
   27266     }
   27267     if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
   27268       rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
   27269     }
   27270     if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
   27271       rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
   27272       if( !rc ){
   27273         context->reserved = 0;
   27274       }
   27275     }
   27276     if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
   27277       pInode->eFileLock = SHARED_LOCK;
   27278     }
   27279   }
   27280   if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
   27281 
   27282     /* Decrement the shared lock counter.  Release the lock using an
   27283     ** OS call only when all threads in this same process have released
   27284     ** the lock.
   27285     */
   27286     unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
   27287     pInode->nShared--;
   27288     if( pInode->nShared==0 ){
   27289       SimulateIOErrorBenign(1);
   27290       SimulateIOError( h=(-1) )
   27291       SimulateIOErrorBenign(0);
   27292       if( !skipShared ){
   27293         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
   27294       }
   27295       if( !rc ){
   27296         pInode->eFileLock = NO_LOCK;
   27297         pFile->eFileLock = NO_LOCK;
   27298       }
   27299     }
   27300     if( rc==SQLITE_OK ){
   27301       pInode->nLock--;
   27302       assert( pInode->nLock>=0 );
   27303       if( pInode->nLock==0 ){
   27304         closePendingFds(pFile);
   27305       }
   27306     }
   27307   }
   27308 
   27309   unixLeaveMutex();
   27310   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
   27311   return rc;
   27312 }
   27313 
   27314 /*
   27315 ** Close a file & cleanup AFP specific locking context
   27316 */
   27317 static int afpClose(sqlite3_file *id) {
   27318   int rc = SQLITE_OK;
   27319   if( id ){
   27320     unixFile *pFile = (unixFile*)id;
   27321     afpUnlock(id, NO_LOCK);
   27322     unixEnterMutex();
   27323     if( pFile->pInode && pFile->pInode->nLock ){
   27324       /* If there are outstanding locks, do not actually close the file just
   27325       ** yet because that would clear those locks.  Instead, add the file
   27326       ** descriptor to pInode->aPending.  It will be automatically closed when
   27327       ** the last lock is cleared.
   27328       */
   27329       setPendingFd(pFile);
   27330     }
   27331     releaseInodeInfo(pFile);
   27332     sqlite3_free(pFile->lockingContext);
   27333     rc = closeUnixFile(id);
   27334     unixLeaveMutex();
   27335   }
   27336   return rc;
   27337 }
   27338 
   27339 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
   27340 /*
   27341 ** The code above is the AFP lock implementation.  The code is specific
   27342 ** to MacOSX and does not work on other unix platforms.  No alternative
   27343 ** is available.  If you don't compile for a mac, then the "unix-afp"
   27344 ** VFS is not available.
   27345 **
   27346 ********************* End of the AFP lock implementation **********************
   27347 ******************************************************************************/
   27348 
   27349 /******************************************************************************
   27350 *************************** Begin NFS Locking ********************************/
   27351 
   27352 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   27353 /*
   27354  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   27355  ** must be either NO_LOCK or SHARED_LOCK.
   27356  **
   27357  ** If the locking level of the file descriptor is already at or below
   27358  ** the requested locking level, this routine is a no-op.
   27359  */
   27360 static int nfsUnlock(sqlite3_file *id, int eFileLock){
   27361   return posixUnlock(id, eFileLock, 1);
   27362 }
   27363 
   27364 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
   27365 /*
   27366 ** The code above is the NFS lock implementation.  The code is specific
   27367 ** to MacOSX and does not work on other unix platforms.  No alternative
   27368 ** is available.
   27369 **
   27370 ********************* End of the NFS lock implementation **********************
   27371 ******************************************************************************/
   27372 
   27373 /******************************************************************************
   27374 **************** Non-locking sqlite3_file methods *****************************
   27375 **
   27376 ** The next division contains implementations for all methods of the
   27377 ** sqlite3_file object other than the locking methods.  The locking
   27378 ** methods were defined in divisions above (one locking method per
   27379 ** division).  Those methods that are common to all locking modes
   27380 ** are gather together into this division.
   27381 */
   27382 
   27383 /*
   27384 ** Seek to the offset passed as the second argument, then read cnt
   27385 ** bytes into pBuf. Return the number of bytes actually read.
   27386 **
   27387 ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
   27388 ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
   27389 ** one system to another.  Since SQLite does not define USE_PREAD
   27390 ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
   27391 ** See tickets #2741 and #2681.
   27392 **
   27393 ** To avoid stomping the errno value on a failed read the lastErrno value
   27394 ** is set before returning.
   27395 */
   27396 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
   27397   int got;
   27398   int prior = 0;
   27399 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
   27400   i64 newOffset;
   27401 #endif
   27402   TIMER_START;
   27403   assert( cnt==(cnt&0x1ffff) );
   27404   assert( id->h>2 );
   27405   cnt &= 0x1ffff;
   27406   do{
   27407 #if defined(USE_PREAD)
   27408     got = osPread(id->h, pBuf, cnt, offset);
   27409     SimulateIOError( got = -1 );
   27410 #elif defined(USE_PREAD64)
   27411     got = osPread64(id->h, pBuf, cnt, offset);
   27412     SimulateIOError( got = -1 );
   27413 #else
   27414     newOffset = lseek(id->h, offset, SEEK_SET);
   27415     SimulateIOError( newOffset-- );
   27416     if( newOffset!=offset ){
   27417       if( newOffset == -1 ){
   27418         ((unixFile*)id)->lastErrno = errno;
   27419       }else{
   27420         ((unixFile*)id)->lastErrno = 0;
   27421       }
   27422       return -1;
   27423     }
   27424     got = osRead(id->h, pBuf, cnt);
   27425 #endif
   27426     if( got==cnt ) break;
   27427     if( got<0 ){
   27428       if( errno==EINTR ){ got = 1; continue; }
   27429       prior = 0;
   27430       ((unixFile*)id)->lastErrno = errno;
   27431       break;
   27432     }else if( got>0 ){
   27433       cnt -= got;
   27434       offset += got;
   27435       prior += got;
   27436       pBuf = (void*)(got + (char*)pBuf);
   27437     }
   27438   }while( got>0 );
   27439   TIMER_END;
   27440   OSTRACE(("READ    %-3d %5d %7lld %llu\n",
   27441             id->h, got+prior, offset-prior, TIMER_ELAPSED));
   27442   return got+prior;
   27443 }
   27444 
   27445 /*
   27446 ** Read data from a file into a buffer.  Return SQLITE_OK if all
   27447 ** bytes were read successfully and SQLITE_IOERR if anything goes
   27448 ** wrong.
   27449 */
   27450 static int unixRead(
   27451   sqlite3_file *id,
   27452   void *pBuf,
   27453   int amt,
   27454   sqlite3_int64 offset
   27455 ){
   27456   unixFile *pFile = (unixFile *)id;
   27457   int got;
   27458   assert( id );
   27459   assert( offset>=0 );
   27460   assert( amt>0 );
   27461 
   27462   /* If this is a database file (not a journal, master-journal or temp
   27463   ** file), the bytes in the locking range should never be read or written. */
   27464 #if 0
   27465   assert( pFile->pUnused==0
   27466        || offset>=PENDING_BYTE+512
   27467        || offset+amt<=PENDING_BYTE
   27468   );
   27469 #endif
   27470 
   27471 #if SQLITE_MAX_MMAP_SIZE>0
   27472   /* Deal with as much of this read request as possible by transfering
   27473   ** data from the memory mapping using memcpy().  */
   27474   if( offset<pFile->mmapSize ){
   27475     if( offset+amt <= pFile->mmapSize ){
   27476       memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
   27477       return SQLITE_OK;
   27478     }else{
   27479       int nCopy = pFile->mmapSize - offset;
   27480       memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
   27481       pBuf = &((u8 *)pBuf)[nCopy];
   27482       amt -= nCopy;
   27483       offset += nCopy;
   27484     }
   27485   }
   27486 #endif
   27487 
   27488   got = seekAndRead(pFile, offset, pBuf, amt);
   27489   if( got==amt ){
   27490     return SQLITE_OK;
   27491   }else if( got<0 ){
   27492     /* lastErrno set by seekAndRead */
   27493     return SQLITE_IOERR_READ;
   27494   }else{
   27495     pFile->lastErrno = 0; /* not a system error */
   27496     /* Unread parts of the buffer must be zero-filled */
   27497     memset(&((char*)pBuf)[got], 0, amt-got);
   27498     return SQLITE_IOERR_SHORT_READ;
   27499   }
   27500 }
   27501 
   27502 /*
   27503 ** Attempt to seek the file-descriptor passed as the first argument to
   27504 ** absolute offset iOff, then attempt to write nBuf bytes of data from
   27505 ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
   27506 ** return the actual number of bytes written (which may be less than
   27507 ** nBuf).
   27508 */
   27509 static int seekAndWriteFd(
   27510   int fd,                         /* File descriptor to write to */
   27511   i64 iOff,                       /* File offset to begin writing at */
   27512   const void *pBuf,               /* Copy data from this buffer to the file */
   27513   int nBuf,                       /* Size of buffer pBuf in bytes */
   27514   int *piErrno                    /* OUT: Error number if error occurs */
   27515 ){
   27516   int rc = 0;                     /* Value returned by system call */
   27517 
   27518   assert( nBuf==(nBuf&0x1ffff) );
   27519   assert( fd>2 );
   27520   nBuf &= 0x1ffff;
   27521   TIMER_START;
   27522 
   27523 #if defined(USE_PREAD)
   27524   do{ rc = osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
   27525 #elif defined(USE_PREAD64)
   27526   do{ rc = osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
   27527 #else
   27528   do{
   27529     i64 iSeek = lseek(fd, iOff, SEEK_SET);
   27530     SimulateIOError( iSeek-- );
   27531 
   27532     if( iSeek!=iOff ){
   27533       if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
   27534       return -1;
   27535     }
   27536     rc = osWrite(fd, pBuf, nBuf);
   27537   }while( rc<0 && errno==EINTR );
   27538 #endif
   27539 
   27540   TIMER_END;
   27541   OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
   27542 
   27543   if( rc<0 && piErrno ) *piErrno = errno;
   27544   return rc;
   27545 }
   27546 
   27547 
   27548 /*
   27549 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
   27550 ** Return the number of bytes actually read.  Update the offset.
   27551 **
   27552 ** To avoid stomping the errno value on a failed write the lastErrno value
   27553 ** is set before returning.
   27554 */
   27555 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
   27556   return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
   27557 }
   27558 
   27559 
   27560 /*
   27561 ** Write data from a buffer into a file.  Return SQLITE_OK on success
   27562 ** or some other error code on failure.
   27563 */
   27564 static int unixWrite(
   27565   sqlite3_file *id,
   27566   const void *pBuf,
   27567   int amt,
   27568   sqlite3_int64 offset
   27569 ){
   27570   unixFile *pFile = (unixFile*)id;
   27571   int wrote = 0;
   27572   assert( id );
   27573   assert( amt>0 );
   27574 
   27575   /* If this is a database file (not a journal, master-journal or temp
   27576   ** file), the bytes in the locking range should never be read or written. */
   27577 #if 0
   27578   assert( pFile->pUnused==0
   27579        || offset>=PENDING_BYTE+512
   27580        || offset+amt<=PENDING_BYTE
   27581   );
   27582 #endif
   27583 
   27584 #ifdef SQLITE_DEBUG
   27585   /* If we are doing a normal write to a database file (as opposed to
   27586   ** doing a hot-journal rollback or a write to some file other than a
   27587   ** normal database file) then record the fact that the database
   27588   ** has changed.  If the transaction counter is modified, record that
   27589   ** fact too.
   27590   */
   27591   if( pFile->inNormalWrite ){
   27592     pFile->dbUpdate = 1;  /* The database has been modified */
   27593     if( offset<=24 && offset+amt>=27 ){
   27594       int rc;
   27595       char oldCntr[4];
   27596       SimulateIOErrorBenign(1);
   27597       rc = seekAndRead(pFile, 24, oldCntr, 4);
   27598       SimulateIOErrorBenign(0);
   27599       if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
   27600         pFile->transCntrChng = 1;  /* The transaction counter has changed */
   27601       }
   27602     }
   27603   }
   27604 #endif
   27605 
   27606 #if SQLITE_MAX_MMAP_SIZE>0
   27607   /* Deal with as much of this write request as possible by transfering
   27608   ** data from the memory mapping using memcpy().  */
   27609   if( offset<pFile->mmapSize ){
   27610     if( offset+amt <= pFile->mmapSize ){
   27611       memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
   27612       return SQLITE_OK;
   27613     }else{
   27614       int nCopy = pFile->mmapSize - offset;
   27615       memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
   27616       pBuf = &((u8 *)pBuf)[nCopy];
   27617       amt -= nCopy;
   27618       offset += nCopy;
   27619     }
   27620   }
   27621 #endif
   27622 
   27623   while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
   27624     amt -= wrote;
   27625     offset += wrote;
   27626     pBuf = &((char*)pBuf)[wrote];
   27627   }
   27628   SimulateIOError(( wrote=(-1), amt=1 ));
   27629   SimulateDiskfullError(( wrote=0, amt=1 ));
   27630 
   27631   if( amt>0 ){
   27632     if( wrote<0 && pFile->lastErrno!=ENOSPC ){
   27633       /* lastErrno set by seekAndWrite */
   27634       return SQLITE_IOERR_WRITE;
   27635     }else{
   27636       pFile->lastErrno = 0; /* not a system error */
   27637       return SQLITE_FULL;
   27638     }
   27639   }
   27640 
   27641   return SQLITE_OK;
   27642 }
   27643 
   27644 #ifdef SQLITE_TEST
   27645 /*
   27646 ** Count the number of fullsyncs and normal syncs.  This is used to test
   27647 ** that syncs and fullsyncs are occurring at the right times.
   27648 */
   27649 SQLITE_API int sqlite3_sync_count = 0;
   27650 SQLITE_API int sqlite3_fullsync_count = 0;
   27651 #endif
   27652 
   27653 /*
   27654 ** We do not trust systems to provide a working fdatasync().  Some do.
   27655 ** Others do no.  To be safe, we will stick with the (slightly slower)
   27656 ** fsync(). If you know that your system does support fdatasync() correctly,
   27657 ** then simply compile with -Dfdatasync=fdatasync
   27658 */
   27659 #if !defined(fdatasync)
   27660 # define fdatasync fsync
   27661 #endif
   27662 
   27663 /*
   27664 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
   27665 ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
   27666 ** only available on Mac OS X.  But that could change.
   27667 */
   27668 #ifdef F_FULLFSYNC
   27669 # define HAVE_FULLFSYNC 1
   27670 #else
   27671 # define HAVE_FULLFSYNC 0
   27672 #endif
   27673 
   27674 
   27675 /*
   27676 ** The fsync() system call does not work as advertised on many
   27677 ** unix systems.  The following procedure is an attempt to make
   27678 ** it work better.
   27679 **
   27680 ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
   27681 ** for testing when we want to run through the test suite quickly.
   27682 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
   27683 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
   27684 ** or power failure will likely corrupt the database file.
   27685 **
   27686 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
   27687 ** The idea behind dataOnly is that it should only write the file content
   27688 ** to disk, not the inode.  We only set dataOnly if the file size is
   27689 ** unchanged since the file size is part of the inode.  However,
   27690 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
   27691 ** file size has changed.  The only real difference between fdatasync()
   27692 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
   27693 ** inode if the mtime or owner or other inode attributes have changed.
   27694 ** We only care about the file size, not the other file attributes, so
   27695 ** as far as SQLite is concerned, an fdatasync() is always adequate.
   27696 ** So, we always use fdatasync() if it is available, regardless of
   27697 ** the value of the dataOnly flag.
   27698 */
   27699 static int full_fsync(int fd, int fullSync, int dataOnly){
   27700   int rc;
   27701 
   27702   /* The following "ifdef/elif/else/" block has the same structure as
   27703   ** the one below. It is replicated here solely to avoid cluttering
   27704   ** up the real code with the UNUSED_PARAMETER() macros.
   27705   */
   27706 #ifdef SQLITE_NO_SYNC
   27707   UNUSED_PARAMETER(fd);
   27708   UNUSED_PARAMETER(fullSync);
   27709   UNUSED_PARAMETER(dataOnly);
   27710 #elif HAVE_FULLFSYNC
   27711   UNUSED_PARAMETER(dataOnly);
   27712 #else
   27713   UNUSED_PARAMETER(fullSync);
   27714   UNUSED_PARAMETER(dataOnly);
   27715 #endif
   27716 
   27717   /* Record the number of times that we do a normal fsync() and
   27718   ** FULLSYNC.  This is used during testing to verify that this procedure
   27719   ** gets called with the correct arguments.
   27720   */
   27721 #ifdef SQLITE_TEST
   27722   if( fullSync ) sqlite3_fullsync_count++;
   27723   sqlite3_sync_count++;
   27724 #endif
   27725 
   27726   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
   27727   ** no-op
   27728   */
   27729 #ifdef SQLITE_NO_SYNC
   27730   rc = SQLITE_OK;
   27731 #elif HAVE_FULLFSYNC
   27732   if( fullSync ){
   27733     rc = osFcntl(fd, F_FULLFSYNC, 0);
   27734   }else{
   27735     rc = 1;
   27736   }
   27737   /* If the FULLFSYNC failed, fall back to attempting an fsync().
   27738   ** It shouldn't be possible for fullfsync to fail on the local
   27739   ** file system (on OSX), so failure indicates that FULLFSYNC
   27740   ** isn't supported for this file system. So, attempt an fsync
   27741   ** and (for now) ignore the overhead of a superfluous fcntl call.
   27742   ** It'd be better to detect fullfsync support once and avoid
   27743   ** the fcntl call every time sync is called.
   27744   */
   27745   if( rc ) rc = fsync(fd);
   27746 
   27747 #elif defined(__APPLE__)
   27748   /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
   27749   ** so currently we default to the macro that redefines fdatasync to fsync
   27750   */
   27751   rc = fsync(fd);
   27752 #else
   27753   rc = fdatasync(fd);
   27754 #if OS_VXWORKS
   27755   if( rc==-1 && errno==ENOTSUP ){
   27756     rc = fsync(fd);
   27757   }
   27758 #endif /* OS_VXWORKS */
   27759 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
   27760 
   27761   if( OS_VXWORKS && rc!= -1 ){
   27762     rc = 0;
   27763   }
   27764   return rc;
   27765 }
   27766 
   27767 /*
   27768 ** Open a file descriptor to the directory containing file zFilename.
   27769 ** If successful, *pFd is set to the opened file descriptor and
   27770 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
   27771 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
   27772 ** value.
   27773 **
   27774 ** The directory file descriptor is used for only one thing - to
   27775 ** fsync() a directory to make sure file creation and deletion events
   27776 ** are flushed to disk.  Such fsyncs are not needed on newer
   27777 ** journaling filesystems, but are required on older filesystems.
   27778 **
   27779 ** This routine can be overridden using the xSetSysCall interface.
   27780 ** The ability to override this routine was added in support of the
   27781 ** chromium sandbox.  Opening a directory is a security risk (we are
   27782 ** told) so making it overrideable allows the chromium sandbox to
   27783 ** replace this routine with a harmless no-op.  To make this routine
   27784 ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
   27785 ** *pFd set to a negative number.
   27786 **
   27787 ** If SQLITE_OK is returned, the caller is responsible for closing
   27788 ** the file descriptor *pFd using close().
   27789 */
   27790 static int openDirectory(const char *zFilename, int *pFd){
   27791   int ii;
   27792   int fd = -1;
   27793   char zDirname[MAX_PATHNAME+1];
   27794 
   27795   sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
   27796   for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
   27797   if( ii>0 ){
   27798     zDirname[ii] = '\0';
   27799     fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
   27800     if( fd>=0 ){
   27801       OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
   27802     }
   27803   }
   27804   *pFd = fd;
   27805   return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
   27806 }
   27807 
   27808 /*
   27809 ** Make sure all writes to a particular file are committed to disk.
   27810 **
   27811 ** If dataOnly==0 then both the file itself and its metadata (file
   27812 ** size, access time, etc) are synced.  If dataOnly!=0 then only the
   27813 ** file data is synced.
   27814 **
   27815 ** Under Unix, also make sure that the directory entry for the file
   27816 ** has been created by fsync-ing the directory that contains the file.
   27817 ** If we do not do this and we encounter a power failure, the directory
   27818 ** entry for the journal might not exist after we reboot.  The next
   27819 ** SQLite to access the file will not know that the journal exists (because
   27820 ** the directory entry for the journal was never created) and the transaction
   27821 ** will not roll back - possibly leading to database corruption.
   27822 */
   27823 static int unixSync(sqlite3_file *id, int flags){
   27824   int rc;
   27825   unixFile *pFile = (unixFile*)id;
   27826 
   27827   int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
   27828   int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
   27829 
   27830   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
   27831   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
   27832       || (flags&0x0F)==SQLITE_SYNC_FULL
   27833   );
   27834 
   27835   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
   27836   ** line is to test that doing so does not cause any problems.
   27837   */
   27838   SimulateDiskfullError( return SQLITE_FULL );
   27839 
   27840   assert( pFile );
   27841   OSTRACE(("SYNC    %-3d\n", pFile->h));
   27842   rc = full_fsync(pFile->h, isFullsync, isDataOnly);
   27843   SimulateIOError( rc=1 );
   27844   if( rc ){
   27845     pFile->lastErrno = errno;
   27846     return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
   27847   }
   27848 
   27849   /* Also fsync the directory containing the file if the DIRSYNC flag
   27850   ** is set.  This is a one-time occurrence.  Many systems (examples: AIX)
   27851   ** are unable to fsync a directory, so ignore errors on the fsync.
   27852   */
   27853   if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
   27854     int dirfd;
   27855     OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
   27856             HAVE_FULLFSYNC, isFullsync));
   27857     rc = osOpenDirectory(pFile->zPath, &dirfd);
   27858     if( rc==SQLITE_OK && dirfd>=0 ){
   27859       full_fsync(dirfd, 0, 0);
   27860       robust_close(pFile, dirfd, __LINE__);
   27861     }else if( rc==SQLITE_CANTOPEN ){
   27862       rc = SQLITE_OK;
   27863     }
   27864     pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
   27865   }
   27866   return rc;
   27867 }
   27868 
   27869 /*
   27870 ** Truncate an open file to a specified size
   27871 */
   27872 static int unixTruncate(sqlite3_file *id, i64 nByte){
   27873   unixFile *pFile = (unixFile *)id;
   27874   int rc;
   27875   assert( pFile );
   27876   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
   27877 
   27878   /* If the user has configured a chunk-size for this file, truncate the
   27879   ** file so that it consists of an integer number of chunks (i.e. the
   27880   ** actual file size after the operation may be larger than the requested
   27881   ** size).
   27882   */
   27883   if( pFile->szChunk>0 ){
   27884     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
   27885   }
   27886 
   27887   rc = robust_ftruncate(pFile->h, (off_t)nByte);
   27888   if( rc ){
   27889     pFile->lastErrno = errno;
   27890     return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
   27891   }else{
   27892 #ifdef SQLITE_DEBUG
   27893     /* If we are doing a normal write to a database file (as opposed to
   27894     ** doing a hot-journal rollback or a write to some file other than a
   27895     ** normal database file) and we truncate the file to zero length,
   27896     ** that effectively updates the change counter.  This might happen
   27897     ** when restoring a database using the backup API from a zero-length
   27898     ** source.
   27899     */
   27900     if( pFile->inNormalWrite && nByte==0 ){
   27901       pFile->transCntrChng = 1;
   27902     }
   27903 #endif
   27904 
   27905 #if SQLITE_MAX_MMAP_SIZE>0
   27906     /* If the file was just truncated to a size smaller than the currently
   27907     ** mapped region, reduce the effective mapping size as well. SQLite will
   27908     ** use read() and write() to access data beyond this point from now on.
   27909     */
   27910     if( nByte<pFile->mmapSize ){
   27911       pFile->mmapSize = nByte;
   27912     }
   27913 #endif
   27914 
   27915     return SQLITE_OK;
   27916   }
   27917 }
   27918 
   27919 /*
   27920 ** Determine the current size of a file in bytes
   27921 */
   27922 static int unixFileSize(sqlite3_file *id, i64 *pSize){
   27923   int rc;
   27924   struct stat buf;
   27925   assert( id );
   27926   rc = osFstat(((unixFile*)id)->h, &buf);
   27927   SimulateIOError( rc=1 );
   27928   if( rc!=0 ){
   27929     ((unixFile*)id)->lastErrno = errno;
   27930     return unixLogError(SQLITE_IOERR_FSTAT, "fstat", ((unixFile*)id)->zPath);
   27931   }
   27932   *pSize = buf.st_size;
   27933 
   27934   /* When opening a zero-size database, the findInodeInfo() procedure
   27935   ** writes a single byte into that file in order to work around a bug
   27936   ** in the OS-X msdos filesystem.  In order to avoid problems with upper
   27937   ** layers, we need to report this file size as zero even though it is
   27938   ** really 1.   Ticket #3260.
   27939   */
   27940   if( *pSize==1 ) *pSize = 0;
   27941 
   27942 
   27943   return SQLITE_OK;
   27944 }
   27945 
   27946 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
   27947 /*
   27948 ** Handler for proxy-locking file-control verbs.  Defined below in the
   27949 ** proxying locking division.
   27950 */
   27951 static int proxyFileControl(sqlite3_file*,int,void*);
   27952 #endif
   27953 
   27954 /*
   27955 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
   27956 ** file-control operation.  Enlarge the database to nBytes in size
   27957 ** (rounded up to the next chunk-size).  If the database is already
   27958 ** nBytes or larger, this routine is a no-op.
   27959 */
   27960 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
   27961   if( pFile->szChunk>0 ){
   27962     i64 nSize;                    /* Required file size */
   27963     struct stat buf;              /* Used to hold return values of fstat() */
   27964 
   27965     if( osFstat(pFile->h, &buf) ) {
   27966       return unixLogError(SQLITE_IOERR_FSTAT, "fstat", pFile->zPath);
   27967     }
   27968 
   27969     nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
   27970     if( nSize>(i64)buf.st_size ){
   27971 
   27972 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
   27973       /* The code below is handling the return value of osFallocate()
   27974       ** correctly. posix_fallocate() is defined to "returns zero on success,
   27975       ** or an error number on  failure". See the manpage for details. */
   27976       int err;
   27977       do{
   27978         err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
   27979       }while( err==EINTR );
   27980       if( err ) return SQLITE_IOERR_WRITE;
   27981 #else
   27982       /* If the OS does not have posix_fallocate(), fake it. First use
   27983       ** ftruncate() to set the file size, then write a single byte to
   27984       ** the last byte in each block within the extended region. This
   27985       ** is the same technique used by glibc to implement posix_fallocate()
   27986       ** on systems that do not have a real fallocate() system call.
   27987       */
   27988       int nBlk = buf.st_blksize;  /* File-system block size */
   27989       i64 iWrite;                 /* Next offset to write to */
   27990 
   27991       if( robust_ftruncate(pFile->h, nSize) ){
   27992         pFile->lastErrno = errno;
   27993         return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
   27994       }
   27995       iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
   27996       while( iWrite<nSize ){
   27997         int nWrite = seekAndWrite(pFile, iWrite, "", 1);
   27998         if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
   27999         iWrite += nBlk;
   28000       }
   28001 #endif
   28002     }
   28003   }
   28004 
   28005 #if SQLITE_MAX_MMAP_SIZE>0
   28006   if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
   28007     int rc;
   28008     if( pFile->szChunk<=0 ){
   28009       if( robust_ftruncate(pFile->h, nByte) ){
   28010         pFile->lastErrno = errno;
   28011         return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
   28012       }
   28013     }
   28014 
   28015     rc = unixMapfile(pFile, nByte);
   28016     return rc;
   28017   }
   28018 #endif
   28019 
   28020   return SQLITE_OK;
   28021 }
   28022 
   28023 /*
   28024 ** If *pArg is inititially negative then this is a query.  Set *pArg to
   28025 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
   28026 **
   28027 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
   28028 */
   28029 static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
   28030   if( *pArg<0 ){
   28031     *pArg = (pFile->ctrlFlags & mask)!=0;
   28032   }else if( (*pArg)==0 ){
   28033     pFile->ctrlFlags &= ~mask;
   28034   }else{
   28035     pFile->ctrlFlags |= mask;
   28036   }
   28037 }
   28038 
   28039 /* Forward declaration */
   28040 static int unixGetTempname(int nBuf, char *zBuf);
   28041 
   28042 /*
   28043 ** Information and control of an open file handle.
   28044 */
   28045 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
   28046   unixFile *pFile = (unixFile*)id;
   28047   switch( op ){
   28048     case SQLITE_FCNTL_LOCKSTATE: {
   28049       *(int*)pArg = pFile->eFileLock;
   28050       return SQLITE_OK;
   28051     }
   28052     case SQLITE_LAST_ERRNO: {
   28053       *(int*)pArg = pFile->lastErrno;
   28054       return SQLITE_OK;
   28055     }
   28056     case SQLITE_FCNTL_CHUNK_SIZE: {
   28057       pFile->szChunk = *(int *)pArg;
   28058       return SQLITE_OK;
   28059     }
   28060     case SQLITE_FCNTL_SIZE_HINT: {
   28061       int rc;
   28062       SimulateIOErrorBenign(1);
   28063       rc = fcntlSizeHint(pFile, *(i64 *)pArg);
   28064       SimulateIOErrorBenign(0);
   28065       return rc;
   28066     }
   28067     case SQLITE_FCNTL_PERSIST_WAL: {
   28068       unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
   28069       return SQLITE_OK;
   28070     }
   28071     case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
   28072       unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
   28073       return SQLITE_OK;
   28074     }
   28075     case SQLITE_FCNTL_VFSNAME: {
   28076       *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
   28077       return SQLITE_OK;
   28078     }
   28079     case SQLITE_FCNTL_TEMPFILENAME: {
   28080       char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
   28081       if( zTFile ){
   28082         unixGetTempname(pFile->pVfs->mxPathname, zTFile);
   28083         *(char**)pArg = zTFile;
   28084       }
   28085       return SQLITE_OK;
   28086     }
   28087     case SQLITE_FCNTL_HAS_MOVED: {
   28088       *(int*)pArg = fileHasMoved(pFile);
   28089       return SQLITE_OK;
   28090     }
   28091 #if SQLITE_MAX_MMAP_SIZE>0
   28092     case SQLITE_FCNTL_MMAP_SIZE: {
   28093       i64 newLimit = *(i64*)pArg;
   28094       int rc = SQLITE_OK;
   28095       if( newLimit>sqlite3GlobalConfig.mxMmap ){
   28096         newLimit = sqlite3GlobalConfig.mxMmap;
   28097       }
   28098       *(i64*)pArg = pFile->mmapSizeMax;
   28099       if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
   28100         pFile->mmapSizeMax = newLimit;
   28101         if( pFile->mmapSize>0 ){
   28102           unixUnmapfile(pFile);
   28103           rc = unixMapfile(pFile, -1);
   28104         }
   28105       }
   28106       return rc;
   28107     }
   28108 #endif
   28109 #ifdef SQLITE_DEBUG
   28110     /* The pager calls this method to signal that it has done
   28111     ** a rollback and that the database is therefore unchanged and
   28112     ** it hence it is OK for the transaction change counter to be
   28113     ** unchanged.
   28114     */
   28115     case SQLITE_FCNTL_DB_UNCHANGED: {
   28116       ((unixFile*)id)->dbUpdate = 0;
   28117       return SQLITE_OK;
   28118     }
   28119 #endif
   28120 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
   28121     case SQLITE_SET_LOCKPROXYFILE:
   28122     case SQLITE_GET_LOCKPROXYFILE: {
   28123       return proxyFileControl(id,op,pArg);
   28124     }
   28125 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
   28126   }
   28127   return SQLITE_NOTFOUND;
   28128 }
   28129 
   28130 /*
   28131 ** Return the sector size in bytes of the underlying block device for
   28132 ** the specified file. This is almost always 512 bytes, but may be
   28133 ** larger for some devices.
   28134 **
   28135 ** SQLite code assumes this function cannot fail. It also assumes that
   28136 ** if two files are created in the same file-system directory (i.e.
   28137 ** a database and its journal file) that the sector size will be the
   28138 ** same for both.
   28139 */
   28140 #ifndef __QNXNTO__
   28141 static int unixSectorSize(sqlite3_file *NotUsed){
   28142   UNUSED_PARAMETER(NotUsed);
   28143   return SQLITE_DEFAULT_SECTOR_SIZE;
   28144 }
   28145 #endif
   28146 
   28147 /*
   28148 ** The following version of unixSectorSize() is optimized for QNX.
   28149 */
   28150 #ifdef __QNXNTO__
   28151 #include <sys/dcmd_blk.h>
   28152 #include <sys/statvfs.h>
   28153 static int unixSectorSize(sqlite3_file *id){
   28154   unixFile *pFile = (unixFile*)id;
   28155   if( pFile->sectorSize == 0 ){
   28156     struct statvfs fsInfo;
   28157 
   28158     /* Set defaults for non-supported filesystems */
   28159     pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
   28160     pFile->deviceCharacteristics = 0;
   28161     if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
   28162       return pFile->sectorSize;
   28163     }
   28164 
   28165     if( !strcmp(fsInfo.f_basetype, "tmp") ) {
   28166       pFile->sectorSize = fsInfo.f_bsize;
   28167       pFile->deviceCharacteristics =
   28168         SQLITE_IOCAP_ATOMIC4K |       /* All ram filesystem writes are atomic */
   28169         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
   28170                                       ** the write succeeds */
   28171         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
   28172                                       ** so it is ordered */
   28173         0;
   28174     }else if( strstr(fsInfo.f_basetype, "etfs") ){
   28175       pFile->sectorSize = fsInfo.f_bsize;
   28176       pFile->deviceCharacteristics =
   28177         /* etfs cluster size writes are atomic */
   28178         (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
   28179         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
   28180                                       ** the write succeeds */
   28181         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
   28182                                       ** so it is ordered */
   28183         0;
   28184     }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
   28185       pFile->sectorSize = fsInfo.f_bsize;
   28186       pFile->deviceCharacteristics =
   28187         SQLITE_IOCAP_ATOMIC |         /* All filesystem writes are atomic */
   28188         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
   28189                                       ** the write succeeds */
   28190         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
   28191                                       ** so it is ordered */
   28192         0;
   28193     }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
   28194       pFile->sectorSize = fsInfo.f_bsize;
   28195       pFile->deviceCharacteristics =
   28196         /* full bitset of atomics from max sector size and smaller */
   28197         ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
   28198         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
   28199                                       ** so it is ordered */
   28200         0;
   28201     }else if( strstr(fsInfo.f_basetype, "dos") ){
   28202       pFile->sectorSize = fsInfo.f_bsize;
   28203       pFile->deviceCharacteristics =
   28204         /* full bitset of atomics from max sector size and smaller */
   28205         ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
   28206         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
   28207                                       ** so it is ordered */
   28208         0;
   28209     }else{
   28210       pFile->deviceCharacteristics =
   28211         SQLITE_IOCAP_ATOMIC512 |      /* blocks are atomic */
   28212         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
   28213                                       ** the write succeeds */
   28214         0;
   28215     }
   28216   }
   28217   /* Last chance verification.  If the sector size isn't a multiple of 512
   28218   ** then it isn't valid.*/
   28219   if( pFile->sectorSize % 512 != 0 ){
   28220     pFile->deviceCharacteristics = 0;
   28221     pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
   28222   }
   28223   return pFile->sectorSize;
   28224 }
   28225 #endif /* __QNXNTO__ */
   28226 
   28227 /*
   28228 ** Return the device characteristics for the file.
   28229 **
   28230 ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
   28231 ** However, that choice is contraversial since technically the underlying
   28232 ** file system does not always provide powersafe overwrites.  (In other
   28233 ** words, after a power-loss event, parts of the file that were never
   28234 ** written might end up being altered.)  However, non-PSOW behavior is very,
   28235 ** very rare.  And asserting PSOW makes a large reduction in the amount
   28236 ** of required I/O for journaling, since a lot of padding is eliminated.
   28237 **  Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
   28238 ** available to turn it off and URI query parameter available to turn it off.
   28239 */
   28240 static int unixDeviceCharacteristics(sqlite3_file *id){
   28241   unixFile *p = (unixFile*)id;
   28242   int rc = 0;
   28243 #ifdef __QNXNTO__
   28244   if( p->sectorSize==0 ) unixSectorSize(id);
   28245   rc = p->deviceCharacteristics;
   28246 #endif
   28247   if( p->ctrlFlags & UNIXFILE_PSOW ){
   28248     rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
   28249   }
   28250   return rc;
   28251 }
   28252 
   28253 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
   28254 
   28255 /*
   28256 ** Return the system page size.
   28257 **
   28258 ** This function should not be called directly by other code in this file.
   28259 ** Instead, it should be called via macro osGetpagesize().
   28260 */
   28261 static int unixGetpagesize(void){
   28262 #if defined(_BSD_SOURCE)
   28263   return getpagesize();
   28264 #else
   28265   return (int)sysconf(_SC_PAGESIZE);
   28266 #endif
   28267 }
   28268 
   28269 #endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
   28270 
   28271 #ifndef SQLITE_OMIT_WAL
   28272 
   28273 /*
   28274 ** Object used to represent an shared memory buffer.
   28275 **
   28276 ** When multiple threads all reference the same wal-index, each thread
   28277 ** has its own unixShm object, but they all point to a single instance
   28278 ** of this unixShmNode object.  In other words, each wal-index is opened
   28279 ** only once per process.
   28280 **
   28281 ** Each unixShmNode object is connected to a single unixInodeInfo object.
   28282 ** We could coalesce this object into unixInodeInfo, but that would mean
   28283 ** every open file that does not use shared memory (in other words, most
   28284 ** open files) would have to carry around this extra information.  So
   28285 ** the unixInodeInfo object contains a pointer to this unixShmNode object
   28286 ** and the unixShmNode object is created only when needed.
   28287 **
   28288 ** unixMutexHeld() must be true when creating or destroying
   28289 ** this object or while reading or writing the following fields:
   28290 **
   28291 **      nRef
   28292 **
   28293 ** The following fields are read-only after the object is created:
   28294 **
   28295 **      fid
   28296 **      zFilename
   28297 **
   28298 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
   28299 ** unixMutexHeld() is true when reading or writing any other field
   28300 ** in this structure.
   28301 */
   28302 struct unixShmNode {
   28303   unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
   28304   sqlite3_mutex *mutex;      /* Mutex to access this object */
   28305   char *zFilename;           /* Name of the mmapped file */
   28306   int h;                     /* Open file descriptor */
   28307   int szRegion;              /* Size of shared-memory regions */
   28308   u16 nRegion;               /* Size of array apRegion */
   28309   u8 isReadonly;             /* True if read-only */
   28310   char **apRegion;           /* Array of mapped shared-memory regions */
   28311   int nRef;                  /* Number of unixShm objects pointing to this */
   28312   unixShm *pFirst;           /* All unixShm objects pointing to this */
   28313 #ifdef SQLITE_DEBUG
   28314   u8 exclMask;               /* Mask of exclusive locks held */
   28315   u8 sharedMask;             /* Mask of shared locks held */
   28316   u8 nextShmId;              /* Next available unixShm.id value */
   28317 #endif
   28318 };
   28319 
   28320 /*
   28321 ** Structure used internally by this VFS to record the state of an
   28322 ** open shared memory connection.
   28323 **
   28324 ** The following fields are initialized when this object is created and
   28325 ** are read-only thereafter:
   28326 **
   28327 **    unixShm.pFile
   28328 **    unixShm.id
   28329 **
   28330 ** All other fields are read/write.  The unixShm.pFile->mutex must be held
   28331 ** while accessing any read/write fields.
   28332 */
   28333 struct unixShm {
   28334   unixShmNode *pShmNode;     /* The underlying unixShmNode object */
   28335   unixShm *pNext;            /* Next unixShm with the same unixShmNode */
   28336   u8 hasMutex;               /* True if holding the unixShmNode mutex */
   28337   u8 id;                     /* Id of this connection within its unixShmNode */
   28338   u16 sharedMask;            /* Mask of shared locks held */
   28339   u16 exclMask;              /* Mask of exclusive locks held */
   28340 };
   28341 
   28342 /*
   28343 ** Constants used for locking
   28344 */
   28345 #define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
   28346 #define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
   28347 
   28348 /*
   28349 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
   28350 **
   28351 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
   28352 ** otherwise.
   28353 */
   28354 static int unixShmSystemLock(
   28355   unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
   28356   int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
   28357   int ofst,              /* First byte of the locking range */
   28358   int n                  /* Number of bytes to lock */
   28359 ){
   28360   struct flock f;       /* The posix advisory locking structure */
   28361   int rc = SQLITE_OK;   /* Result code form fcntl() */
   28362 
   28363   /* Access to the unixShmNode object is serialized by the caller */
   28364   assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
   28365 
   28366   /* Shared locks never span more than one byte */
   28367   assert( n==1 || lockType!=F_RDLCK );
   28368 
   28369   /* Locks are within range */
   28370   assert( n>=1 && n<SQLITE_SHM_NLOCK );
   28371 
   28372   if( pShmNode->h>=0 ){
   28373     /* Initialize the locking parameters */
   28374     memset(&f, 0, sizeof(f));
   28375     f.l_type = lockType;
   28376     f.l_whence = SEEK_SET;
   28377     f.l_start = ofst;
   28378     f.l_len = n;
   28379 
   28380     rc = osFcntl(pShmNode->h, F_SETLK, &f);
   28381     rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
   28382   }
   28383 
   28384   /* Update the global lock state and do debug tracing */
   28385 #ifdef SQLITE_DEBUG
   28386   { u16 mask;
   28387   OSTRACE(("SHM-LOCK "));
   28388   mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
   28389   if( rc==SQLITE_OK ){
   28390     if( lockType==F_UNLCK ){
   28391       OSTRACE(("unlock %d ok", ofst));
   28392       pShmNode->exclMask &= ~mask;
   28393       pShmNode->sharedMask &= ~mask;
   28394     }else if( lockType==F_RDLCK ){
   28395       OSTRACE(("read-lock %d ok", ofst));
   28396       pShmNode->exclMask &= ~mask;
   28397       pShmNode->sharedMask |= mask;
   28398     }else{
   28399       assert( lockType==F_WRLCK );
   28400       OSTRACE(("write-lock %d ok", ofst));
   28401       pShmNode->exclMask |= mask;
   28402       pShmNode->sharedMask &= ~mask;
   28403     }
   28404   }else{
   28405     if( lockType==F_UNLCK ){
   28406       OSTRACE(("unlock %d failed", ofst));
   28407     }else if( lockType==F_RDLCK ){
   28408       OSTRACE(("read-lock failed"));
   28409     }else{
   28410       assert( lockType==F_WRLCK );
   28411       OSTRACE(("write-lock %d failed", ofst));
   28412     }
   28413   }
   28414   OSTRACE((" - afterwards %03x,%03x\n",
   28415            pShmNode->sharedMask, pShmNode->exclMask));
   28416   }
   28417 #endif
   28418 
   28419   return rc;
   28420 }
   28421 
   28422 /*
   28423 ** Return the minimum number of 32KB shm regions that should be mapped at
   28424 ** a time, assuming that each mapping must be an integer multiple of the
   28425 ** current system page-size.
   28426 **
   28427 ** Usually, this is 1. The exception seems to be systems that are configured
   28428 ** to use 64KB pages - in this case each mapping must cover at least two
   28429 ** shm regions.
   28430 */
   28431 static int unixShmRegionPerMap(void){
   28432   int shmsz = 32*1024;            /* SHM region size */
   28433   int pgsz = osGetpagesize();   /* System page size */
   28434   assert( ((pgsz-1)&pgsz)==0 );   /* Page size must be a power of 2 */
   28435   if( pgsz<shmsz ) return 1;
   28436   return pgsz/shmsz;
   28437 }
   28438 
   28439 /*
   28440 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
   28441 **
   28442 ** This is not a VFS shared-memory method; it is a utility function called
   28443 ** by VFS shared-memory methods.
   28444 */
   28445 static void unixShmPurge(unixFile *pFd){
   28446   unixShmNode *p = pFd->pInode->pShmNode;
   28447   assert( unixMutexHeld() );
   28448   if( p && p->nRef==0 ){
   28449     int nShmPerMap = unixShmRegionPerMap();
   28450     int i;
   28451     assert( p->pInode==pFd->pInode );
   28452     sqlite3_mutex_free(p->mutex);
   28453     for(i=0; i<p->nRegion; i+=nShmPerMap){
   28454       if( p->h>=0 ){
   28455         osMunmap(p->apRegion[i], p->szRegion);
   28456       }else{
   28457         sqlite3_free(p->apRegion[i]);
   28458       }
   28459     }
   28460     sqlite3_free(p->apRegion);
   28461     if( p->h>=0 ){
   28462       robust_close(pFd, p->h, __LINE__);
   28463       p->h = -1;
   28464     }
   28465     p->pInode->pShmNode = 0;
   28466     sqlite3_free(p);
   28467   }
   28468 }
   28469 
   28470 /*
   28471 ** Open a shared-memory area associated with open database file pDbFd.
   28472 ** This particular implementation uses mmapped files.
   28473 **
   28474 ** The file used to implement shared-memory is in the same directory
   28475 ** as the open database file and has the same name as the open database
   28476 ** file with the "-shm" suffix added.  For example, if the database file
   28477 ** is "/home/user1/config.db" then the file that is created and mmapped
   28478 ** for shared memory will be called "/home/user1/config.db-shm".
   28479 **
   28480 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
   28481 ** some other tmpfs mount. But if a file in a different directory
   28482 ** from the database file is used, then differing access permissions
   28483 ** or a chroot() might cause two different processes on the same
   28484 ** database to end up using different files for shared memory -
   28485 ** meaning that their memory would not really be shared - resulting
   28486 ** in database corruption.  Nevertheless, this tmpfs file usage
   28487 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
   28488 ** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
   28489 ** option results in an incompatible build of SQLite;  builds of SQLite
   28490 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
   28491 ** same database file at the same time, database corruption will likely
   28492 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
   28493 ** "unsupported" and may go away in a future SQLite release.
   28494 **
   28495 ** When opening a new shared-memory file, if no other instances of that
   28496 ** file are currently open, in this process or in other processes, then
   28497 ** the file must be truncated to zero length or have its header cleared.
   28498 **
   28499 ** If the original database file (pDbFd) is using the "unix-excl" VFS
   28500 ** that means that an exclusive lock is held on the database file and
   28501 ** that no other processes are able to read or write the database.  In
   28502 ** that case, we do not really need shared memory.  No shared memory
   28503 ** file is created.  The shared memory will be simulated with heap memory.
   28504 */
   28505 static int unixOpenSharedMemory(unixFile *pDbFd){
   28506   struct unixShm *p = 0;          /* The connection to be opened */
   28507   struct unixShmNode *pShmNode;   /* The underlying mmapped file */
   28508   int rc;                         /* Result code */
   28509   unixInodeInfo *pInode;          /* The inode of fd */
   28510   char *zShmFilename;             /* Name of the file used for SHM */
   28511   int nShmFilename;               /* Size of the SHM filename in bytes */
   28512 
   28513   /* Allocate space for the new unixShm object. */
   28514   p = sqlite3_malloc( sizeof(*p) );
   28515   if( p==0 ) return SQLITE_NOMEM;
   28516   memset(p, 0, sizeof(*p));
   28517   assert( pDbFd->pShm==0 );
   28518 
   28519   /* Check to see if a unixShmNode object already exists. Reuse an existing
   28520   ** one if present. Create a new one if necessary.
   28521   */
   28522   unixEnterMutex();
   28523   pInode = pDbFd->pInode;
   28524   pShmNode = pInode->pShmNode;
   28525   if( pShmNode==0 ){
   28526     struct stat sStat;                 /* fstat() info for database file */
   28527 
   28528     /* Call fstat() to figure out the permissions on the database file. If
   28529     ** a new *-shm file is created, an attempt will be made to create it
   28530     ** with the same permissions.
   28531     */
   28532     if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
   28533       rc = unixLogError(SQLITE_IOERR_FSTAT, "fstat", pDbFd->zPath);
   28534       goto shm_open_err;
   28535     }
   28536 
   28537 #ifdef SQLITE_SHM_DIRECTORY
   28538     nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
   28539 #else
   28540     nShmFilename = 6 + (int)strlen(pDbFd->zPath);
   28541 #endif
   28542     pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
   28543     if( pShmNode==0 ){
   28544       rc = SQLITE_NOMEM;
   28545       goto shm_open_err;
   28546     }
   28547     memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
   28548     zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
   28549 #ifdef SQLITE_SHM_DIRECTORY
   28550     sqlite3_snprintf(nShmFilename, zShmFilename,
   28551                      SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
   28552                      (u32)sStat.st_ino, (u32)sStat.st_dev);
   28553 #else
   28554     sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
   28555     sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
   28556 #endif
   28557     pShmNode->h = -1;
   28558     pDbFd->pInode->pShmNode = pShmNode;
   28559     pShmNode->pInode = pDbFd->pInode;
   28560     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
   28561     if( pShmNode->mutex==0 ){
   28562       rc = SQLITE_NOMEM;
   28563       goto shm_open_err;
   28564     }
   28565 
   28566     if( pInode->bProcessLock==0 ){
   28567       int openFlags = O_RDWR | O_CREAT;
   28568       if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
   28569         openFlags = O_RDONLY;
   28570         pShmNode->isReadonly = 1;
   28571       }
   28572       pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
   28573       if( pShmNode->h<0 ){
   28574         rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
   28575         goto shm_open_err;
   28576       }
   28577 
   28578       /* If this process is running as root, make sure that the SHM file
   28579       ** is owned by the same user that owns the original database.  Otherwise,
   28580       ** the original owner will not be able to connect.
   28581       */
   28582       osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
   28583 
   28584       /* Check to see if another process is holding the dead-man switch.
   28585       ** If not, truncate the file to zero length.
   28586       */
   28587       rc = SQLITE_OK;
   28588       if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
   28589         if( robust_ftruncate(pShmNode->h, 0) ){
   28590           rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
   28591         }
   28592       }
   28593       if( rc==SQLITE_OK ){
   28594         rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
   28595       }
   28596       if( rc ) goto shm_open_err;
   28597     }
   28598   }
   28599 
   28600   /* Make the new connection a child of the unixShmNode */
   28601   p->pShmNode = pShmNode;
   28602 #ifdef SQLITE_DEBUG
   28603   p->id = pShmNode->nextShmId++;
   28604 #endif
   28605   pShmNode->nRef++;
   28606   pDbFd->pShm = p;
   28607   unixLeaveMutex();
   28608 
   28609   /* The reference count on pShmNode has already been incremented under
   28610   ** the cover of the unixEnterMutex() mutex and the pointer from the
   28611   ** new (struct unixShm) object to the pShmNode has been set. All that is
   28612   ** left to do is to link the new object into the linked list starting
   28613   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
   28614   ** mutex.
   28615   */
   28616   sqlite3_mutex_enter(pShmNode->mutex);
   28617   p->pNext = pShmNode->pFirst;
   28618   pShmNode->pFirst = p;
   28619   sqlite3_mutex_leave(pShmNode->mutex);
   28620   return SQLITE_OK;
   28621 
   28622   /* Jump here on any error */
   28623 shm_open_err:
   28624   unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
   28625   sqlite3_free(p);
   28626   unixLeaveMutex();
   28627   return rc;
   28628 }
   28629 
   28630 /*
   28631 ** This function is called to obtain a pointer to region iRegion of the
   28632 ** shared-memory associated with the database file fd. Shared-memory regions
   28633 ** are numbered starting from zero. Each shared-memory region is szRegion
   28634 ** bytes in size.
   28635 **
   28636 ** If an error occurs, an error code is returned and *pp is set to NULL.
   28637 **
   28638 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
   28639 ** region has not been allocated (by any client, including one running in a
   28640 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
   28641 ** bExtend is non-zero and the requested shared-memory region has not yet
   28642 ** been allocated, it is allocated by this function.
   28643 **
   28644 ** If the shared-memory region has already been allocated or is allocated by
   28645 ** this call as described above, then it is mapped into this processes
   28646 ** address space (if it is not already), *pp is set to point to the mapped
   28647 ** memory and SQLITE_OK returned.
   28648 */
   28649 static int unixShmMap(
   28650   sqlite3_file *fd,               /* Handle open on database file */
   28651   int iRegion,                    /* Region to retrieve */
   28652   int szRegion,                   /* Size of regions */
   28653   int bExtend,                    /* True to extend file if necessary */
   28654   void volatile **pp              /* OUT: Mapped memory */
   28655 ){
   28656   unixFile *pDbFd = (unixFile*)fd;
   28657   unixShm *p;
   28658   unixShmNode *pShmNode;
   28659   int rc = SQLITE_OK;
   28660   int nShmPerMap = unixShmRegionPerMap();
   28661   int nReqRegion;
   28662 
   28663   /* If the shared-memory file has not yet been opened, open it now. */
   28664   if( pDbFd->pShm==0 ){
   28665     rc = unixOpenSharedMemory(pDbFd);
   28666     if( rc!=SQLITE_OK ) return rc;
   28667   }
   28668 
   28669   p = pDbFd->pShm;
   28670   pShmNode = p->pShmNode;
   28671   sqlite3_mutex_enter(pShmNode->mutex);
   28672   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
   28673   assert( pShmNode->pInode==pDbFd->pInode );
   28674   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
   28675   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
   28676 
   28677   /* Minimum number of regions required to be mapped. */
   28678   nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
   28679 
   28680   if( pShmNode->nRegion<nReqRegion ){
   28681     char **apNew;                      /* New apRegion[] array */
   28682     int nByte = nReqRegion*szRegion;   /* Minimum required file size */
   28683     struct stat sStat;                 /* Used by fstat() */
   28684 
   28685     pShmNode->szRegion = szRegion;
   28686 
   28687     if( pShmNode->h>=0 ){
   28688       /* The requested region is not mapped into this processes address space.
   28689       ** Check to see if it has been allocated (i.e. if the wal-index file is
   28690       ** large enough to contain the requested region).
   28691       */
   28692       if( osFstat(pShmNode->h, &sStat) ){
   28693         rc = SQLITE_IOERR_SHMSIZE;
   28694         goto shmpage_out;
   28695       }
   28696 
   28697       if( sStat.st_size<nByte ){
   28698         /* The requested memory region does not exist. If bExtend is set to
   28699         ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
   28700         */
   28701         if( !bExtend ){
   28702           goto shmpage_out;
   28703         }
   28704 
   28705         /* Alternatively, if bExtend is true, extend the file. Do this by
   28706         ** writing a single byte to the end of each (OS) page being
   28707         ** allocated or extended. Technically, we need only write to the
   28708         ** last page in order to extend the file. But writing to all new
   28709         ** pages forces the OS to allocate them immediately, which reduces
   28710         ** the chances of SIGBUS while accessing the mapped region later on.
   28711         */
   28712         else{
   28713           static const int pgsz = 4096;
   28714           int iPg;
   28715 
   28716           /* Write to the last byte of each newly allocated or extended page */
   28717           assert( (nByte % pgsz)==0 );
   28718           for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
   28719             if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
   28720               const char *zFile = pShmNode->zFilename;
   28721               rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
   28722               goto shmpage_out;
   28723             }
   28724           }
   28725         }
   28726       }
   28727     }
   28728 
   28729     /* Map the requested memory region into this processes address space. */
   28730     apNew = (char **)sqlite3_realloc(
   28731         pShmNode->apRegion, nReqRegion*sizeof(char *)
   28732     );
   28733     if( !apNew ){
   28734       rc = SQLITE_IOERR_NOMEM;
   28735       goto shmpage_out;
   28736     }
   28737     pShmNode->apRegion = apNew;
   28738     while( pShmNode->nRegion<nReqRegion ){
   28739       int nMap = szRegion*nShmPerMap;
   28740       int i;
   28741       void *pMem;
   28742       if( pShmNode->h>=0 ){
   28743         pMem = osMmap(0, nMap,
   28744             pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
   28745             MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
   28746         );
   28747         if( pMem==MAP_FAILED ){
   28748           rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
   28749           goto shmpage_out;
   28750         }
   28751       }else{
   28752         pMem = sqlite3_malloc(szRegion);
   28753         if( pMem==0 ){
   28754           rc = SQLITE_NOMEM;
   28755           goto shmpage_out;
   28756         }
   28757         memset(pMem, 0, szRegion);
   28758       }
   28759 
   28760       for(i=0; i<nShmPerMap; i++){
   28761         pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
   28762       }
   28763       pShmNode->nRegion += nShmPerMap;
   28764     }
   28765   }
   28766 
   28767 shmpage_out:
   28768   if( pShmNode->nRegion>iRegion ){
   28769     *pp = pShmNode->apRegion[iRegion];
   28770   }else{
   28771     *pp = 0;
   28772   }
   28773   if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
   28774   sqlite3_mutex_leave(pShmNode->mutex);
   28775   return rc;
   28776 }
   28777 
   28778 /*
   28779 ** Change the lock state for a shared-memory segment.
   28780 **
   28781 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
   28782 ** different here than in posix.  In xShmLock(), one can go from unlocked
   28783 ** to shared and back or from unlocked to exclusive and back.  But one may
   28784 ** not go from shared to exclusive or from exclusive to shared.
   28785 */
   28786 static int unixShmLock(
   28787   sqlite3_file *fd,          /* Database file holding the shared memory */
   28788   int ofst,                  /* First lock to acquire or release */
   28789   int n,                     /* Number of locks to acquire or release */
   28790   int flags                  /* What to do with the lock */
   28791 ){
   28792   unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
   28793   unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
   28794   unixShm *pX;                          /* For looping over all siblings */
   28795   unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
   28796   int rc = SQLITE_OK;                   /* Result code */
   28797   u16 mask;                             /* Mask of locks to take or release */
   28798 
   28799   assert( pShmNode==pDbFd->pInode->pShmNode );
   28800   assert( pShmNode->pInode==pDbFd->pInode );
   28801   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
   28802   assert( n>=1 );
   28803   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
   28804        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
   28805        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
   28806        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
   28807   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
   28808   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
   28809   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
   28810 
   28811   mask = (1<<(ofst+n)) - (1<<ofst);
   28812   assert( n>1 || mask==(1<<ofst) );
   28813   sqlite3_mutex_enter(pShmNode->mutex);
   28814   if( flags & SQLITE_SHM_UNLOCK ){
   28815     u16 allMask = 0; /* Mask of locks held by siblings */
   28816 
   28817     /* See if any siblings hold this same lock */
   28818     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
   28819       if( pX==p ) continue;
   28820       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
   28821       allMask |= pX->sharedMask;
   28822     }
   28823 
   28824     /* Unlock the system-level locks */
   28825     if( (mask & allMask)==0 ){
   28826       rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
   28827     }else{
   28828       rc = SQLITE_OK;
   28829     }
   28830 
   28831     /* Undo the local locks */
   28832     if( rc==SQLITE_OK ){
   28833       p->exclMask &= ~mask;
   28834       p->sharedMask &= ~mask;
   28835     }
   28836   }else if( flags & SQLITE_SHM_SHARED ){
   28837     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
   28838 
   28839     /* Find out which shared locks are already held by sibling connections.
   28840     ** If any sibling already holds an exclusive lock, go ahead and return
   28841     ** SQLITE_BUSY.
   28842     */
   28843     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
   28844       if( (pX->exclMask & mask)!=0 ){
   28845         rc = SQLITE_BUSY;
   28846         break;
   28847       }
   28848       allShared |= pX->sharedMask;
   28849     }
   28850 
   28851     /* Get shared locks at the system level, if necessary */
   28852     if( rc==SQLITE_OK ){
   28853       if( (allShared & mask)==0 ){
   28854         rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
   28855       }else{
   28856         rc = SQLITE_OK;
   28857       }
   28858     }
   28859 
   28860     /* Get the local shared locks */
   28861     if( rc==SQLITE_OK ){
   28862       p->sharedMask |= mask;
   28863     }
   28864   }else{
   28865     /* Make sure no sibling connections hold locks that will block this
   28866     ** lock.  If any do, return SQLITE_BUSY right away.
   28867     */
   28868     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
   28869       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
   28870         rc = SQLITE_BUSY;
   28871         break;
   28872       }
   28873     }
   28874 
   28875     /* Get the exclusive locks at the system level.  Then if successful
   28876     ** also mark the local connection as being locked.
   28877     */
   28878     if( rc==SQLITE_OK ){
   28879       rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
   28880       if( rc==SQLITE_OK ){
   28881         assert( (p->sharedMask & mask)==0 );
   28882         p->exclMask |= mask;
   28883       }
   28884     }
   28885   }
   28886   sqlite3_mutex_leave(pShmNode->mutex);
   28887   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
   28888            p->id, getpid(), p->sharedMask, p->exclMask));
   28889   return rc;
   28890 }
   28891 
   28892 /*
   28893 ** Implement a memory barrier or memory fence on shared memory.
   28894 **
   28895 ** All loads and stores begun before the barrier must complete before
   28896 ** any load or store begun after the barrier.
   28897 */
   28898 static void unixShmBarrier(
   28899   sqlite3_file *fd                /* Database file holding the shared memory */
   28900 ){
   28901   UNUSED_PARAMETER(fd);
   28902   unixEnterMutex();
   28903   unixLeaveMutex();
   28904 }
   28905 
   28906 /*
   28907 ** Close a connection to shared-memory.  Delete the underlying
   28908 ** storage if deleteFlag is true.
   28909 **
   28910 ** If there is no shared memory associated with the connection then this
   28911 ** routine is a harmless no-op.
   28912 */
   28913 static int unixShmUnmap(
   28914   sqlite3_file *fd,               /* The underlying database file */
   28915   int deleteFlag                  /* Delete shared-memory if true */
   28916 ){
   28917   unixShm *p;                     /* The connection to be closed */
   28918   unixShmNode *pShmNode;          /* The underlying shared-memory file */
   28919   unixShm **pp;                   /* For looping over sibling connections */
   28920   unixFile *pDbFd;                /* The underlying database file */
   28921 
   28922   pDbFd = (unixFile*)fd;
   28923   p = pDbFd->pShm;
   28924   if( p==0 ) return SQLITE_OK;
   28925   pShmNode = p->pShmNode;
   28926 
   28927   assert( pShmNode==pDbFd->pInode->pShmNode );
   28928   assert( pShmNode->pInode==pDbFd->pInode );
   28929 
   28930   /* Remove connection p from the set of connections associated
   28931   ** with pShmNode */
   28932   sqlite3_mutex_enter(pShmNode->mutex);
   28933   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
   28934   *pp = p->pNext;
   28935 
   28936   /* Free the connection p */
   28937   sqlite3_free(p);
   28938   pDbFd->pShm = 0;
   28939   sqlite3_mutex_leave(pShmNode->mutex);
   28940 
   28941   /* If pShmNode->nRef has reached 0, then close the underlying
   28942   ** shared-memory file, too */
   28943   unixEnterMutex();
   28944   assert( pShmNode->nRef>0 );
   28945   pShmNode->nRef--;
   28946   if( pShmNode->nRef==0 ){
   28947     if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
   28948     unixShmPurge(pDbFd);
   28949   }
   28950   unixLeaveMutex();
   28951 
   28952   return SQLITE_OK;
   28953 }
   28954 
   28955 
   28956 #else
   28957 # define unixShmMap     0
   28958 # define unixShmLock    0
   28959 # define unixShmBarrier 0
   28960 # define unixShmUnmap   0
   28961 #endif /* #ifndef SQLITE_OMIT_WAL */
   28962 
   28963 #if SQLITE_MAX_MMAP_SIZE>0
   28964 /*
   28965 ** If it is currently memory mapped, unmap file pFd.
   28966 */
   28967 static void unixUnmapfile(unixFile *pFd){
   28968   assert( pFd->nFetchOut==0 );
   28969   if( pFd->pMapRegion ){
   28970     osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
   28971     pFd->pMapRegion = 0;
   28972     pFd->mmapSize = 0;
   28973     pFd->mmapSizeActual = 0;
   28974   }
   28975 }
   28976 
   28977 /*
   28978 ** Attempt to set the size of the memory mapping maintained by file
   28979 ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
   28980 **
   28981 ** If successful, this function sets the following variables:
   28982 **
   28983 **       unixFile.pMapRegion
   28984 **       unixFile.mmapSize
   28985 **       unixFile.mmapSizeActual
   28986 **
   28987 ** If unsuccessful, an error message is logged via sqlite3_log() and
   28988 ** the three variables above are zeroed. In this case SQLite should
   28989 ** continue accessing the database using the xRead() and xWrite()
   28990 ** methods.
   28991 */
   28992 static void unixRemapfile(
   28993   unixFile *pFd,                  /* File descriptor object */
   28994   i64 nNew                        /* Required mapping size */
   28995 ){
   28996   const char *zErr = "mmap";
   28997   int h = pFd->h;                      /* File descriptor open on db file */
   28998   u8 *pOrig = (u8 *)pFd->pMapRegion;   /* Pointer to current file mapping */
   28999   i64 nOrig = pFd->mmapSizeActual;     /* Size of pOrig region in bytes */
   29000   u8 *pNew = 0;                        /* Location of new mapping */
   29001   int flags = PROT_READ;               /* Flags to pass to mmap() */
   29002 
   29003   assert( pFd->nFetchOut==0 );
   29004   assert( nNew>pFd->mmapSize );
   29005   assert( nNew<=pFd->mmapSizeMax );
   29006   assert( nNew>0 );
   29007   assert( pFd->mmapSizeActual>=pFd->mmapSize );
   29008   assert( MAP_FAILED!=0 );
   29009 
   29010   if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
   29011 
   29012   if( pOrig ){
   29013 #if HAVE_MREMAP
   29014     i64 nReuse = pFd->mmapSize;
   29015 #else
   29016     const int szSyspage = osGetpagesize();
   29017     i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
   29018 #endif
   29019     u8 *pReq = &pOrig[nReuse];
   29020 
   29021     /* Unmap any pages of the existing mapping that cannot be reused. */
   29022     if( nReuse!=nOrig ){
   29023       osMunmap(pReq, nOrig-nReuse);
   29024     }
   29025 
   29026 #if HAVE_MREMAP
   29027     pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
   29028     zErr = "mremap";
   29029 #else
   29030     pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
   29031     if( pNew!=MAP_FAILED ){
   29032       if( pNew!=pReq ){
   29033         osMunmap(pNew, nNew - nReuse);
   29034         pNew = 0;
   29035       }else{
   29036         pNew = pOrig;
   29037       }
   29038     }
   29039 #endif
   29040 
   29041     /* The attempt to extend the existing mapping failed. Free it. */
   29042     if( pNew==MAP_FAILED || pNew==0 ){
   29043       osMunmap(pOrig, nReuse);
   29044     }
   29045   }
   29046 
   29047   /* If pNew is still NULL, try to create an entirely new mapping. */
   29048   if( pNew==0 ){
   29049     pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
   29050   }
   29051 
   29052   if( pNew==MAP_FAILED ){
   29053     pNew = 0;
   29054     nNew = 0;
   29055     unixLogError(SQLITE_OK, zErr, pFd->zPath);
   29056 
   29057     /* If the mmap() above failed, assume that all subsequent mmap() calls
   29058     ** will probably fail too. Fall back to using xRead/xWrite exclusively
   29059     ** in this case.  */
   29060     pFd->mmapSizeMax = 0;
   29061   }
   29062   pFd->pMapRegion = (void *)pNew;
   29063   pFd->mmapSize = pFd->mmapSizeActual = nNew;
   29064 }
   29065 
   29066 /*
   29067 ** Memory map or remap the file opened by file-descriptor pFd (if the file
   29068 ** is already mapped, the existing mapping is replaced by the new). Or, if
   29069 ** there already exists a mapping for this file, and there are still
   29070 ** outstanding xFetch() references to it, this function is a no-op.
   29071 **
   29072 ** If parameter nByte is non-negative, then it is the requested size of
   29073 ** the mapping to create. Otherwise, if nByte is less than zero, then the
   29074 ** requested size is the size of the file on disk. The actual size of the
   29075 ** created mapping is either the requested size or the value configured
   29076 ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
   29077 **
   29078 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
   29079 ** recreated as a result of outstanding references) or an SQLite error
   29080 ** code otherwise.
   29081 */
   29082 static int unixMapfile(unixFile *pFd, i64 nByte){
   29083   i64 nMap = nByte;
   29084   int rc;
   29085 
   29086   assert( nMap>=0 || pFd->nFetchOut==0 );
   29087   if( pFd->nFetchOut>0 ) return SQLITE_OK;
   29088 
   29089   if( nMap<0 ){
   29090     struct stat statbuf;          /* Low-level file information */
   29091     rc = osFstat(pFd->h, &statbuf);
   29092     if( rc!=SQLITE_OK ){
   29093       return SQLITE_IOERR_FSTAT;
   29094     }
   29095     nMap = statbuf.st_size;
   29096   }
   29097   if( nMap>pFd->mmapSizeMax ){
   29098     nMap = pFd->mmapSizeMax;
   29099   }
   29100 
   29101   if( nMap!=pFd->mmapSize ){
   29102     if( nMap>0 ){
   29103       unixRemapfile(pFd, nMap);
   29104     }else{
   29105       unixUnmapfile(pFd);
   29106     }
   29107   }
   29108 
   29109   return SQLITE_OK;
   29110 }
   29111 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
   29112 
   29113 /*
   29114 ** If possible, return a pointer to a mapping of file fd starting at offset
   29115 ** iOff. The mapping must be valid for at least nAmt bytes.
   29116 **
   29117 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
   29118 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
   29119 ** Finally, if an error does occur, return an SQLite error code. The final
   29120 ** value of *pp is undefined in this case.
   29121 **
   29122 ** If this function does return a pointer, the caller must eventually
   29123 ** release the reference by calling unixUnfetch().
   29124 */
   29125 static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
   29126 #if SQLITE_MAX_MMAP_SIZE>0
   29127   unixFile *pFd = (unixFile *)fd;   /* The underlying database file */
   29128 #endif
   29129   *pp = 0;
   29130 
   29131 #if SQLITE_MAX_MMAP_SIZE>0
   29132   if( pFd->mmapSizeMax>0 ){
   29133     if( pFd->pMapRegion==0 ){
   29134       int rc = unixMapfile(pFd, -1);
   29135       if( rc!=SQLITE_OK ) return rc;
   29136     }
   29137     if( pFd->mmapSize >= iOff+nAmt ){
   29138       *pp = &((u8 *)pFd->pMapRegion)[iOff];
   29139       pFd->nFetchOut++;
   29140     }
   29141   }
   29142 #endif
   29143   return SQLITE_OK;
   29144 }
   29145 
   29146 /*
   29147 ** If the third argument is non-NULL, then this function releases a
   29148 ** reference obtained by an earlier call to unixFetch(). The second
   29149 ** argument passed to this function must be the same as the corresponding
   29150 ** argument that was passed to the unixFetch() invocation.
   29151 **
   29152 ** Or, if the third argument is NULL, then this function is being called
   29153 ** to inform the VFS layer that, according to POSIX, any existing mapping
   29154 ** may now be invalid and should be unmapped.
   29155 */
   29156 static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
   29157 #if SQLITE_MAX_MMAP_SIZE>0
   29158   unixFile *pFd = (unixFile *)fd;   /* The underlying database file */
   29159   UNUSED_PARAMETER(iOff);
   29160 
   29161   /* If p==0 (unmap the entire file) then there must be no outstanding
   29162   ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
   29163   ** then there must be at least one outstanding.  */
   29164   assert( (p==0)==(pFd->nFetchOut==0) );
   29165 
   29166   /* If p!=0, it must match the iOff value. */
   29167   assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
   29168 
   29169   if( p ){
   29170     pFd->nFetchOut--;
   29171   }else{
   29172     unixUnmapfile(pFd);
   29173   }
   29174 
   29175   assert( pFd->nFetchOut>=0 );
   29176 #else
   29177   UNUSED_PARAMETER(fd);
   29178   UNUSED_PARAMETER(p);
   29179   UNUSED_PARAMETER(iOff);
   29180 #endif
   29181   return SQLITE_OK;
   29182 }
   29183 
   29184 /*
   29185 ** Here ends the implementation of all sqlite3_file methods.
   29186 **
   29187 ********************** End sqlite3_file Methods *******************************
   29188 ******************************************************************************/
   29189 
   29190 /*
   29191 ** This division contains definitions of sqlite3_io_methods objects that
   29192 ** implement various file locking strategies.  It also contains definitions
   29193 ** of "finder" functions.  A finder-function is used to locate the appropriate
   29194 ** sqlite3_io_methods object for a particular database file.  The pAppData
   29195 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
   29196 ** the correct finder-function for that VFS.
   29197 **
   29198 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
   29199 ** object.  The only interesting finder-function is autolockIoFinder, which
   29200 ** looks at the filesystem type and tries to guess the best locking
   29201 ** strategy from that.
   29202 **
   29203 ** For finder-funtion F, two objects are created:
   29204 **
   29205 **    (1) The real finder-function named "FImpt()".
   29206 **
   29207 **    (2) A constant pointer to this function named just "F".
   29208 **
   29209 **
   29210 ** A pointer to the F pointer is used as the pAppData value for VFS
   29211 ** objects.  We have to do this instead of letting pAppData point
   29212 ** directly at the finder-function since C90 rules prevent a void*
   29213 ** from be cast into a function pointer.
   29214 **
   29215 **
   29216 ** Each instance of this macro generates two objects:
   29217 **
   29218 **   *  A constant sqlite3_io_methods object call METHOD that has locking
   29219 **      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
   29220 **
   29221 **   *  An I/O method finder function called FINDER that returns a pointer
   29222 **      to the METHOD object in the previous bullet.
   29223 */
   29224 #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK)      \
   29225 static const sqlite3_io_methods METHOD = {                                   \
   29226    VERSION,                    /* iVersion */                                \
   29227    CLOSE,                      /* xClose */                                  \
   29228    unixRead,                   /* xRead */                                   \
   29229    unixWrite,                  /* xWrite */                                  \
   29230    unixTruncate,               /* xTruncate */                               \
   29231    unixSync,                   /* xSync */                                   \
   29232    unixFileSize,               /* xFileSize */                               \
   29233    LOCK,                       /* xLock */                                   \
   29234    UNLOCK,                     /* xUnlock */                                 \
   29235    CKLOCK,                     /* xCheckReservedLock */                      \
   29236    unixFileControl,            /* xFileControl */                            \
   29237    unixSectorSize,             /* xSectorSize */                             \
   29238    unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
   29239    unixShmMap,                 /* xShmMap */                                 \
   29240    unixShmLock,                /* xShmLock */                                \
   29241    unixShmBarrier,             /* xShmBarrier */                             \
   29242    unixShmUnmap,               /* xShmUnmap */                               \
   29243    unixFetch,                  /* xFetch */                                  \
   29244    unixUnfetch,                /* xUnfetch */                                \
   29245 };                                                                           \
   29246 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
   29247   UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
   29248   return &METHOD;                                                            \
   29249 }                                                                            \
   29250 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
   29251     = FINDER##Impl;
   29252 
   29253 /*
   29254 ** Here are all of the sqlite3_io_methods objects for each of the
   29255 ** locking strategies.  Functions that return pointers to these methods
   29256 ** are also created.
   29257 */
   29258 IOMETHODS(
   29259   posixIoFinder,            /* Finder function name */
   29260   posixIoMethods,           /* sqlite3_io_methods object name */
   29261   3,                        /* shared memory and mmap are enabled */
   29262   unixClose,                /* xClose method */
   29263   unixLock,                 /* xLock method */
   29264   unixUnlock,               /* xUnlock method */
   29265   unixCheckReservedLock     /* xCheckReservedLock method */
   29266 )
   29267 IOMETHODS(
   29268   nolockIoFinder,           /* Finder function name */
   29269   nolockIoMethods,          /* sqlite3_io_methods object name */
   29270   1,                        /* shared memory is disabled */
   29271   nolockClose,              /* xClose method */
   29272   nolockLock,               /* xLock method */
   29273   nolockUnlock,             /* xUnlock method */
   29274   nolockCheckReservedLock   /* xCheckReservedLock method */
   29275 )
   29276 IOMETHODS(
   29277   dotlockIoFinder,          /* Finder function name */
   29278   dotlockIoMethods,         /* sqlite3_io_methods object name */
   29279   1,                        /* shared memory is disabled */
   29280   dotlockClose,             /* xClose method */
   29281   dotlockLock,              /* xLock method */
   29282   dotlockUnlock,            /* xUnlock method */
   29283   dotlockCheckReservedLock  /* xCheckReservedLock method */
   29284 )
   29285 
   29286 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
   29287 IOMETHODS(
   29288   flockIoFinder,            /* Finder function name */
   29289   flockIoMethods,           /* sqlite3_io_methods object name */
   29290   1,                        /* shared memory is disabled */
   29291   flockClose,               /* xClose method */
   29292   flockLock,                /* xLock method */
   29293   flockUnlock,              /* xUnlock method */
   29294   flockCheckReservedLock    /* xCheckReservedLock method */
   29295 )
   29296 #endif
   29297 
   29298 #if OS_VXWORKS
   29299 IOMETHODS(
   29300   semIoFinder,              /* Finder function name */
   29301   semIoMethods,             /* sqlite3_io_methods object name */
   29302   1,                        /* shared memory is disabled */
   29303   semClose,                 /* xClose method */
   29304   semLock,                  /* xLock method */
   29305   semUnlock,                /* xUnlock method */
   29306   semCheckReservedLock      /* xCheckReservedLock method */
   29307 )
   29308 #endif
   29309 
   29310 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   29311 IOMETHODS(
   29312   afpIoFinder,              /* Finder function name */
   29313   afpIoMethods,             /* sqlite3_io_methods object name */
   29314   1,                        /* shared memory is disabled */
   29315   afpClose,                 /* xClose method */
   29316   afpLock,                  /* xLock method */
   29317   afpUnlock,                /* xUnlock method */
   29318   afpCheckReservedLock      /* xCheckReservedLock method */
   29319 )
   29320 #endif
   29321 
   29322 /*
   29323 ** The proxy locking method is a "super-method" in the sense that it
   29324 ** opens secondary file descriptors for the conch and lock files and
   29325 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
   29326 ** secondary files.  For this reason, the division that implements
   29327 ** proxy locking is located much further down in the file.  But we need
   29328 ** to go ahead and define the sqlite3_io_methods and finder function
   29329 ** for proxy locking here.  So we forward declare the I/O methods.
   29330 */
   29331 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   29332 static int proxyClose(sqlite3_file*);
   29333 static int proxyLock(sqlite3_file*, int);
   29334 static int proxyUnlock(sqlite3_file*, int);
   29335 static int proxyCheckReservedLock(sqlite3_file*, int*);
   29336 IOMETHODS(
   29337   proxyIoFinder,            /* Finder function name */
   29338   proxyIoMethods,           /* sqlite3_io_methods object name */
   29339   1,                        /* shared memory is disabled */
   29340   proxyClose,               /* xClose method */
   29341   proxyLock,                /* xLock method */
   29342   proxyUnlock,              /* xUnlock method */
   29343   proxyCheckReservedLock    /* xCheckReservedLock method */
   29344 )
   29345 #endif
   29346 
   29347 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
   29348 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   29349 IOMETHODS(
   29350   nfsIoFinder,               /* Finder function name */
   29351   nfsIoMethods,              /* sqlite3_io_methods object name */
   29352   1,                         /* shared memory is disabled */
   29353   unixClose,                 /* xClose method */
   29354   unixLock,                  /* xLock method */
   29355   nfsUnlock,                 /* xUnlock method */
   29356   unixCheckReservedLock      /* xCheckReservedLock method */
   29357 )
   29358 #endif
   29359 
   29360 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   29361 /*
   29362 ** This "finder" function attempts to determine the best locking strategy
   29363 ** for the database file "filePath".  It then returns the sqlite3_io_methods
   29364 ** object that implements that strategy.
   29365 **
   29366 ** This is for MacOSX only.
   29367 */
   29368 static const sqlite3_io_methods *autolockIoFinderImpl(
   29369   const char *filePath,    /* name of the database file */
   29370   unixFile *pNew           /* open file object for the database file */
   29371 ){
   29372   static const struct Mapping {
   29373     const char *zFilesystem;              /* Filesystem type name */
   29374     const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
   29375   } aMap[] = {
   29376     { "hfs",    &posixIoMethods },
   29377     { "ufs",    &posixIoMethods },
   29378     { "afpfs",  &afpIoMethods },
   29379     { "smbfs",  &afpIoMethods },
   29380     { "webdav", &nolockIoMethods },
   29381     { 0, 0 }
   29382   };
   29383   int i;
   29384   struct statfs fsInfo;
   29385   struct flock lockInfo;
   29386 
   29387   if( !filePath ){
   29388     /* If filePath==NULL that means we are dealing with a transient file
   29389     ** that does not need to be locked. */
   29390     return &nolockIoMethods;
   29391   }
   29392   if( statfs(filePath, &fsInfo) != -1 ){
   29393     if( fsInfo.f_flags & MNT_RDONLY ){
   29394       return &nolockIoMethods;
   29395     }
   29396     for(i=0; aMap[i].zFilesystem; i++){
   29397       if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
   29398         return aMap[i].pMethods;
   29399       }
   29400     }
   29401   }
   29402 
   29403   /* Default case. Handles, amongst others, "nfs".
   29404   ** Test byte-range lock using fcntl(). If the call succeeds,
   29405   ** assume that the file-system supports POSIX style locks.
   29406   */
   29407   lockInfo.l_len = 1;
   29408   lockInfo.l_start = 0;
   29409   lockInfo.l_whence = SEEK_SET;
   29410   lockInfo.l_type = F_RDLCK;
   29411   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
   29412     if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
   29413       return &nfsIoMethods;
   29414     } else {
   29415       return &posixIoMethods;
   29416     }
   29417   }else{
   29418     return &dotlockIoMethods;
   29419   }
   29420 }
   29421 static const sqlite3_io_methods
   29422   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
   29423 
   29424 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
   29425 
   29426 #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
   29427 /*
   29428 ** This "finder" function attempts to determine the best locking strategy
   29429 ** for the database file "filePath".  It then returns the sqlite3_io_methods
   29430 ** object that implements that strategy.
   29431 **
   29432 ** This is for VXWorks only.
   29433 */
   29434 static const sqlite3_io_methods *autolockIoFinderImpl(
   29435   const char *filePath,    /* name of the database file */
   29436   unixFile *pNew           /* the open file object */
   29437 ){
   29438   struct flock lockInfo;
   29439 
   29440   if( !filePath ){
   29441     /* If filePath==NULL that means we are dealing with a transient file
   29442     ** that does not need to be locked. */
   29443     return &nolockIoMethods;
   29444   }
   29445 
   29446   /* Test if fcntl() is supported and use POSIX style locks.
   29447   ** Otherwise fall back to the named semaphore method.
   29448   */
   29449   lockInfo.l_len = 1;
   29450   lockInfo.l_start = 0;
   29451   lockInfo.l_whence = SEEK_SET;
   29452   lockInfo.l_type = F_RDLCK;
   29453   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
   29454     return &posixIoMethods;
   29455   }else{
   29456     return &semIoMethods;
   29457   }
   29458 }
   29459 static const sqlite3_io_methods
   29460   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
   29461 
   29462 #endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
   29463 
   29464 /*
   29465 ** An abstract type for a pointer to a IO method finder function:
   29466 */
   29467 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
   29468 
   29469 
   29470 /****************************************************************************
   29471 **************************** sqlite3_vfs methods ****************************
   29472 **
   29473 ** This division contains the implementation of methods on the
   29474 ** sqlite3_vfs object.
   29475 */
   29476 
   29477 /*
   29478 ** Initialize the contents of the unixFile structure pointed to by pId.
   29479 */
   29480 static int fillInUnixFile(
   29481   sqlite3_vfs *pVfs,      /* Pointer to vfs object */
   29482   int h,                  /* Open file descriptor of file being opened */
   29483   sqlite3_file *pId,      /* Write to the unixFile structure here */
   29484   const char *zFilename,  /* Name of the file being opened */
   29485   int ctrlFlags           /* Zero or more UNIXFILE_* values */
   29486 ){
   29487   const sqlite3_io_methods *pLockingStyle;
   29488   unixFile *pNew = (unixFile *)pId;
   29489   int rc = SQLITE_OK;
   29490 
   29491   assert( pNew->pInode==NULL );
   29492 
   29493   /* Usually the path zFilename should not be a relative pathname. The
   29494   ** exception is when opening the proxy "conch" file in builds that
   29495   ** include the special Apple locking styles.
   29496   */
   29497 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   29498   assert( zFilename==0 || zFilename[0]=='/'
   29499     || pVfs->pAppData==(void*)&autolockIoFinder );
   29500 #else
   29501   assert( zFilename==0 || zFilename[0]=='/' );
   29502 #endif
   29503 
   29504   /* No locking occurs in temporary files */
   29505   assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
   29506 
   29507   OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
   29508   pNew->h = h;
   29509   pNew->pVfs = pVfs;
   29510   pNew->zPath = zFilename;
   29511   pNew->ctrlFlags = (u8)ctrlFlags;
   29512 #if SQLITE_MAX_MMAP_SIZE>0
   29513   pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
   29514 #endif
   29515   if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
   29516                            "psow", SQLITE_POWERSAFE_OVERWRITE) ){
   29517     pNew->ctrlFlags |= UNIXFILE_PSOW;
   29518   }
   29519   if( strcmp(pVfs->zName,"unix-excl")==0 ){
   29520     pNew->ctrlFlags |= UNIXFILE_EXCL;
   29521   }
   29522 
   29523 #if OS_VXWORKS
   29524   pNew->pId = vxworksFindFileId(zFilename);
   29525   if( pNew->pId==0 ){
   29526     ctrlFlags |= UNIXFILE_NOLOCK;
   29527     rc = SQLITE_NOMEM;
   29528   }
   29529 #endif
   29530 
   29531   if( ctrlFlags & UNIXFILE_NOLOCK ){
   29532     pLockingStyle = &nolockIoMethods;
   29533   }else{
   29534     pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
   29535 #if SQLITE_ENABLE_LOCKING_STYLE
   29536     /* Cache zFilename in the locking context (AFP and dotlock override) for
   29537     ** proxyLock activation is possible (remote proxy is based on db name)
   29538     ** zFilename remains valid until file is closed, to support */
   29539     pNew->lockingContext = (void*)zFilename;
   29540 #endif
   29541   }
   29542 
   29543   if( pLockingStyle == &posixIoMethods
   29544 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   29545     || pLockingStyle == &nfsIoMethods
   29546 #endif
   29547   ){
   29548     unixEnterMutex();
   29549     rc = findInodeInfo(pNew, &pNew->pInode);
   29550     if( rc!=SQLITE_OK ){
   29551       /* If an error occurred in findInodeInfo(), close the file descriptor
   29552       ** immediately, before releasing the mutex. findInodeInfo() may fail
   29553       ** in two scenarios:
   29554       **
   29555       **   (a) A call to fstat() failed.
   29556       **   (b) A malloc failed.
   29557       **
   29558       ** Scenario (b) may only occur if the process is holding no other
   29559       ** file descriptors open on the same file. If there were other file
   29560       ** descriptors on this file, then no malloc would be required by
   29561       ** findInodeInfo(). If this is the case, it is quite safe to close
   29562       ** handle h - as it is guaranteed that no posix locks will be released
   29563       ** by doing so.
   29564       **
   29565       ** If scenario (a) caused the error then things are not so safe. The
   29566       ** implicit assumption here is that if fstat() fails, things are in
   29567       ** such bad shape that dropping a lock or two doesn't matter much.
   29568       */
   29569       robust_close(pNew, h, __LINE__);
   29570       h = -1;
   29571     }
   29572     unixLeaveMutex();
   29573   }
   29574 
   29575 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
   29576   else if( pLockingStyle == &afpIoMethods ){
   29577     /* AFP locking uses the file path so it needs to be included in
   29578     ** the afpLockingContext.
   29579     */
   29580     afpLockingContext *pCtx;
   29581     pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
   29582     if( pCtx==0 ){
   29583       rc = SQLITE_NOMEM;
   29584     }else{
   29585       /* NB: zFilename exists and remains valid until the file is closed
   29586       ** according to requirement F11141.  So we do not need to make a
   29587       ** copy of the filename. */
   29588       pCtx->dbPath = zFilename;
   29589       pCtx->reserved = 0;
   29590       srandomdev();
   29591       unixEnterMutex();
   29592       rc = findInodeInfo(pNew, &pNew->pInode);
   29593       if( rc!=SQLITE_OK ){
   29594         sqlite3_free(pNew->lockingContext);
   29595         robust_close(pNew, h, __LINE__);
   29596         h = -1;
   29597       }
   29598       unixLeaveMutex();
   29599     }
   29600   }
   29601 #endif
   29602 
   29603   else if( pLockingStyle == &dotlockIoMethods ){
   29604     /* Dotfile locking uses the file path so it needs to be included in
   29605     ** the dotlockLockingContext
   29606     */
   29607     char *zLockFile;
   29608     int nFilename;
   29609     assert( zFilename!=0 );
   29610     nFilename = (int)strlen(zFilename) + 6;
   29611     zLockFile = (char *)sqlite3_malloc(nFilename);
   29612     if( zLockFile==0 ){
   29613       rc = SQLITE_NOMEM;
   29614     }else{
   29615       sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
   29616     }
   29617     pNew->lockingContext = zLockFile;
   29618   }
   29619 
   29620 #if OS_VXWORKS
   29621   else if( pLockingStyle == &semIoMethods ){
   29622     /* Named semaphore locking uses the file path so it needs to be
   29623     ** included in the semLockingContext
   29624     */
   29625     unixEnterMutex();
   29626     rc = findInodeInfo(pNew, &pNew->pInode);
   29627     if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
   29628       char *zSemName = pNew->pInode->aSemName;
   29629       int n;
   29630       sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
   29631                        pNew->pId->zCanonicalName);
   29632       for( n=1; zSemName[n]; n++ )
   29633         if( zSemName[n]=='/' ) zSemName[n] = '_';
   29634       pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
   29635       if( pNew->pInode->pSem == SEM_FAILED ){
   29636         rc = SQLITE_NOMEM;
   29637         pNew->pInode->aSemName[0] = '\0';
   29638       }
   29639     }
   29640     unixLeaveMutex();
   29641   }
   29642 #endif
   29643 
   29644   pNew->lastErrno = 0;
   29645 #if OS_VXWORKS
   29646   if( rc!=SQLITE_OK ){
   29647     if( h>=0 ) robust_close(pNew, h, __LINE__);
   29648     h = -1;
   29649     osUnlink(zFilename);
   29650     pNew->ctrlFlags |= UNIXFILE_DELETE;
   29651   }
   29652 #endif
   29653   if( rc!=SQLITE_OK ){
   29654     if( h>=0 ) robust_close(pNew, h, __LINE__);
   29655   }else{
   29656     pNew->pMethod = pLockingStyle;
   29657     OpenCounter(+1);
   29658     verifyDbFile(pNew);
   29659   }
   29660   return rc;
   29661 }
   29662 
   29663 /*
   29664 ** Return the name of a directory in which to put temporary files.
   29665 ** If no suitable temporary file directory can be found, return NULL.
   29666 */
   29667 static const char *unixTempFileDir(void){
   29668   static const char *azDirs[] = {
   29669      0,
   29670      0,
   29671      0,
   29672      "/var/tmp",
   29673      "/usr/tmp",
   29674      "/tmp",
   29675      0        /* List terminator */
   29676   };
   29677   unsigned int i;
   29678   struct stat buf;
   29679   const char *zDir = 0;
   29680 
   29681   azDirs[0] = sqlite3_temp_directory;
   29682   if( !azDirs[1] ) azDirs[1] = getenv("SQLITE_TMPDIR");
   29683   if( !azDirs[2] ) azDirs[2] = getenv("TMPDIR");
   29684   for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
   29685     if( zDir==0 ) continue;
   29686     if( osStat(zDir, &buf) ) continue;
   29687     if( !S_ISDIR(buf.st_mode) ) continue;
   29688     if( osAccess(zDir, 07) ) continue;
   29689     break;
   29690   }
   29691   return zDir;
   29692 }
   29693 
   29694 /*
   29695 ** Create a temporary file name in zBuf.  zBuf must be allocated
   29696 ** by the calling process and must be big enough to hold at least
   29697 ** pVfs->mxPathname bytes.
   29698 */
   29699 static int unixGetTempname(int nBuf, char *zBuf){
   29700   static const unsigned char zChars[] =
   29701     "abcdefghijklmnopqrstuvwxyz"
   29702     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
   29703     "0123456789";
   29704   unsigned int i, j;
   29705   const char *zDir;
   29706 
   29707   /* It's odd to simulate an io-error here, but really this is just
   29708   ** using the io-error infrastructure to test that SQLite handles this
   29709   ** function failing.
   29710   */
   29711   SimulateIOError( return SQLITE_IOERR );
   29712 
   29713   zDir = unixTempFileDir();
   29714   if( zDir==0 ) zDir = ".";
   29715 
   29716   /* Check that the output buffer is large enough for the temporary file
   29717   ** name. If it is not, return SQLITE_ERROR.
   29718   */
   29719   if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
   29720     return SQLITE_ERROR;
   29721   }
   29722 
   29723   do{
   29724     sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
   29725     j = (int)strlen(zBuf);
   29726     sqlite3_randomness(15, &zBuf[j]);
   29727     for(i=0; i<15; i++, j++){
   29728       zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
   29729     }
   29730     zBuf[j] = 0;
   29731     zBuf[j+1] = 0;
   29732   }while( osAccess(zBuf,0)==0 );
   29733   return SQLITE_OK;
   29734 }
   29735 
   29736 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
   29737 /*
   29738 ** Routine to transform a unixFile into a proxy-locking unixFile.
   29739 ** Implementation in the proxy-lock division, but used by unixOpen()
   29740 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
   29741 */
   29742 static int proxyTransformUnixFile(unixFile*, const char*);
   29743 #endif
   29744 
   29745 /*
   29746 ** Search for an unused file descriptor that was opened on the database
   29747 ** file (not a journal or master-journal file) identified by pathname
   29748 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
   29749 ** argument to this function.
   29750 **
   29751 ** Such a file descriptor may exist if a database connection was closed
   29752 ** but the associated file descriptor could not be closed because some
   29753 ** other file descriptor open on the same file is holding a file-lock.
   29754 ** Refer to comments in the unixClose() function and the lengthy comment
   29755 ** describing "Posix Advisory Locking" at the start of this file for
   29756 ** further details. Also, ticket #4018.
   29757 **
   29758 ** If a suitable file descriptor is found, then it is returned. If no
   29759 ** such file descriptor is located, -1 is returned.
   29760 */
   29761 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
   29762   UnixUnusedFd *pUnused = 0;
   29763 
   29764   /* Do not search for an unused file descriptor on vxworks. Not because
   29765   ** vxworks would not benefit from the change (it might, we're not sure),
   29766   ** but because no way to test it is currently available. It is better
   29767   ** not to risk breaking vxworks support for the sake of such an obscure
   29768   ** feature.  */
   29769 #if !OS_VXWORKS
   29770   struct stat sStat;                   /* Results of stat() call */
   29771 
   29772   /* A stat() call may fail for various reasons. If this happens, it is
   29773   ** almost certain that an open() call on the same path will also fail.
   29774   ** For this reason, if an error occurs in the stat() call here, it is
   29775   ** ignored and -1 is returned. The caller will try to open a new file
   29776   ** descriptor on the same path, fail, and return an error to SQLite.
   29777   **
   29778   ** Even if a subsequent open() call does succeed, the consequences of
   29779   ** not searching for a resusable file descriptor are not dire.  */
   29780   if( 0==osStat(zPath, &sStat) ){
   29781     unixInodeInfo *pInode;
   29782 
   29783     unixEnterMutex();
   29784     pInode = inodeList;
   29785     while( pInode && (pInode->fileId.dev!=sStat.st_dev
   29786                      || pInode->fileId.ino!=sStat.st_ino) ){
   29787        pInode = pInode->pNext;
   29788     }
   29789     if( pInode ){
   29790       UnixUnusedFd **pp;
   29791       for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
   29792       pUnused = *pp;
   29793       if( pUnused ){
   29794         *pp = pUnused->pNext;
   29795       }
   29796     }
   29797     unixLeaveMutex();
   29798   }
   29799 #endif    /* if !OS_VXWORKS */
   29800   return pUnused;
   29801 }
   29802 
   29803 /*
   29804 ** This function is called by unixOpen() to determine the unix permissions
   29805 ** to create new files with. If no error occurs, then SQLITE_OK is returned
   29806 ** and a value suitable for passing as the third argument to open(2) is
   29807 ** written to *pMode. If an IO error occurs, an SQLite error code is
   29808 ** returned and the value of *pMode is not modified.
   29809 **
   29810 ** In most cases cases, this routine sets *pMode to 0, which will become
   29811 ** an indication to robust_open() to create the file using
   29812 ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
   29813 ** But if the file being opened is a WAL or regular journal file, then
   29814 ** this function queries the file-system for the permissions on the
   29815 ** corresponding database file and sets *pMode to this value. Whenever
   29816 ** possible, WAL and journal files are created using the same permissions
   29817 ** as the associated database file.
   29818 **
   29819 ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
   29820 ** original filename is unavailable.  But 8_3_NAMES is only used for
   29821 ** FAT filesystems and permissions do not matter there, so just use
   29822 ** the default permissions.
   29823 */
   29824 static int findCreateFileMode(
   29825   const char *zPath,              /* Path of file (possibly) being created */
   29826   int flags,                      /* Flags passed as 4th argument to xOpen() */
   29827   mode_t *pMode,                  /* OUT: Permissions to open file with */
   29828   uid_t *pUid,                    /* OUT: uid to set on the file */
   29829   gid_t *pGid                     /* OUT: gid to set on the file */
   29830 ){
   29831   int rc = SQLITE_OK;             /* Return Code */
   29832   *pMode = 0;
   29833   *pUid = 0;
   29834   *pGid = 0;
   29835   if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
   29836     char zDb[MAX_PATHNAME+1];     /* Database file path */
   29837     int nDb;                      /* Number of valid bytes in zDb */
   29838     struct stat sStat;            /* Output of stat() on database file */
   29839 
   29840     /* zPath is a path to a WAL or journal file. The following block derives
   29841     ** the path to the associated database file from zPath. This block handles
   29842     ** the following naming conventions:
   29843     **
   29844     **   "<path to db>-journal"
   29845     **   "<path to db>-wal"
   29846     **   "<path to db>-journalNN"
   29847     **   "<path to db>-walNN"
   29848     **
   29849     ** where NN is a decimal number. The NN naming schemes are
   29850     ** used by the test_multiplex.c module.
   29851     */
   29852     nDb = sqlite3Strlen30(zPath) - 1;
   29853 #ifdef SQLITE_ENABLE_8_3_NAMES
   29854     while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
   29855     if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
   29856 #else
   29857     while( zPath[nDb]!='-' ){
   29858       assert( nDb>0 );
   29859       assert( zPath[nDb]!='\n' );
   29860       nDb--;
   29861     }
   29862 #endif
   29863     memcpy(zDb, zPath, nDb);
   29864     zDb[nDb] = '\0';
   29865 
   29866     if( 0==osStat(zDb, &sStat) ){
   29867       *pMode = sStat.st_mode & 0777;
   29868       *pUid = sStat.st_uid;
   29869       *pGid = sStat.st_gid;
   29870     }else{
   29871       rc = unixLogError(SQLITE_IOERR_FSTAT, "stat", zDb);
   29872     }
   29873   }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
   29874     *pMode = 0600;
   29875   }
   29876   return rc;
   29877 }
   29878 
   29879 /*
   29880 ** Open the file zPath.
   29881 **
   29882 ** Previously, the SQLite OS layer used three functions in place of this
   29883 ** one:
   29884 **
   29885 **     sqlite3OsOpenReadWrite();
   29886 **     sqlite3OsOpenReadOnly();
   29887 **     sqlite3OsOpenExclusive();
   29888 **
   29889 ** These calls correspond to the following combinations of flags:
   29890 **
   29891 **     ReadWrite() ->     (READWRITE | CREATE)
   29892 **     ReadOnly()  ->     (READONLY)
   29893 **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
   29894 **
   29895 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
   29896 ** true, the file was configured to be automatically deleted when the
   29897 ** file handle closed. To achieve the same effect using this new
   29898 ** interface, add the DELETEONCLOSE flag to those specified above for
   29899 ** OpenExclusive().
   29900 */
   29901 static int unixOpen(
   29902   sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
   29903   const char *zPath,           /* Pathname of file to be opened */
   29904   sqlite3_file *pFile,         /* The file descriptor to be filled in */
   29905   int flags,                   /* Input flags to control the opening */
   29906   int *pOutFlags               /* Output flags returned to SQLite core */
   29907 ){
   29908   unixFile *p = (unixFile *)pFile;
   29909   int fd = -1;                   /* File descriptor returned by open() */
   29910   int openFlags = 0;             /* Flags to pass to open() */
   29911   int eType = flags&0xFFFFFF00;  /* Type of file to open */
   29912   int noLock;                    /* True to omit locking primitives */
   29913   int rc = SQLITE_OK;            /* Function Return Code */
   29914   int ctrlFlags = 0;             /* UNIXFILE_* flags */
   29915 
   29916   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
   29917   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
   29918   int isCreate     = (flags & SQLITE_OPEN_CREATE);
   29919   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
   29920   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
   29921 #if SQLITE_ENABLE_LOCKING_STYLE
   29922   int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
   29923 #endif
   29924 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
   29925   struct statfs fsInfo;
   29926 #endif
   29927 
   29928   /* If creating a master or main-file journal, this function will open
   29929   ** a file-descriptor on the directory too. The first time unixSync()
   29930   ** is called the directory file descriptor will be fsync()ed and close()d.
   29931   */
   29932   int syncDir = (isCreate && (
   29933         eType==SQLITE_OPEN_MASTER_JOURNAL
   29934      || eType==SQLITE_OPEN_MAIN_JOURNAL
   29935      || eType==SQLITE_OPEN_WAL
   29936   ));
   29937 
   29938   /* If argument zPath is a NULL pointer, this function is required to open
   29939   ** a temporary file. Use this buffer to store the file name in.
   29940   */
   29941   char zTmpname[MAX_PATHNAME+2];
   29942   const char *zName = zPath;
   29943 
   29944   /* Check the following statements are true:
   29945   **
   29946   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
   29947   **   (b) if CREATE is set, then READWRITE must also be set, and
   29948   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
   29949   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
   29950   */
   29951   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
   29952   assert(isCreate==0 || isReadWrite);
   29953   assert(isExclusive==0 || isCreate);
   29954   assert(isDelete==0 || isCreate);
   29955 
   29956   /* The main DB, main journal, WAL file and master journal are never
   29957   ** automatically deleted. Nor are they ever temporary files.  */
   29958   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
   29959   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
   29960   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
   29961   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
   29962 
   29963   /* Assert that the upper layer has set one of the "file-type" flags. */
   29964   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
   29965        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
   29966        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
   29967        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
   29968   );
   29969 
   29970   /* Detect a pid change and reset the PRNG.  There is a race condition
   29971   ** here such that two or more threads all trying to open databases at
   29972   ** the same instant might all reset the PRNG.  But multiple resets
   29973   ** are harmless.
   29974   */
   29975   if( randomnessPid!=getpid() ){
   29976     randomnessPid = getpid();
   29977     sqlite3_randomness(0,0);
   29978   }
   29979 
   29980   memset(p, 0, sizeof(unixFile));
   29981 
   29982   if( eType==SQLITE_OPEN_MAIN_DB ){
   29983     UnixUnusedFd *pUnused;
   29984     pUnused = findReusableFd(zName, flags);
   29985     if( pUnused ){
   29986       fd = pUnused->fd;
   29987     }else{
   29988       pUnused = sqlite3_malloc(sizeof(*pUnused));
   29989       if( !pUnused ){
   29990         return SQLITE_NOMEM;
   29991       }
   29992     }
   29993     p->pUnused = pUnused;
   29994 
   29995     /* Database filenames are double-zero terminated if they are not
   29996     ** URIs with parameters.  Hence, they can always be passed into
   29997     ** sqlite3_uri_parameter(). */
   29998     assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
   29999 
   30000   }else if( !zName ){
   30001     /* If zName is NULL, the upper layer is requesting a temp file. */
   30002     assert(isDelete && !syncDir);
   30003     rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
   30004     if( rc!=SQLITE_OK ){
   30005       return rc;
   30006     }
   30007     zName = zTmpname;
   30008 
   30009     /* Generated temporary filenames are always double-zero terminated
   30010     ** for use by sqlite3_uri_parameter(). */
   30011     assert( zName[strlen(zName)+1]==0 );
   30012   }
   30013 
   30014   /* Determine the value of the flags parameter passed to POSIX function
   30015   ** open(). These must be calculated even if open() is not called, as
   30016   ** they may be stored as part of the file handle and used by the
   30017   ** 'conch file' locking functions later on.  */
   30018   if( isReadonly )  openFlags |= O_RDONLY;
   30019   if( isReadWrite ) openFlags |= O_RDWR;
   30020   if( isCreate )    openFlags |= O_CREAT;
   30021   if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
   30022   openFlags |= (O_LARGEFILE|O_BINARY);
   30023 
   30024   if( fd<0 ){
   30025     mode_t openMode;              /* Permissions to create file with */
   30026     uid_t uid;                    /* Userid for the file */
   30027     gid_t gid;                    /* Groupid for the file */
   30028     rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
   30029     if( rc!=SQLITE_OK ){
   30030       assert( !p->pUnused );
   30031       assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
   30032       return rc;
   30033     }
   30034     fd = robust_open(zName, openFlags, openMode);
   30035     OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
   30036     if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
   30037       /* Failed to open the file for read/write access. Try read-only. */
   30038       flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
   30039       openFlags &= ~(O_RDWR|O_CREAT);
   30040       flags |= SQLITE_OPEN_READONLY;
   30041       openFlags |= O_RDONLY;
   30042       isReadonly = 1;
   30043       fd = robust_open(zName, openFlags, openMode);
   30044     }
   30045     if( fd<0 ){
   30046       rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
   30047       goto open_finished;
   30048     }
   30049 
   30050     /* If this process is running as root and if creating a new rollback
   30051     ** journal or WAL file, set the ownership of the journal or WAL to be
   30052     ** the same as the original database.
   30053     */
   30054     if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
   30055       osFchown(fd, uid, gid);
   30056     }
   30057   }
   30058   assert( fd>=0 );
   30059   if( pOutFlags ){
   30060     *pOutFlags = flags;
   30061   }
   30062 
   30063   if( p->pUnused ){
   30064     p->pUnused->fd = fd;
   30065     p->pUnused->flags = flags;
   30066   }
   30067 
   30068   if( isDelete ){
   30069 #if OS_VXWORKS
   30070     zPath = zName;
   30071 #elif defined(SQLITE_UNLINK_AFTER_CLOSE)
   30072     zPath = sqlite3_mprintf("%s", zName);
   30073     if( zPath==0 ){
   30074       robust_close(p, fd, __LINE__);
   30075       return SQLITE_NOMEM;
   30076     }
   30077 #else
   30078     osUnlink(zName);
   30079 #endif
   30080   }
   30081 #if SQLITE_ENABLE_LOCKING_STYLE
   30082   else{
   30083     p->openFlags = openFlags;
   30084   }
   30085 #endif
   30086 
   30087   noLock = eType!=SQLITE_OPEN_MAIN_DB;
   30088 
   30089 
   30090 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
   30091   if( fstatfs(fd, &fsInfo) == -1 ){
   30092     ((unixFile*)pFile)->lastErrno = errno;
   30093     robust_close(p, fd, __LINE__);
   30094     return SQLITE_IOERR_ACCESS;
   30095   }
   30096   if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
   30097     ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
   30098   }
   30099 #endif
   30100 
   30101   /* Set up appropriate ctrlFlags */
   30102   if( isDelete )                ctrlFlags |= UNIXFILE_DELETE;
   30103   if( isReadonly )              ctrlFlags |= UNIXFILE_RDONLY;
   30104   if( noLock )                  ctrlFlags |= UNIXFILE_NOLOCK;
   30105   if( syncDir )                 ctrlFlags |= UNIXFILE_DIRSYNC;
   30106   if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
   30107 
   30108 #if SQLITE_ENABLE_LOCKING_STYLE
   30109 #if SQLITE_PREFER_PROXY_LOCKING
   30110   isAutoProxy = 1;
   30111 #endif
   30112   if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
   30113     char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
   30114     int useProxy = 0;
   30115 
   30116     /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
   30117     ** never use proxy, NULL means use proxy for non-local files only.  */
   30118     if( envforce!=NULL ){
   30119       useProxy = atoi(envforce)>0;
   30120     }else{
   30121       if( statfs(zPath, &fsInfo) == -1 ){
   30122         /* In theory, the close(fd) call is sub-optimal. If the file opened
   30123         ** with fd is a database file, and there are other connections open
   30124         ** on that file that are currently holding advisory locks on it,
   30125         ** then the call to close() will cancel those locks. In practice,
   30126         ** we're assuming that statfs() doesn't fail very often. At least
   30127         ** not while other file descriptors opened by the same process on
   30128         ** the same file are working.  */
   30129         p->lastErrno = errno;
   30130         robust_close(p, fd, __LINE__);
   30131         rc = SQLITE_IOERR_ACCESS;
   30132         goto open_finished;
   30133       }
   30134       useProxy = !(fsInfo.f_flags&MNT_LOCAL);
   30135     }
   30136     if( useProxy ){
   30137       rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
   30138       if( rc==SQLITE_OK ){
   30139         rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
   30140         if( rc!=SQLITE_OK ){
   30141           /* Use unixClose to clean up the resources added in fillInUnixFile
   30142           ** and clear all the structure's references.  Specifically,
   30143           ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
   30144           */
   30145           unixClose(pFile);
   30146           return rc;
   30147         }
   30148       }
   30149       goto open_finished;
   30150     }
   30151   }
   30152 #endif
   30153 
   30154   rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
   30155 
   30156 open_finished:
   30157   if( rc!=SQLITE_OK ){
   30158     sqlite3_free(p->pUnused);
   30159   }
   30160   return rc;
   30161 }
   30162 
   30163 
   30164 /*
   30165 ** Delete the file at zPath. If the dirSync argument is true, fsync()
   30166 ** the directory after deleting the file.
   30167 */
   30168 static int unixDelete(
   30169   sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
   30170   const char *zPath,        /* Name of file to be deleted */
   30171   int dirSync               /* If true, fsync() directory after deleting file */
   30172 ){
   30173   int rc = SQLITE_OK;
   30174   UNUSED_PARAMETER(NotUsed);
   30175   SimulateIOError(return SQLITE_IOERR_DELETE);
   30176   if( osUnlink(zPath)==(-1) ){
   30177     if( errno==ENOENT
   30178 #if OS_VXWORKS
   30179         || errno==0x380003
   30180 #endif
   30181     ){
   30182       rc = SQLITE_IOERR_DELETE_NOENT;
   30183     }else{
   30184       rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
   30185     }
   30186     return rc;
   30187   }
   30188 #ifndef SQLITE_DISABLE_DIRSYNC
   30189   if( (dirSync & 1)!=0 ){
   30190     int fd;
   30191     rc = osOpenDirectory(zPath, &fd);
   30192     if( rc==SQLITE_OK ){
   30193 #if OS_VXWORKS
   30194       if( fsync(fd)==-1 )
   30195 #else
   30196       if( fsync(fd) )
   30197 #endif
   30198       {
   30199         rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
   30200       }
   30201       robust_close(0, fd, __LINE__);
   30202     }else if( rc==SQLITE_CANTOPEN ){
   30203       rc = SQLITE_OK;
   30204     }
   30205   }
   30206 #endif
   30207   return rc;
   30208 }
   30209 
   30210 /*
   30211 ** Test the existence of or access permissions of file zPath. The
   30212 ** test performed depends on the value of flags:
   30213 **
   30214 **     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
   30215 **     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
   30216 **     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
   30217 **
   30218 ** Otherwise return 0.
   30219 */
   30220 static int unixAccess(
   30221   sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
   30222   const char *zPath,      /* Path of the file to examine */
   30223   int flags,              /* What do we want to learn about the zPath file? */
   30224   int *pResOut            /* Write result boolean here */
   30225 ){
   30226   int amode = 0;
   30227   UNUSED_PARAMETER(NotUsed);
   30228   SimulateIOError( return SQLITE_IOERR_ACCESS; );
   30229   switch( flags ){
   30230     case SQLITE_ACCESS_EXISTS:
   30231       amode = F_OK;
   30232       break;
   30233     case SQLITE_ACCESS_READWRITE:
   30234       amode = W_OK|R_OK;
   30235       break;
   30236     case SQLITE_ACCESS_READ:
   30237       amode = R_OK;
   30238       break;
   30239 
   30240     default:
   30241       assert(!"Invalid flags argument");
   30242   }
   30243   *pResOut = (osAccess(zPath, amode)==0);
   30244   if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
   30245     struct stat buf;
   30246     if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
   30247       *pResOut = 0;
   30248     }
   30249   }
   30250   return SQLITE_OK;
   30251 }
   30252 
   30253 
   30254 /*
   30255 ** Turn a relative pathname into a full pathname. The relative path
   30256 ** is stored as a nul-terminated string in the buffer pointed to by
   30257 ** zPath.
   30258 **
   30259 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
   30260 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
   30261 ** this buffer before returning.
   30262 */
   30263 static int unixFullPathname(
   30264   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
   30265   const char *zPath,            /* Possibly relative input path */
   30266   int nOut,                     /* Size of output buffer in bytes */
   30267   char *zOut                    /* Output buffer */
   30268 ){
   30269 
   30270   /* It's odd to simulate an io-error here, but really this is just
   30271   ** using the io-error infrastructure to test that SQLite handles this
   30272   ** function failing. This function could fail if, for example, the
   30273   ** current working directory has been unlinked.
   30274   */
   30275   SimulateIOError( return SQLITE_ERROR );
   30276 
   30277   assert( pVfs->mxPathname==MAX_PATHNAME );
   30278   UNUSED_PARAMETER(pVfs);
   30279 
   30280   zOut[nOut-1] = '\0';
   30281   if( zPath[0]=='/' ){
   30282     sqlite3_snprintf(nOut, zOut, "%s", zPath);
   30283   }else{
   30284     int nCwd;
   30285     if( osGetcwd(zOut, nOut-1)==0 ){
   30286       return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
   30287     }
   30288     nCwd = (int)strlen(zOut);
   30289     sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
   30290   }
   30291   return SQLITE_OK;
   30292 }
   30293 
   30294 
   30295 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   30296 /*
   30297 ** Interfaces for opening a shared library, finding entry points
   30298 ** within the shared library, and closing the shared library.
   30299 */
   30300 #include <dlfcn.h>
   30301 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
   30302   UNUSED_PARAMETER(NotUsed);
   30303   return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
   30304 }
   30305 
   30306 /*
   30307 ** SQLite calls this function immediately after a call to unixDlSym() or
   30308 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
   30309 ** message is available, it is written to zBufOut. If no error message
   30310 ** is available, zBufOut is left unmodified and SQLite uses a default
   30311 ** error message.
   30312 */
   30313 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
   30314   const char *zErr;
   30315   UNUSED_PARAMETER(NotUsed);
   30316   unixEnterMutex();
   30317   zErr = dlerror();
   30318   if( zErr ){
   30319     sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
   30320   }
   30321   unixLeaveMutex();
   30322 }
   30323 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
   30324   /*
   30325   ** GCC with -pedantic-errors says that C90 does not allow a void* to be
   30326   ** cast into a pointer to a function.  And yet the library dlsym() routine
   30327   ** returns a void* which is really a pointer to a function.  So how do we
   30328   ** use dlsym() with -pedantic-errors?
   30329   **
   30330   ** Variable x below is defined to be a pointer to a function taking
   30331   ** parameters void* and const char* and returning a pointer to a function.
   30332   ** We initialize x by assigning it a pointer to the dlsym() function.
   30333   ** (That assignment requires a cast.)  Then we call the function that
   30334   ** x points to.
   30335   **
   30336   ** This work-around is unlikely to work correctly on any system where
   30337   ** you really cannot cast a function pointer into void*.  But then, on the
   30338   ** other hand, dlsym() will not work on such a system either, so we have
   30339   ** not really lost anything.
   30340   */
   30341   void (*(*x)(void*,const char*))(void);
   30342   UNUSED_PARAMETER(NotUsed);
   30343   x = (void(*(*)(void*,const char*))(void))dlsym;
   30344   return (*x)(p, zSym);
   30345 }
   30346 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
   30347   UNUSED_PARAMETER(NotUsed);
   30348   dlclose(pHandle);
   30349 }
   30350 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
   30351   #define unixDlOpen  0
   30352   #define unixDlError 0
   30353   #define unixDlSym   0
   30354   #define unixDlClose 0
   30355 #endif
   30356 
   30357 /*
   30358 ** Write nBuf bytes of random data to the supplied buffer zBuf.
   30359 */
   30360 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
   30361   UNUSED_PARAMETER(NotUsed);
   30362   assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
   30363 
   30364   /* We have to initialize zBuf to prevent valgrind from reporting
   30365   ** errors.  The reports issued by valgrind are incorrect - we would
   30366   ** prefer that the randomness be increased by making use of the
   30367   ** uninitialized space in zBuf - but valgrind errors tend to worry
   30368   ** some users.  Rather than argue, it seems easier just to initialize
   30369   ** the whole array and silence valgrind, even if that means less randomness
   30370   ** in the random seed.
   30371   **
   30372   ** When testing, initializing zBuf[] to zero is all we do.  That means
   30373   ** that we always use the same random number sequence.  This makes the
   30374   ** tests repeatable.
   30375   */
   30376   memset(zBuf, 0, nBuf);
   30377   randomnessPid = getpid();
   30378 #if !defined(SQLITE_TEST)
   30379   {
   30380     int fd, got;
   30381     fd = robust_open("/dev/urandom", O_RDONLY, 0);
   30382     if( fd<0 ){
   30383       time_t t;
   30384       time(&t);
   30385       memcpy(zBuf, &t, sizeof(t));
   30386       memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
   30387       assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
   30388       nBuf = sizeof(t) + sizeof(randomnessPid);
   30389     }else{
   30390       do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
   30391       robust_close(0, fd, __LINE__);
   30392     }
   30393   }
   30394 #endif
   30395   return nBuf;
   30396 }
   30397 
   30398 
   30399 /*
   30400 ** Sleep for a little while.  Return the amount of time slept.
   30401 ** The argument is the number of microseconds we want to sleep.
   30402 ** The return value is the number of microseconds of sleep actually
   30403 ** requested from the underlying operating system, a number which
   30404 ** might be greater than or equal to the argument, but not less
   30405 ** than the argument.
   30406 */
   30407 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
   30408 #if OS_VXWORKS
   30409   struct timespec sp;
   30410 
   30411   sp.tv_sec = microseconds / 1000000;
   30412   sp.tv_nsec = (microseconds % 1000000) * 1000;
   30413   nanosleep(&sp, NULL);
   30414   UNUSED_PARAMETER(NotUsed);
   30415   return microseconds;
   30416 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
   30417   usleep(microseconds);
   30418   UNUSED_PARAMETER(NotUsed);
   30419   return microseconds;
   30420 #else
   30421   int seconds = (microseconds+999999)/1000000;
   30422   sleep(seconds);
   30423   UNUSED_PARAMETER(NotUsed);
   30424   return seconds*1000000;
   30425 #endif
   30426 }
   30427 
   30428 /*
   30429 ** The following variable, if set to a non-zero value, is interpreted as
   30430 ** the number of seconds since 1970 and is used to set the result of
   30431 ** sqlite3OsCurrentTime() during testing.
   30432 */
   30433 #ifdef SQLITE_TEST
   30434 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
   30435 #endif
   30436 
   30437 /*
   30438 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
   30439 ** the current time and date as a Julian Day number times 86_400_000.  In
   30440 ** other words, write into *piNow the number of milliseconds since the Julian
   30441 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
   30442 ** proleptic Gregorian calendar.
   30443 **
   30444 ** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
   30445 ** cannot be found.
   30446 */
   30447 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
   30448   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
   30449   int rc = SQLITE_OK;
   30450 #if defined(NO_GETTOD)
   30451   time_t t;
   30452   time(&t);
   30453   *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
   30454 #elif OS_VXWORKS
   30455   struct timespec sNow;
   30456   clock_gettime(CLOCK_REALTIME, &sNow);
   30457   *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
   30458 #else
   30459   struct timeval sNow;
   30460   if( gettimeofday(&sNow, 0)==0 ){
   30461     *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
   30462   }else{
   30463     rc = SQLITE_ERROR;
   30464   }
   30465 #endif
   30466 
   30467 #ifdef SQLITE_TEST
   30468   if( sqlite3_current_time ){
   30469     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
   30470   }
   30471 #endif
   30472   UNUSED_PARAMETER(NotUsed);
   30473   return rc;
   30474 }
   30475 
   30476 /*
   30477 ** Find the current time (in Universal Coordinated Time).  Write the
   30478 ** current time and date as a Julian Day number into *prNow and
   30479 ** return 0.  Return 1 if the time and date cannot be found.
   30480 */
   30481 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
   30482   sqlite3_int64 i = 0;
   30483   int rc;
   30484   UNUSED_PARAMETER(NotUsed);
   30485   rc = unixCurrentTimeInt64(0, &i);
   30486   *prNow = i/86400000.0;
   30487   return rc;
   30488 }
   30489 
   30490 /*
   30491 ** We added the xGetLastError() method with the intention of providing
   30492 ** better low-level error messages when operating-system problems come up
   30493 ** during SQLite operation.  But so far, none of that has been implemented
   30494 ** in the core.  So this routine is never called.  For now, it is merely
   30495 ** a place-holder.
   30496 */
   30497 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
   30498   UNUSED_PARAMETER(NotUsed);
   30499   UNUSED_PARAMETER(NotUsed2);
   30500   UNUSED_PARAMETER(NotUsed3);
   30501   return 0;
   30502 }
   30503 
   30504 
   30505 /*
   30506 ************************ End of sqlite3_vfs methods ***************************
   30507 ******************************************************************************/
   30508 
   30509 /******************************************************************************
   30510 ************************** Begin Proxy Locking ********************************
   30511 **
   30512 ** Proxy locking is a "uber-locking-method" in this sense:  It uses the
   30513 ** other locking methods on secondary lock files.  Proxy locking is a
   30514 ** meta-layer over top of the primitive locking implemented above.  For
   30515 ** this reason, the division that implements of proxy locking is deferred
   30516 ** until late in the file (here) after all of the other I/O methods have
   30517 ** been defined - so that the primitive locking methods are available
   30518 ** as services to help with the implementation of proxy locking.
   30519 **
   30520 ****
   30521 **
   30522 ** The default locking schemes in SQLite use byte-range locks on the
   30523 ** database file to coordinate safe, concurrent access by multiple readers
   30524 ** and writers [http://sqlite.org/lockingv3.html].  The five file locking
   30525 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
   30526 ** as POSIX read & write locks over fixed set of locations (via fsctl),
   30527 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
   30528 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
   30529 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
   30530 ** address in the shared range is taken for a SHARED lock, the entire
   30531 ** shared range is taken for an EXCLUSIVE lock):
   30532 **
   30533 **      PENDING_BYTE        0x40000000
   30534 **      RESERVED_BYTE       0x40000001
   30535 **      SHARED_RANGE        0x40000002 -> 0x40000200
   30536 **
   30537 ** This works well on the local file system, but shows a nearly 100x
   30538 ** slowdown in read performance on AFP because the AFP client disables
   30539 ** the read cache when byte-range locks are present.  Enabling the read
   30540 ** cache exposes a cache coherency problem that is present on all OS X
   30541 ** supported network file systems.  NFS and AFP both observe the
   30542 ** close-to-open semantics for ensuring cache coherency
   30543 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
   30544 ** address the requirements for concurrent database access by multiple
   30545 ** readers and writers
   30546 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
   30547 **
   30548 ** To address the performance and cache coherency issues, proxy file locking
   30549 ** changes the way database access is controlled by limiting access to a
   30550 ** single host at a time and moving file locks off of the database file
   30551 ** and onto a proxy file on the local file system.
   30552 **
   30553 **
   30554 ** Using proxy locks
   30555 ** -----------------
   30556 **
   30557 ** C APIs
   30558 **
   30559 **  sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
   30560 **                       <proxy_path> | ":auto:");
   30561 **  sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
   30562 **
   30563 **
   30564 ** SQL pragmas
   30565 **
   30566 **  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
   30567 **  PRAGMA [database.]lock_proxy_file
   30568 **
   30569 ** Specifying ":auto:" means that if there is a conch file with a matching
   30570 ** host ID in it, the proxy path in the conch file will be used, otherwise
   30571 ** a proxy path based on the user's temp dir
   30572 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
   30573 ** actual proxy file name is generated from the name and path of the
   30574 ** database file.  For example:
   30575 **
   30576 **       For database path "/Users/me/foo.db"
   30577 **       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
   30578 **
   30579 ** Once a lock proxy is configured for a database connection, it can not
   30580 ** be removed, however it may be switched to a different proxy path via
   30581 ** the above APIs (assuming the conch file is not being held by another
   30582 ** connection or process).
   30583 **
   30584 **
   30585 ** How proxy locking works
   30586 ** -----------------------
   30587 **
   30588 ** Proxy file locking relies primarily on two new supporting files:
   30589 **
   30590 **   *  conch file to limit access to the database file to a single host
   30591 **      at a time
   30592 **
   30593 **   *  proxy file to act as a proxy for the advisory locks normally
   30594 **      taken on the database
   30595 **
   30596 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
   30597 ** by taking an sqlite-style shared lock on the conch file, reading the
   30598 ** contents and comparing the host's unique host ID (see below) and lock
   30599 ** proxy path against the values stored in the conch.  The conch file is
   30600 ** stored in the same directory as the database file and the file name
   30601 ** is patterned after the database file name as ".<databasename>-conch".
   30602 ** If the conch file does not exist, or it's contents do not match the
   30603 ** host ID and/or proxy path, then the lock is escalated to an exclusive
   30604 ** lock and the conch file contents is updated with the host ID and proxy
   30605 ** path and the lock is downgraded to a shared lock again.  If the conch
   30606 ** is held by another process (with a shared lock), the exclusive lock
   30607 ** will fail and SQLITE_BUSY is returned.
   30608 **
   30609 ** The proxy file - a single-byte file used for all advisory file locks
   30610 ** normally taken on the database file.   This allows for safe sharing
   30611 ** of the database file for multiple readers and writers on the same
   30612 ** host (the conch ensures that they all use the same local lock file).
   30613 **
   30614 ** Requesting the lock proxy does not immediately take the conch, it is
   30615 ** only taken when the first request to lock database file is made.
   30616 ** This matches the semantics of the traditional locking behavior, where
   30617 ** opening a connection to a database file does not take a lock on it.
   30618 ** The shared lock and an open file descriptor are maintained until
   30619 ** the connection to the database is closed.
   30620 **
   30621 ** The proxy file and the lock file are never deleted so they only need
   30622 ** to be created the first time they are used.
   30623 **
   30624 ** Configuration options
   30625 ** ---------------------
   30626 **
   30627 **  SQLITE_PREFER_PROXY_LOCKING
   30628 **
   30629 **       Database files accessed on non-local file systems are
   30630 **       automatically configured for proxy locking, lock files are
   30631 **       named automatically using the same logic as
   30632 **       PRAGMA lock_proxy_file=":auto:"
   30633 **
   30634 **  SQLITE_PROXY_DEBUG
   30635 **
   30636 **       Enables the logging of error messages during host id file
   30637 **       retrieval and creation
   30638 **
   30639 **  LOCKPROXYDIR
   30640 **
   30641 **       Overrides the default directory used for lock proxy files that
   30642 **       are named automatically via the ":auto:" setting
   30643 **
   30644 **  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
   30645 **
   30646 **       Permissions to use when creating a directory for storing the
   30647 **       lock proxy files, only used when LOCKPROXYDIR is not set.
   30648 **
   30649 **
   30650 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
   30651 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
   30652 ** force proxy locking to be used for every database file opened, and 0
   30653 ** will force automatic proxy locking to be disabled for all database
   30654 ** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
   30655 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
   30656 */
   30657 
   30658 /*
   30659 ** Proxy locking is only available on MacOSX
   30660 */
   30661 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   30662 
   30663 /*
   30664 ** The proxyLockingContext has the path and file structures for the remote
   30665 ** and local proxy files in it
   30666 */
   30667 typedef struct proxyLockingContext proxyLockingContext;
   30668 struct proxyLockingContext {
   30669   unixFile *conchFile;         /* Open conch file */
   30670   char *conchFilePath;         /* Name of the conch file */
   30671   unixFile *lockProxy;         /* Open proxy lock file */
   30672   char *lockProxyPath;         /* Name of the proxy lock file */
   30673   char *dbPath;                /* Name of the open file */
   30674   int conchHeld;               /* 1 if the conch is held, -1 if lockless */
   30675   void *oldLockingContext;     /* Original lockingcontext to restore on close */
   30676   sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
   30677 };
   30678 
   30679 /*
   30680 ** The proxy lock file path for the database at dbPath is written into lPath,
   30681 ** which must point to valid, writable memory large enough for a maxLen length
   30682 ** file path.
   30683 */
   30684 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
   30685   int len;
   30686   int dbLen;
   30687   int i;
   30688 
   30689 #ifdef LOCKPROXYDIR
   30690   len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
   30691 #else
   30692 # ifdef _CS_DARWIN_USER_TEMP_DIR
   30693   {
   30694     if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
   30695       OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
   30696                lPath, errno, getpid()));
   30697       return SQLITE_IOERR_LOCK;
   30698     }
   30699     len = strlcat(lPath, "sqliteplocks", maxLen);
   30700   }
   30701 # else
   30702   len = strlcpy(lPath, "/tmp/", maxLen);
   30703 # endif
   30704 #endif
   30705 
   30706   if( lPath[len-1]!='/' ){
   30707     len = strlcat(lPath, "/", maxLen);
   30708   }
   30709 
   30710   /* transform the db path to a unique cache name */
   30711   dbLen = (int)strlen(dbPath);
   30712   for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
   30713     char c = dbPath[i];
   30714     lPath[i+len] = (c=='/')?'_':c;
   30715   }
   30716   lPath[i+len]='\0';
   30717   strlcat(lPath, ":auto:", maxLen);
   30718   OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, getpid()));
   30719   return SQLITE_OK;
   30720 }
   30721 
   30722 /*
   30723  ** Creates the lock file and any missing directories in lockPath
   30724  */
   30725 static int proxyCreateLockPath(const char *lockPath){
   30726   int i, len;
   30727   char buf[MAXPATHLEN];
   30728   int start = 0;
   30729 
   30730   assert(lockPath!=NULL);
   30731   /* try to create all the intermediate directories */
   30732   len = (int)strlen(lockPath);
   30733   buf[0] = lockPath[0];
   30734   for( i=1; i<len; i++ ){
   30735     if( lockPath[i] == '/' && (i - start > 0) ){
   30736       /* only mkdir if leaf dir != "." or "/" or ".." */
   30737       if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
   30738          || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
   30739         buf[i]='\0';
   30740         if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
   30741           int err=errno;
   30742           if( err!=EEXIST ) {
   30743             OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
   30744                      "'%s' proxy lock path=%s pid=%d\n",
   30745                      buf, strerror(err), lockPath, getpid()));
   30746             return err;
   30747           }
   30748         }
   30749       }
   30750       start=i+1;
   30751     }
   30752     buf[i] = lockPath[i];
   30753   }
   30754   OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n", lockPath, getpid()));
   30755   return 0;
   30756 }
   30757 
   30758 /*
   30759 ** Create a new VFS file descriptor (stored in memory obtained from
   30760 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
   30761 **
   30762 ** The caller is responsible not only for closing the file descriptor
   30763 ** but also for freeing the memory associated with the file descriptor.
   30764 */
   30765 static int proxyCreateUnixFile(
   30766     const char *path,        /* path for the new unixFile */
   30767     unixFile **ppFile,       /* unixFile created and returned by ref */
   30768     int islockfile           /* if non zero missing dirs will be created */
   30769 ) {
   30770   int fd = -1;
   30771   unixFile *pNew;
   30772   int rc = SQLITE_OK;
   30773   int openFlags = O_RDWR | O_CREAT;
   30774   sqlite3_vfs dummyVfs;
   30775   int terrno = 0;
   30776   UnixUnusedFd *pUnused = NULL;
   30777 
   30778   /* 1. first try to open/create the file
   30779   ** 2. if that fails, and this is a lock file (not-conch), try creating
   30780   ** the parent directories and then try again.
   30781   ** 3. if that fails, try to open the file read-only
   30782   ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
   30783   */
   30784   pUnused = findReusableFd(path, openFlags);
   30785   if( pUnused ){
   30786     fd = pUnused->fd;
   30787   }else{
   30788     pUnused = sqlite3_malloc(sizeof(*pUnused));
   30789     if( !pUnused ){
   30790       return SQLITE_NOMEM;
   30791     }
   30792   }
   30793   if( fd<0 ){
   30794     fd = robust_open(path, openFlags, 0);
   30795     terrno = errno;
   30796     if( fd<0 && errno==ENOENT && islockfile ){
   30797       if( proxyCreateLockPath(path) == SQLITE_OK ){
   30798         fd = robust_open(path, openFlags, 0);
   30799       }
   30800     }
   30801   }
   30802   if( fd<0 ){
   30803     openFlags = O_RDONLY;
   30804     fd = robust_open(path, openFlags, 0);
   30805     terrno = errno;
   30806   }
   30807   if( fd<0 ){
   30808     if( islockfile ){
   30809       return SQLITE_BUSY;
   30810     }
   30811     switch (terrno) {
   30812       case EACCES:
   30813         return SQLITE_PERM;
   30814       case EIO:
   30815         return SQLITE_IOERR_LOCK; /* even though it is the conch */
   30816       default:
   30817         return SQLITE_CANTOPEN_BKPT;
   30818     }
   30819   }
   30820 
   30821   pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
   30822   if( pNew==NULL ){
   30823     rc = SQLITE_NOMEM;
   30824     goto end_create_proxy;
   30825   }
   30826   memset(pNew, 0, sizeof(unixFile));
   30827   pNew->openFlags = openFlags;
   30828   memset(&dummyVfs, 0, sizeof(dummyVfs));
   30829   dummyVfs.pAppData = (void*)&autolockIoFinder;
   30830   dummyVfs.zName = "dummy";
   30831   pUnused->fd = fd;
   30832   pUnused->flags = openFlags;
   30833   pNew->pUnused = pUnused;
   30834 
   30835   rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
   30836   if( rc==SQLITE_OK ){
   30837     *ppFile = pNew;
   30838     return SQLITE_OK;
   30839   }
   30840 end_create_proxy:
   30841   robust_close(pNew, fd, __LINE__);
   30842   sqlite3_free(pNew);
   30843   sqlite3_free(pUnused);
   30844   return rc;
   30845 }
   30846 
   30847 #ifdef SQLITE_TEST
   30848 /* simulate multiple hosts by creating unique hostid file paths */
   30849 SQLITE_API int sqlite3_hostid_num = 0;
   30850 #endif
   30851 
   30852 #define PROXY_HOSTIDLEN    16  /* conch file host id length */
   30853 
   30854 /* Not always defined in the headers as it ought to be */
   30855 extern int gethostuuid(uuid_t id, const struct timespec *wait);
   30856 
   30857 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
   30858 ** bytes of writable memory.
   30859 */
   30860 static int proxyGetHostID(unsigned char *pHostID, int *pError){
   30861   assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
   30862   memset(pHostID, 0, PROXY_HOSTIDLEN);
   30863 #if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
   30864                && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
   30865   {
   30866     static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
   30867     if( gethostuuid(pHostID, &timeout) ){
   30868       int err = errno;
   30869       if( pError ){
   30870         *pError = err;
   30871       }
   30872       return SQLITE_IOERR;
   30873     }
   30874   }
   30875 #else
   30876   UNUSED_PARAMETER(pError);
   30877 #endif
   30878 #ifdef SQLITE_TEST
   30879   /* simulate multiple hosts by creating unique hostid file paths */
   30880   if( sqlite3_hostid_num != 0){
   30881     pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
   30882   }
   30883 #endif
   30884 
   30885   return SQLITE_OK;
   30886 }
   30887 
   30888 /* The conch file contains the header, host id and lock file path
   30889  */
   30890 #define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
   30891 #define PROXY_HEADERLEN    1   /* conch file header length */
   30892 #define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
   30893 #define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
   30894 
   30895 /*
   30896 ** Takes an open conch file, copies the contents to a new path and then moves
   30897 ** it back.  The newly created file's file descriptor is assigned to the
   30898 ** conch file structure and finally the original conch file descriptor is
   30899 ** closed.  Returns zero if successful.
   30900 */
   30901 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
   30902   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   30903   unixFile *conchFile = pCtx->conchFile;
   30904   char tPath[MAXPATHLEN];
   30905   char buf[PROXY_MAXCONCHLEN];
   30906   char *cPath = pCtx->conchFilePath;
   30907   size_t readLen = 0;
   30908   size_t pathLen = 0;
   30909   char errmsg[64] = "";
   30910   int fd = -1;
   30911   int rc = -1;
   30912   UNUSED_PARAMETER(myHostID);
   30913 
   30914   /* create a new path by replace the trailing '-conch' with '-break' */
   30915   pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
   30916   if( pathLen>MAXPATHLEN || pathLen<6 ||
   30917      (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
   30918     sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
   30919     goto end_breaklock;
   30920   }
   30921   /* read the conch content */
   30922   readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
   30923   if( readLen<PROXY_PATHINDEX ){
   30924     sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
   30925     goto end_breaklock;
   30926   }
   30927   /* write it out to the temporary break file */
   30928   fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
   30929   if( fd<0 ){
   30930     sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
   30931     goto end_breaklock;
   30932   }
   30933   if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
   30934     sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
   30935     goto end_breaklock;
   30936   }
   30937   if( rename(tPath, cPath) ){
   30938     sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
   30939     goto end_breaklock;
   30940   }
   30941   rc = 0;
   30942   fprintf(stderr, "broke stale lock on %s\n", cPath);
   30943   robust_close(pFile, conchFile->h, __LINE__);
   30944   conchFile->h = fd;
   30945   conchFile->openFlags = O_RDWR | O_CREAT;
   30946 
   30947 end_breaklock:
   30948   if( rc ){
   30949     if( fd>=0 ){
   30950       osUnlink(tPath);
   30951       robust_close(pFile, fd, __LINE__);
   30952     }
   30953     fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
   30954   }
   30955   return rc;
   30956 }
   30957 
   30958 /* Take the requested lock on the conch file and break a stale lock if the
   30959 ** host id matches.
   30960 */
   30961 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
   30962   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   30963   unixFile *conchFile = pCtx->conchFile;
   30964   int rc = SQLITE_OK;
   30965   int nTries = 0;
   30966   struct timespec conchModTime;
   30967 
   30968   memset(&conchModTime, 0, sizeof(conchModTime));
   30969   do {
   30970     rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
   30971     nTries ++;
   30972     if( rc==SQLITE_BUSY ){
   30973       /* If the lock failed (busy):
   30974        * 1st try: get the mod time of the conch, wait 0.5s and try again.
   30975        * 2nd try: fail if the mod time changed or host id is different, wait
   30976        *           10 sec and try again
   30977        * 3rd try: break the lock unless the mod time has changed.
   30978        */
   30979       struct stat buf;
   30980       if( osFstat(conchFile->h, &buf) ){
   30981         pFile->lastErrno = errno;
   30982         return SQLITE_IOERR_LOCK;
   30983       }
   30984 
   30985       if( nTries==1 ){
   30986         conchModTime = buf.st_mtimespec;
   30987         usleep(500000); /* wait 0.5 sec and try the lock again*/
   30988         continue;
   30989       }
   30990 
   30991       assert( nTries>1 );
   30992       if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
   30993          conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
   30994         return SQLITE_BUSY;
   30995       }
   30996 
   30997       if( nTries==2 ){
   30998         char tBuf[PROXY_MAXCONCHLEN];
   30999         int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
   31000         if( len<0 ){
   31001           pFile->lastErrno = errno;
   31002           return SQLITE_IOERR_LOCK;
   31003         }
   31004         if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
   31005           /* don't break the lock if the host id doesn't match */
   31006           if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
   31007             return SQLITE_BUSY;
   31008           }
   31009         }else{
   31010           /* don't break the lock on short read or a version mismatch */
   31011           return SQLITE_BUSY;
   31012         }
   31013         usleep(10000000); /* wait 10 sec and try the lock again */
   31014         continue;
   31015       }
   31016 
   31017       assert( nTries==3 );
   31018       if( 0==proxyBreakConchLock(pFile, myHostID) ){
   31019         rc = SQLITE_OK;
   31020         if( lockType==EXCLUSIVE_LOCK ){
   31021           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
   31022         }
   31023         if( !rc ){
   31024           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
   31025         }
   31026       }
   31027     }
   31028   } while( rc==SQLITE_BUSY && nTries<3 );
   31029 
   31030   return rc;
   31031 }
   31032 
   31033 /* Takes the conch by taking a shared lock and read the contents conch, if
   31034 ** lockPath is non-NULL, the host ID and lock file path must match.  A NULL
   31035 ** lockPath means that the lockPath in the conch file will be used if the
   31036 ** host IDs match, or a new lock path will be generated automatically
   31037 ** and written to the conch file.
   31038 */
   31039 static int proxyTakeConch(unixFile *pFile){
   31040   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   31041 
   31042   if( pCtx->conchHeld!=0 ){
   31043     return SQLITE_OK;
   31044   }else{
   31045     unixFile *conchFile = pCtx->conchFile;
   31046     uuid_t myHostID;
   31047     int pError = 0;
   31048     char readBuf[PROXY_MAXCONCHLEN];
   31049     char lockPath[MAXPATHLEN];
   31050     char *tempLockPath = NULL;
   31051     int rc = SQLITE_OK;
   31052     int createConch = 0;
   31053     int hostIdMatch = 0;
   31054     int readLen = 0;
   31055     int tryOldLockPath = 0;
   31056     int forceNewLockPath = 0;
   31057 
   31058     OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
   31059              (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
   31060 
   31061     rc = proxyGetHostID(myHostID, &pError);
   31062     if( (rc&0xff)==SQLITE_IOERR ){
   31063       pFile->lastErrno = pError;
   31064       goto end_takeconch;
   31065     }
   31066     rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
   31067     if( rc!=SQLITE_OK ){
   31068       goto end_takeconch;
   31069     }
   31070     /* read the existing conch file */
   31071     readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
   31072     if( readLen<0 ){
   31073       /* I/O error: lastErrno set by seekAndRead */
   31074       pFile->lastErrno = conchFile->lastErrno;
   31075       rc = SQLITE_IOERR_READ;
   31076       goto end_takeconch;
   31077     }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
   31078              readBuf[0]!=(char)PROXY_CONCHVERSION ){
   31079       /* a short read or version format mismatch means we need to create a new
   31080       ** conch file.
   31081       */
   31082       createConch = 1;
   31083     }
   31084     /* if the host id matches and the lock path already exists in the conch
   31085     ** we'll try to use the path there, if we can't open that path, we'll
   31086     ** retry with a new auto-generated path
   31087     */
   31088     do { /* in case we need to try again for an :auto: named lock file */
   31089 
   31090       if( !createConch && !forceNewLockPath ){
   31091         hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
   31092                                   PROXY_HOSTIDLEN);
   31093         /* if the conch has data compare the contents */
   31094         if( !pCtx->lockProxyPath ){
   31095           /* for auto-named local lock file, just check the host ID and we'll
   31096            ** use the local lock file path that's already in there
   31097            */
   31098           if( hostIdMatch ){
   31099             size_t pathLen = (readLen - PROXY_PATHINDEX);
   31100 
   31101             if( pathLen>=MAXPATHLEN ){
   31102               pathLen=MAXPATHLEN-1;
   31103             }
   31104             memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
   31105             lockPath[pathLen] = 0;
   31106             tempLockPath = lockPath;
   31107             tryOldLockPath = 1;
   31108             /* create a copy of the lock path if the conch is taken */
   31109             goto end_takeconch;
   31110           }
   31111         }else if( hostIdMatch
   31112                && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
   31113                            readLen-PROXY_PATHINDEX)
   31114         ){
   31115           /* conch host and lock path match */
   31116           goto end_takeconch;
   31117         }
   31118       }
   31119 
   31120       /* if the conch isn't writable and doesn't match, we can't take it */
   31121       if( (conchFile->openFlags&O_RDWR) == 0 ){
   31122         rc = SQLITE_BUSY;
   31123         goto end_takeconch;
   31124       }
   31125 
   31126       /* either the conch didn't match or we need to create a new one */
   31127       if( !pCtx->lockProxyPath ){
   31128         proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
   31129         tempLockPath = lockPath;
   31130         /* create a copy of the lock path _only_ if the conch is taken */
   31131       }
   31132 
   31133       /* update conch with host and path (this will fail if other process
   31134       ** has a shared lock already), if the host id matches, use the big
   31135       ** stick.
   31136       */
   31137       futimes(conchFile->h, NULL);
   31138       if( hostIdMatch && !createConch ){
   31139         if( conchFile->pInode && conchFile->pInode->nShared>1 ){
   31140           /* We are trying for an exclusive lock but another thread in this
   31141            ** same process is still holding a shared lock. */
   31142           rc = SQLITE_BUSY;
   31143         } else {
   31144           rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
   31145         }
   31146       }else{
   31147         rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
   31148       }
   31149       if( rc==SQLITE_OK ){
   31150         char writeBuffer[PROXY_MAXCONCHLEN];
   31151         int writeSize = 0;
   31152 
   31153         writeBuffer[0] = (char)PROXY_CONCHVERSION;
   31154         memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
   31155         if( pCtx->lockProxyPath!=NULL ){
   31156           strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
   31157         }else{
   31158           strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
   31159         }
   31160         writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
   31161         robust_ftruncate(conchFile->h, writeSize);
   31162         rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
   31163         fsync(conchFile->h);
   31164         /* If we created a new conch file (not just updated the contents of a
   31165          ** valid conch file), try to match the permissions of the database
   31166          */
   31167         if( rc==SQLITE_OK && createConch ){
   31168           struct stat buf;
   31169           int err = osFstat(pFile->h, &buf);
   31170           if( err==0 ){
   31171             mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
   31172                                         S_IROTH|S_IWOTH);
   31173             /* try to match the database file R/W permissions, ignore failure */
   31174 #ifndef SQLITE_PROXY_DEBUG
   31175             osFchmod(conchFile->h, cmode);
   31176 #else
   31177             do{
   31178               rc = osFchmod(conchFile->h, cmode);
   31179             }while( rc==(-1) && errno==EINTR );
   31180             if( rc!=0 ){
   31181               int code = errno;
   31182               fprintf(stderr, "fchmod %o FAILED with %d %s\n",
   31183                       cmode, code, strerror(code));
   31184             } else {
   31185               fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
   31186             }
   31187           }else{
   31188             int code = errno;
   31189             fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
   31190                     err, code, strerror(code));
   31191 #endif
   31192           }
   31193         }
   31194       }
   31195       conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
   31196 
   31197     end_takeconch:
   31198       OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
   31199       if( rc==SQLITE_OK && pFile->openFlags ){
   31200         int fd;
   31201         if( pFile->h>=0 ){
   31202           robust_close(pFile, pFile->h, __LINE__);
   31203         }
   31204         pFile->h = -1;
   31205         fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
   31206         OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
   31207         if( fd>=0 ){
   31208           pFile->h = fd;
   31209         }else{
   31210           rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
   31211            during locking */
   31212         }
   31213       }
   31214       if( rc==SQLITE_OK && !pCtx->lockProxy ){
   31215         char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
   31216         rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
   31217         if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
   31218           /* we couldn't create the proxy lock file with the old lock file path
   31219            ** so try again via auto-naming
   31220            */
   31221           forceNewLockPath = 1;
   31222           tryOldLockPath = 0;
   31223           continue; /* go back to the do {} while start point, try again */
   31224         }
   31225       }
   31226       if( rc==SQLITE_OK ){
   31227         /* Need to make a copy of path if we extracted the value
   31228          ** from the conch file or the path was allocated on the stack
   31229          */
   31230         if( tempLockPath ){
   31231           pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
   31232           if( !pCtx->lockProxyPath ){
   31233             rc = SQLITE_NOMEM;
   31234           }
   31235         }
   31236       }
   31237       if( rc==SQLITE_OK ){
   31238         pCtx->conchHeld = 1;
   31239 
   31240         if( pCtx->lockProxy->pMethod == &afpIoMethods ){
   31241           afpLockingContext *afpCtx;
   31242           afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
   31243           afpCtx->dbPath = pCtx->lockProxyPath;
   31244         }
   31245       } else {
   31246         conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
   31247       }
   31248       OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
   31249                rc==SQLITE_OK?"ok":"failed"));
   31250       return rc;
   31251     } while (1); /* in case we need to retry the :auto: lock file -
   31252                  ** we should never get here except via the 'continue' call. */
   31253   }
   31254 }
   31255 
   31256 /*
   31257 ** If pFile holds a lock on a conch file, then release that lock.
   31258 */
   31259 static int proxyReleaseConch(unixFile *pFile){
   31260   int rc = SQLITE_OK;         /* Subroutine return code */
   31261   proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
   31262   unixFile *conchFile;        /* Name of the conch file */
   31263 
   31264   pCtx = (proxyLockingContext *)pFile->lockingContext;
   31265   conchFile = pCtx->conchFile;
   31266   OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
   31267            (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
   31268            getpid()));
   31269   if( pCtx->conchHeld>0 ){
   31270     rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
   31271   }
   31272   pCtx->conchHeld = 0;
   31273   OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
   31274            (rc==SQLITE_OK ? "ok" : "failed")));
   31275   return rc;
   31276 }
   31277 
   31278 /*
   31279 ** Given the name of a database file, compute the name of its conch file.
   31280 ** Store the conch filename in memory obtained from sqlite3_malloc().
   31281 ** Make *pConchPath point to the new name.  Return SQLITE_OK on success
   31282 ** or SQLITE_NOMEM if unable to obtain memory.
   31283 **
   31284 ** The caller is responsible for ensuring that the allocated memory
   31285 ** space is eventually freed.
   31286 **
   31287 ** *pConchPath is set to NULL if a memory allocation error occurs.
   31288 */
   31289 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
   31290   int i;                        /* Loop counter */
   31291   int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
   31292   char *conchPath;              /* buffer in which to construct conch name */
   31293 
   31294   /* Allocate space for the conch filename and initialize the name to
   31295   ** the name of the original database file. */
   31296   *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
   31297   if( conchPath==0 ){
   31298     return SQLITE_NOMEM;
   31299   }
   31300   memcpy(conchPath, dbPath, len+1);
   31301 
   31302   /* now insert a "." before the last / character */
   31303   for( i=(len-1); i>=0; i-- ){
   31304     if( conchPath[i]=='/' ){
   31305       i++;
   31306       break;
   31307     }
   31308   }
   31309   conchPath[i]='.';
   31310   while ( i<len ){
   31311     conchPath[i+1]=dbPath[i];
   31312     i++;
   31313   }
   31314 
   31315   /* append the "-conch" suffix to the file */
   31316   memcpy(&conchPath[i+1], "-conch", 7);
   31317   assert( (int)strlen(conchPath) == len+7 );
   31318 
   31319   return SQLITE_OK;
   31320 }
   31321 
   31322 
   31323 /* Takes a fully configured proxy locking-style unix file and switches
   31324 ** the local lock file path
   31325 */
   31326 static int switchLockProxyPath(unixFile *pFile, const char *path) {
   31327   proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
   31328   char *oldPath = pCtx->lockProxyPath;
   31329   int rc = SQLITE_OK;
   31330 
   31331   if( pFile->eFileLock!=NO_LOCK ){
   31332     return SQLITE_BUSY;
   31333   }
   31334 
   31335   /* nothing to do if the path is NULL, :auto: or matches the existing path */
   31336   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
   31337     (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
   31338     return SQLITE_OK;
   31339   }else{
   31340     unixFile *lockProxy = pCtx->lockProxy;
   31341     pCtx->lockProxy=NULL;
   31342     pCtx->conchHeld = 0;
   31343     if( lockProxy!=NULL ){
   31344       rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
   31345       if( rc ) return rc;
   31346       sqlite3_free(lockProxy);
   31347     }
   31348     sqlite3_free(oldPath);
   31349     pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
   31350   }
   31351 
   31352   return rc;
   31353 }
   31354 
   31355 /*
   31356 ** pFile is a file that has been opened by a prior xOpen call.  dbPath
   31357 ** is a string buffer at least MAXPATHLEN+1 characters in size.
   31358 **
   31359 ** This routine find the filename associated with pFile and writes it
   31360 ** int dbPath.
   31361 */
   31362 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
   31363 #if defined(__APPLE__)
   31364   if( pFile->pMethod == &afpIoMethods ){
   31365     /* afp style keeps a reference to the db path in the filePath field
   31366     ** of the struct */
   31367     assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
   31368     strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
   31369   } else
   31370 #endif
   31371   if( pFile->pMethod == &dotlockIoMethods ){
   31372     /* dot lock style uses the locking context to store the dot lock
   31373     ** file path */
   31374     int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
   31375     memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
   31376   }else{
   31377     /* all other styles use the locking context to store the db file path */
   31378     assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
   31379     strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
   31380   }
   31381   return SQLITE_OK;
   31382 }
   31383 
   31384 /*
   31385 ** Takes an already filled in unix file and alters it so all file locking
   31386 ** will be performed on the local proxy lock file.  The following fields
   31387 ** are preserved in the locking context so that they can be restored and
   31388 ** the unix structure properly cleaned up at close time:
   31389 **  ->lockingContext
   31390 **  ->pMethod
   31391 */
   31392 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
   31393   proxyLockingContext *pCtx;
   31394   char dbPath[MAXPATHLEN+1];       /* Name of the database file */
   31395   char *lockPath=NULL;
   31396   int rc = SQLITE_OK;
   31397 
   31398   if( pFile->eFileLock!=NO_LOCK ){
   31399     return SQLITE_BUSY;
   31400   }
   31401   proxyGetDbPathForUnixFile(pFile, dbPath);
   31402   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
   31403     lockPath=NULL;
   31404   }else{
   31405     lockPath=(char *)path;
   31406   }
   31407 
   31408   OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
   31409            (lockPath ? lockPath : ":auto:"), getpid()));
   31410 
   31411   pCtx = sqlite3_malloc( sizeof(*pCtx) );
   31412   if( pCtx==0 ){
   31413     return SQLITE_NOMEM;
   31414   }
   31415   memset(pCtx, 0, sizeof(*pCtx));
   31416 
   31417   rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
   31418   if( rc==SQLITE_OK ){
   31419     rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
   31420     if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
   31421       /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
   31422       ** (c) the file system is read-only, then enable no-locking access.
   31423       ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
   31424       ** that openFlags will have only one of O_RDONLY or O_RDWR.
   31425       */
   31426       struct statfs fsInfo;
   31427       struct stat conchInfo;
   31428       int goLockless = 0;
   31429 
   31430       if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
   31431         int err = errno;
   31432         if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
   31433           goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
   31434         }
   31435       }
   31436       if( goLockless ){
   31437         pCtx->conchHeld = -1; /* read only FS/ lockless */
   31438         rc = SQLITE_OK;
   31439       }
   31440     }
   31441   }
   31442   if( rc==SQLITE_OK && lockPath ){
   31443     pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
   31444   }
   31445 
   31446   if( rc==SQLITE_OK ){
   31447     pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
   31448     if( pCtx->dbPath==NULL ){
   31449       rc = SQLITE_NOMEM;
   31450     }
   31451   }
   31452   if( rc==SQLITE_OK ){
   31453     /* all memory is allocated, proxys are created and assigned,
   31454     ** switch the locking context and pMethod then return.
   31455     */
   31456     pCtx->oldLockingContext = pFile->lockingContext;
   31457     pFile->lockingContext = pCtx;
   31458     pCtx->pOldMethod = pFile->pMethod;
   31459     pFile->pMethod = &proxyIoMethods;
   31460   }else{
   31461     if( pCtx->conchFile ){
   31462       pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
   31463       sqlite3_free(pCtx->conchFile);
   31464     }
   31465     sqlite3DbFree(0, pCtx->lockProxyPath);
   31466     sqlite3_free(pCtx->conchFilePath);
   31467     sqlite3_free(pCtx);
   31468   }
   31469   OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
   31470            (rc==SQLITE_OK ? "ok" : "failed")));
   31471   return rc;
   31472 }
   31473 
   31474 
   31475 /*
   31476 ** This routine handles sqlite3_file_control() calls that are specific
   31477 ** to proxy locking.
   31478 */
   31479 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
   31480   switch( op ){
   31481     case SQLITE_GET_LOCKPROXYFILE: {
   31482       unixFile *pFile = (unixFile*)id;
   31483       if( pFile->pMethod == &proxyIoMethods ){
   31484         proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
   31485         proxyTakeConch(pFile);
   31486         if( pCtx->lockProxyPath ){
   31487           *(const char **)pArg = pCtx->lockProxyPath;
   31488         }else{
   31489           *(const char **)pArg = ":auto: (not held)";
   31490         }
   31491       } else {
   31492         *(const char **)pArg = NULL;
   31493       }
   31494       return SQLITE_OK;
   31495     }
   31496     case SQLITE_SET_LOCKPROXYFILE: {
   31497       unixFile *pFile = (unixFile*)id;
   31498       int rc = SQLITE_OK;
   31499       int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
   31500       if( pArg==NULL || (const char *)pArg==0 ){
   31501         if( isProxyStyle ){
   31502           /* turn off proxy locking - not supported */
   31503           rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
   31504         }else{
   31505           /* turn off proxy locking - already off - NOOP */
   31506           rc = SQLITE_OK;
   31507         }
   31508       }else{
   31509         const char *proxyPath = (const char *)pArg;
   31510         if( isProxyStyle ){
   31511           proxyLockingContext *pCtx =
   31512             (proxyLockingContext*)pFile->lockingContext;
   31513           if( !strcmp(pArg, ":auto:")
   31514            || (pCtx->lockProxyPath &&
   31515                !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
   31516           ){
   31517             rc = SQLITE_OK;
   31518           }else{
   31519             rc = switchLockProxyPath(pFile, proxyPath);
   31520           }
   31521         }else{
   31522           /* turn on proxy file locking */
   31523           rc = proxyTransformUnixFile(pFile, proxyPath);
   31524         }
   31525       }
   31526       return rc;
   31527     }
   31528     default: {
   31529       assert( 0 );  /* The call assures that only valid opcodes are sent */
   31530     }
   31531   }
   31532   /*NOTREACHED*/
   31533   return SQLITE_ERROR;
   31534 }
   31535 
   31536 /*
   31537 ** Within this division (the proxying locking implementation) the procedures
   31538 ** above this point are all utilities.  The lock-related methods of the
   31539 ** proxy-locking sqlite3_io_method object follow.
   31540 */
   31541 
   31542 
   31543 /*
   31544 ** This routine checks if there is a RESERVED lock held on the specified
   31545 ** file by this or any other process. If such a lock is held, set *pResOut
   31546 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   31547 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   31548 */
   31549 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
   31550   unixFile *pFile = (unixFile*)id;
   31551   int rc = proxyTakeConch(pFile);
   31552   if( rc==SQLITE_OK ){
   31553     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   31554     if( pCtx->conchHeld>0 ){
   31555       unixFile *proxy = pCtx->lockProxy;
   31556       return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
   31557     }else{ /* conchHeld < 0 is lockless */
   31558       pResOut=0;
   31559     }
   31560   }
   31561   return rc;
   31562 }
   31563 
   31564 /*
   31565 ** Lock the file with the lock specified by parameter eFileLock - one
   31566 ** of the following:
   31567 **
   31568 **     (1) SHARED_LOCK
   31569 **     (2) RESERVED_LOCK
   31570 **     (3) PENDING_LOCK
   31571 **     (4) EXCLUSIVE_LOCK
   31572 **
   31573 ** Sometimes when requesting one lock state, additional lock states
   31574 ** are inserted in between.  The locking might fail on one of the later
   31575 ** transitions leaving the lock state different from what it started but
   31576 ** still short of its goal.  The following chart shows the allowed
   31577 ** transitions and the inserted intermediate states:
   31578 **
   31579 **    UNLOCKED -> SHARED
   31580 **    SHARED -> RESERVED
   31581 **    SHARED -> (PENDING) -> EXCLUSIVE
   31582 **    RESERVED -> (PENDING) -> EXCLUSIVE
   31583 **    PENDING -> EXCLUSIVE
   31584 **
   31585 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   31586 ** routine to lower a locking level.
   31587 */
   31588 static int proxyLock(sqlite3_file *id, int eFileLock) {
   31589   unixFile *pFile = (unixFile*)id;
   31590   int rc = proxyTakeConch(pFile);
   31591   if( rc==SQLITE_OK ){
   31592     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   31593     if( pCtx->conchHeld>0 ){
   31594       unixFile *proxy = pCtx->lockProxy;
   31595       rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
   31596       pFile->eFileLock = proxy->eFileLock;
   31597     }else{
   31598       /* conchHeld < 0 is lockless */
   31599     }
   31600   }
   31601   return rc;
   31602 }
   31603 
   31604 
   31605 /*
   31606 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   31607 ** must be either NO_LOCK or SHARED_LOCK.
   31608 **
   31609 ** If the locking level of the file descriptor is already at or below
   31610 ** the requested locking level, this routine is a no-op.
   31611 */
   31612 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
   31613   unixFile *pFile = (unixFile*)id;
   31614   int rc = proxyTakeConch(pFile);
   31615   if( rc==SQLITE_OK ){
   31616     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   31617     if( pCtx->conchHeld>0 ){
   31618       unixFile *proxy = pCtx->lockProxy;
   31619       rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
   31620       pFile->eFileLock = proxy->eFileLock;
   31621     }else{
   31622       /* conchHeld < 0 is lockless */
   31623     }
   31624   }
   31625   return rc;
   31626 }
   31627 
   31628 /*
   31629 ** Close a file that uses proxy locks.
   31630 */
   31631 static int proxyClose(sqlite3_file *id) {
   31632   if( id ){
   31633     unixFile *pFile = (unixFile*)id;
   31634     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   31635     unixFile *lockProxy = pCtx->lockProxy;
   31636     unixFile *conchFile = pCtx->conchFile;
   31637     int rc = SQLITE_OK;
   31638 
   31639     if( lockProxy ){
   31640       rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
   31641       if( rc ) return rc;
   31642       rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
   31643       if( rc ) return rc;
   31644       sqlite3_free(lockProxy);
   31645       pCtx->lockProxy = 0;
   31646     }
   31647     if( conchFile ){
   31648       if( pCtx->conchHeld ){
   31649         rc = proxyReleaseConch(pFile);
   31650         if( rc ) return rc;
   31651       }
   31652       rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
   31653       if( rc ) return rc;
   31654       sqlite3_free(conchFile);
   31655     }
   31656     sqlite3DbFree(0, pCtx->lockProxyPath);
   31657     sqlite3_free(pCtx->conchFilePath);
   31658     sqlite3DbFree(0, pCtx->dbPath);
   31659     /* restore the original locking context and pMethod then close it */
   31660     pFile->lockingContext = pCtx->oldLockingContext;
   31661     pFile->pMethod = pCtx->pOldMethod;
   31662     sqlite3_free(pCtx);
   31663     return pFile->pMethod->xClose(id);
   31664   }
   31665   return SQLITE_OK;
   31666 }
   31667 
   31668 
   31669 
   31670 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
   31671 /*
   31672 ** The proxy locking style is intended for use with AFP filesystems.
   31673 ** And since AFP is only supported on MacOSX, the proxy locking is also
   31674 ** restricted to MacOSX.
   31675 **
   31676 **
   31677 ******************* End of the proxy lock implementation **********************
   31678 ******************************************************************************/
   31679 
   31680 /*
   31681 ** Initialize the operating system interface.
   31682 **
   31683 ** This routine registers all VFS implementations for unix-like operating
   31684 ** systems.  This routine, and the sqlite3_os_end() routine that follows,
   31685 ** should be the only routines in this file that are visible from other
   31686 ** files.
   31687 **
   31688 ** This routine is called once during SQLite initialization and by a
   31689 ** single thread.  The memory allocation and mutex subsystems have not
   31690 ** necessarily been initialized when this routine is called, and so they
   31691 ** should not be used.
   31692 */
   31693 SQLITE_API int sqlite3_os_init(void){
   31694   /*
   31695   ** The following macro defines an initializer for an sqlite3_vfs object.
   31696   ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
   31697   ** to the "finder" function.  (pAppData is a pointer to a pointer because
   31698   ** silly C90 rules prohibit a void* from being cast to a function pointer
   31699   ** and so we have to go through the intermediate pointer to avoid problems
   31700   ** when compiling with -pedantic-errors on GCC.)
   31701   **
   31702   ** The FINDER parameter to this macro is the name of the pointer to the
   31703   ** finder-function.  The finder-function returns a pointer to the
   31704   ** sqlite_io_methods object that implements the desired locking
   31705   ** behaviors.  See the division above that contains the IOMETHODS
   31706   ** macro for addition information on finder-functions.
   31707   **
   31708   ** Most finders simply return a pointer to a fixed sqlite3_io_methods
   31709   ** object.  But the "autolockIoFinder" available on MacOSX does a little
   31710   ** more than that; it looks at the filesystem type that hosts the
   31711   ** database file and tries to choose an locking method appropriate for
   31712   ** that filesystem time.
   31713   */
   31714   #define UNIXVFS(VFSNAME, FINDER) {                        \
   31715     3,                    /* iVersion */                    \
   31716     sizeof(unixFile),     /* szOsFile */                    \
   31717     MAX_PATHNAME,         /* mxPathname */                  \
   31718     0,                    /* pNext */                       \
   31719     VFSNAME,              /* zName */                       \
   31720     (void*)&FINDER,       /* pAppData */                    \
   31721     unixOpen,             /* xOpen */                       \
   31722     unixDelete,           /* xDelete */                     \
   31723     unixAccess,           /* xAccess */                     \
   31724     unixFullPathname,     /* xFullPathname */               \
   31725     unixDlOpen,           /* xDlOpen */                     \
   31726     unixDlError,          /* xDlError */                    \
   31727     unixDlSym,            /* xDlSym */                      \
   31728     unixDlClose,          /* xDlClose */                    \
   31729     unixRandomness,       /* xRandomness */                 \
   31730     unixSleep,            /* xSleep */                      \
   31731     unixCurrentTime,      /* xCurrentTime */                \
   31732     unixGetLastError,     /* xGetLastError */               \
   31733     unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
   31734     unixSetSystemCall,    /* xSetSystemCall */              \
   31735     unixGetSystemCall,    /* xGetSystemCall */              \
   31736     unixNextSystemCall,   /* xNextSystemCall */             \
   31737   }
   31738 
   31739   /*
   31740   ** All default VFSes for unix are contained in the following array.
   31741   **
   31742   ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
   31743   ** by the SQLite core when the VFS is registered.  So the following
   31744   ** array cannot be const.
   31745   */
   31746   static sqlite3_vfs aVfs[] = {
   31747 #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
   31748     UNIXVFS("unix",          autolockIoFinder ),
   31749 #else
   31750     UNIXVFS("unix",          posixIoFinder ),
   31751 #endif
   31752     UNIXVFS("unix-none",     nolockIoFinder ),
   31753     UNIXVFS("unix-dotfile",  dotlockIoFinder ),
   31754     UNIXVFS("unix-excl",     posixIoFinder ),
   31755 #if OS_VXWORKS
   31756     UNIXVFS("unix-namedsem", semIoFinder ),
   31757 #endif
   31758 #if SQLITE_ENABLE_LOCKING_STYLE
   31759     UNIXVFS("unix-posix",    posixIoFinder ),
   31760 #if !OS_VXWORKS
   31761     UNIXVFS("unix-flock",    flockIoFinder ),
   31762 #endif
   31763 #endif
   31764 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
   31765     UNIXVFS("unix-afp",      afpIoFinder ),
   31766     UNIXVFS("unix-nfs",      nfsIoFinder ),
   31767     UNIXVFS("unix-proxy",    proxyIoFinder ),
   31768 #endif
   31769   };
   31770   unsigned int i;          /* Loop counter */
   31771 
   31772   /* Double-check that the aSyscall[] array has been constructed
   31773   ** correctly.  See ticket [bb3a86e890c8e96ab] */
   31774   assert( ArraySize(aSyscall)==25 );
   31775 
   31776   /* Register all VFSes defined in the aVfs[] array */
   31777   for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
   31778     sqlite3_vfs_register(&aVfs[i], i==0);
   31779   }
   31780   return SQLITE_OK;
   31781 }
   31782 
   31783 /*
   31784 ** Shutdown the operating system interface.
   31785 **
   31786 ** Some operating systems might need to do some cleanup in this routine,
   31787 ** to release dynamically allocated objects.  But not on unix.
   31788 ** This routine is a no-op for unix.
   31789 */
   31790 SQLITE_API int sqlite3_os_end(void){
   31791   return SQLITE_OK;
   31792 }
   31793 
   31794 #endif /* SQLITE_OS_UNIX */
   31795 
   31796 /************** End of os_unix.c *********************************************/
   31797 /************** Begin file os_win.c ******************************************/
   31798 /*
   31799 ** 2004 May 22
   31800 **
   31801 ** The author disclaims copyright to this source code.  In place of
   31802 ** a legal notice, here is a blessing:
   31803 **
   31804 **    May you do good and not evil.
   31805 **    May you find forgiveness for yourself and forgive others.
   31806 **    May you share freely, never taking more than you give.
   31807 **
   31808 ******************************************************************************
   31809 **
   31810 ** This file contains code that is specific to Windows.
   31811 */
   31812 #if SQLITE_OS_WIN               /* This file is used for Windows only */
   31813 
   31814 /*
   31815 ** Include code that is common to all os_*.c files
   31816 */
   31817 /************** Include os_common.h in the middle of os_win.c ****************/
   31818 /************** Begin file os_common.h ***************************************/
   31819 /*
   31820 ** 2004 May 22
   31821 **
   31822 ** The author disclaims copyright to this source code.  In place of
   31823 ** a legal notice, here is a blessing:
   31824 **
   31825 **    May you do good and not evil.
   31826 **    May you find forgiveness for yourself and forgive others.
   31827 **    May you share freely, never taking more than you give.
   31828 **
   31829 ******************************************************************************
   31830 **
   31831 ** This file contains macros and a little bit of code that is common to
   31832 ** all of the platform-specific files (os_*.c) and is #included into those
   31833 ** files.
   31834 **
   31835 ** This file should be #included by the os_*.c files only.  It is not a
   31836 ** general purpose header file.
   31837 */
   31838 #ifndef _OS_COMMON_H_
   31839 #define _OS_COMMON_H_
   31840 
   31841 /*
   31842 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
   31843 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
   31844 ** switch.  The following code should catch this problem at compile-time.
   31845 */
   31846 #ifdef MEMORY_DEBUG
   31847 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
   31848 #endif
   31849 
   31850 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
   31851 # ifndef SQLITE_DEBUG_OS_TRACE
   31852 #   define SQLITE_DEBUG_OS_TRACE 0
   31853 # endif
   31854   int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
   31855 # define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
   31856 #else
   31857 # define OSTRACE(X)
   31858 #endif
   31859 
   31860 /*
   31861 ** Macros for performance tracing.  Normally turned off.  Only works
   31862 ** on i486 hardware.
   31863 */
   31864 #ifdef SQLITE_PERFORMANCE_TRACE
   31865 
   31866 /*
   31867 ** hwtime.h contains inline assembler code for implementing
   31868 ** high-performance timing routines.
   31869 */
   31870 /************** Include hwtime.h in the middle of os_common.h ****************/
   31871 /************** Begin file hwtime.h ******************************************/
   31872 /*
   31873 ** 2008 May 27
   31874 **
   31875 ** The author disclaims copyright to this source code.  In place of
   31876 ** a legal notice, here is a blessing:
   31877 **
   31878 **    May you do good and not evil.
   31879 **    May you find forgiveness for yourself and forgive others.
   31880 **    May you share freely, never taking more than you give.
   31881 **
   31882 ******************************************************************************
   31883 **
   31884 ** This file contains inline asm code for retrieving "high-performance"
   31885 ** counters for x86 class CPUs.
   31886 */
   31887 #ifndef _HWTIME_H_
   31888 #define _HWTIME_H_
   31889 
   31890 /*
   31891 ** The following routine only works on pentium-class (or newer) processors.
   31892 ** It uses the RDTSC opcode to read the cycle count value out of the
   31893 ** processor and returns that value.  This can be used for high-res
   31894 ** profiling.
   31895 */
   31896 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
   31897       (defined(i386) || defined(__i386__) || defined(_M_IX86))
   31898 
   31899   #if defined(__GNUC__)
   31900 
   31901   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   31902      unsigned int lo, hi;
   31903      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
   31904      return (sqlite_uint64)hi << 32 | lo;
   31905   }
   31906 
   31907   #elif defined(_MSC_VER)
   31908 
   31909   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
   31910      __asm {
   31911         rdtsc
   31912         ret       ; return value at EDX:EAX
   31913      }
   31914   }
   31915 
   31916   #endif
   31917 
   31918 #elif (defined(__GNUC__) && defined(__x86_64__))
   31919 
   31920   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   31921       unsigned long val;
   31922       __asm__ __volatile__ ("rdtsc" : "=A" (val));
   31923       return val;
   31924   }
   31925 
   31926 #elif (defined(__GNUC__) && defined(__ppc__))
   31927 
   31928   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   31929       unsigned long long retval;
   31930       unsigned long junk;
   31931       __asm__ __volatile__ ("\n\
   31932           1:      mftbu   %1\n\
   31933                   mftb    %L0\n\
   31934                   mftbu   %0\n\
   31935                   cmpw    %0,%1\n\
   31936                   bne     1b"
   31937                   : "=r" (retval), "=r" (junk));
   31938       return retval;
   31939   }
   31940 
   31941 #else
   31942 
   31943   #error Need implementation of sqlite3Hwtime() for your platform.
   31944 
   31945   /*
   31946   ** To compile without implementing sqlite3Hwtime() for your platform,
   31947   ** you can remove the above #error and use the following
   31948   ** stub function.  You will lose timing support for many
   31949   ** of the debugging and testing utilities, but it should at
   31950   ** least compile and run.
   31951   */
   31952 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
   31953 
   31954 #endif
   31955 
   31956 #endif /* !defined(_HWTIME_H_) */
   31957 
   31958 /************** End of hwtime.h **********************************************/
   31959 /************** Continuing where we left off in os_common.h ******************/
   31960 
   31961 static sqlite_uint64 g_start;
   31962 static sqlite_uint64 g_elapsed;
   31963 #define TIMER_START       g_start=sqlite3Hwtime()
   31964 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
   31965 #define TIMER_ELAPSED     g_elapsed
   31966 #else
   31967 #define TIMER_START
   31968 #define TIMER_END
   31969 #define TIMER_ELAPSED     ((sqlite_uint64)0)
   31970 #endif
   31971 
   31972 /*
   31973 ** If we compile with the SQLITE_TEST macro set, then the following block
   31974 ** of code will give us the ability to simulate a disk I/O error.  This
   31975 ** is used for testing the I/O recovery logic.
   31976 */
   31977 #ifdef SQLITE_TEST
   31978 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
   31979 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
   31980 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
   31981 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
   31982 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
   31983 SQLITE_API int sqlite3_diskfull_pending = 0;
   31984 SQLITE_API int sqlite3_diskfull = 0;
   31985 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
   31986 #define SimulateIOError(CODE)  \
   31987   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
   31988        || sqlite3_io_error_pending-- == 1 )  \
   31989               { local_ioerr(); CODE; }
   31990 static void local_ioerr(){
   31991   IOTRACE(("IOERR\n"));
   31992   sqlite3_io_error_hit++;
   31993   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
   31994 }
   31995 #define SimulateDiskfullError(CODE) \
   31996    if( sqlite3_diskfull_pending ){ \
   31997      if( sqlite3_diskfull_pending == 1 ){ \
   31998        local_ioerr(); \
   31999        sqlite3_diskfull = 1; \
   32000        sqlite3_io_error_hit = 1; \
   32001        CODE; \
   32002      }else{ \
   32003        sqlite3_diskfull_pending--; \
   32004      } \
   32005    }
   32006 #else
   32007 #define SimulateIOErrorBenign(X)
   32008 #define SimulateIOError(A)
   32009 #define SimulateDiskfullError(A)
   32010 #endif
   32011 
   32012 /*
   32013 ** When testing, keep a count of the number of open files.
   32014 */
   32015 #ifdef SQLITE_TEST
   32016 SQLITE_API int sqlite3_open_file_count = 0;
   32017 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
   32018 #else
   32019 #define OpenCounter(X)
   32020 #endif
   32021 
   32022 #endif /* !defined(_OS_COMMON_H_) */
   32023 
   32024 /************** End of os_common.h *******************************************/
   32025 /************** Continuing where we left off in os_win.c *********************/
   32026 
   32027 /*
   32028 ** Include the header file for the Windows VFS.
   32029 */
   32030 
   32031 /*
   32032 ** Compiling and using WAL mode requires several APIs that are only
   32033 ** available in Windows platforms based on the NT kernel.
   32034 */
   32035 #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
   32036 #  error "WAL mode requires support from the Windows NT kernel, compile\
   32037  with SQLITE_OMIT_WAL."
   32038 #endif
   32039 
   32040 /*
   32041 ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
   32042 ** based on the sub-platform)?
   32043 */
   32044 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
   32045 #  define SQLITE_WIN32_HAS_ANSI
   32046 #endif
   32047 
   32048 /*
   32049 ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
   32050 ** based on the sub-platform)?
   32051 */
   32052 #if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
   32053     !defined(SQLITE_WIN32_NO_WIDE)
   32054 #  define SQLITE_WIN32_HAS_WIDE
   32055 #endif
   32056 
   32057 /*
   32058 ** Make sure at least one set of Win32 APIs is available.
   32059 */
   32060 #if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
   32061 #  error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
   32062  must be defined."
   32063 #endif
   32064 
   32065 /*
   32066 ** Define the required Windows SDK version constants if they are not
   32067 ** already available.
   32068 */
   32069 #ifndef NTDDI_WIN8
   32070 #  define NTDDI_WIN8                        0x06020000
   32071 #endif
   32072 
   32073 #ifndef NTDDI_WINBLUE
   32074 #  define NTDDI_WINBLUE                     0x06030000
   32075 #endif
   32076 
   32077 /*
   32078 ** Check to see if the GetVersionEx[AW] functions are deprecated on the
   32079 ** target system.  GetVersionEx was first deprecated in Win8.1.
   32080 */
   32081 #ifndef SQLITE_WIN32_GETVERSIONEX
   32082 #  if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
   32083 #    define SQLITE_WIN32_GETVERSIONEX   0   /* GetVersionEx() is deprecated */
   32084 #  else
   32085 #    define SQLITE_WIN32_GETVERSIONEX   1   /* GetVersionEx() is current */
   32086 #  endif
   32087 #endif
   32088 
   32089 /*
   32090 ** This constant should already be defined (in the "WinDef.h" SDK file).
   32091 */
   32092 #ifndef MAX_PATH
   32093 #  define MAX_PATH                      (260)
   32094 #endif
   32095 
   32096 /*
   32097 ** Maximum pathname length (in chars) for Win32.  This should normally be
   32098 ** MAX_PATH.
   32099 */
   32100 #ifndef SQLITE_WIN32_MAX_PATH_CHARS
   32101 #  define SQLITE_WIN32_MAX_PATH_CHARS   (MAX_PATH)
   32102 #endif
   32103 
   32104 /*
   32105 ** This constant should already be defined (in the "WinNT.h" SDK file).
   32106 */
   32107 #ifndef UNICODE_STRING_MAX_CHARS
   32108 #  define UNICODE_STRING_MAX_CHARS      (32767)
   32109 #endif
   32110 
   32111 /*
   32112 ** Maximum pathname length (in chars) for WinNT.  This should normally be
   32113 ** UNICODE_STRING_MAX_CHARS.
   32114 */
   32115 #ifndef SQLITE_WINNT_MAX_PATH_CHARS
   32116 #  define SQLITE_WINNT_MAX_PATH_CHARS   (UNICODE_STRING_MAX_CHARS)
   32117 #endif
   32118 
   32119 /*
   32120 ** Maximum pathname length (in bytes) for Win32.  The MAX_PATH macro is in
   32121 ** characters, so we allocate 4 bytes per character assuming worst-case of
   32122 ** 4-bytes-per-character for UTF8.
   32123 */
   32124 #ifndef SQLITE_WIN32_MAX_PATH_BYTES
   32125 #  define SQLITE_WIN32_MAX_PATH_BYTES   (SQLITE_WIN32_MAX_PATH_CHARS*4)
   32126 #endif
   32127 
   32128 /*
   32129 ** Maximum pathname length (in bytes) for WinNT.  This should normally be
   32130 ** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
   32131 */
   32132 #ifndef SQLITE_WINNT_MAX_PATH_BYTES
   32133 #  define SQLITE_WINNT_MAX_PATH_BYTES   \
   32134                             (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
   32135 #endif
   32136 
   32137 /*
   32138 ** Maximum error message length (in chars) for WinRT.
   32139 */
   32140 #ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
   32141 #  define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
   32142 #endif
   32143 
   32144 /*
   32145 ** Returns non-zero if the character should be treated as a directory
   32146 ** separator.
   32147 */
   32148 #ifndef winIsDirSep
   32149 #  define winIsDirSep(a)                (((a) == '/') || ((a) == '\\'))
   32150 #endif
   32151 
   32152 /*
   32153 ** This macro is used when a local variable is set to a value that is
   32154 ** [sometimes] not used by the code (e.g. via conditional compilation).
   32155 */
   32156 #ifndef UNUSED_VARIABLE_VALUE
   32157 #  define UNUSED_VARIABLE_VALUE(x)      (void)(x)
   32158 #endif
   32159 
   32160 /*
   32161 ** Returns the character that should be used as the directory separator.
   32162 */
   32163 #ifndef winGetDirSep
   32164 #  define winGetDirSep()                '\\'
   32165 #endif
   32166 
   32167 /*
   32168 ** Do we need to manually define the Win32 file mapping APIs for use with WAL
   32169 ** mode (e.g. these APIs are available in the Windows CE SDK; however, they
   32170 ** are not present in the header file)?
   32171 */
   32172 #if SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL)
   32173 /*
   32174 ** Two of the file mapping APIs are different under WinRT.  Figure out which
   32175 ** set we need.
   32176 */
   32177 #if SQLITE_OS_WINRT
   32178 WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
   32179         LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
   32180 
   32181 WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
   32182 #else
   32183 #if defined(SQLITE_WIN32_HAS_ANSI)
   32184 WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
   32185         DWORD, DWORD, DWORD, LPCSTR);
   32186 #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
   32187 
   32188 #if defined(SQLITE_WIN32_HAS_WIDE)
   32189 WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
   32190         DWORD, DWORD, DWORD, LPCWSTR);
   32191 #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
   32192 
   32193 WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
   32194 #endif /* SQLITE_OS_WINRT */
   32195 
   32196 /*
   32197 ** This file mapping API is common to both Win32 and WinRT.
   32198 */
   32199 WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
   32200 #endif /* SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL) */
   32201 
   32202 /*
   32203 ** Some Microsoft compilers lack this definition.
   32204 */
   32205 #ifndef INVALID_FILE_ATTRIBUTES
   32206 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
   32207 #endif
   32208 
   32209 #ifndef FILE_FLAG_MASK
   32210 # define FILE_FLAG_MASK          (0xFF3C0000)
   32211 #endif
   32212 
   32213 #ifndef FILE_ATTRIBUTE_MASK
   32214 # define FILE_ATTRIBUTE_MASK     (0x0003FFF7)
   32215 #endif
   32216 
   32217 #ifndef SQLITE_OMIT_WAL
   32218 /* Forward references to structures used for WAL */
   32219 typedef struct winShm winShm;           /* A connection to shared-memory */
   32220 typedef struct winShmNode winShmNode;   /* A region of shared-memory */
   32221 #endif
   32222 
   32223 /*
   32224 ** WinCE lacks native support for file locking so we have to fake it
   32225 ** with some code of our own.
   32226 */
   32227 #if SQLITE_OS_WINCE
   32228 typedef struct winceLock {
   32229   int nReaders;       /* Number of reader locks obtained */
   32230   BOOL bPending;      /* Indicates a pending lock has been obtained */
   32231   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
   32232   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
   32233 } winceLock;
   32234 #endif
   32235 
   32236 /*
   32237 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
   32238 ** portability layer.
   32239 */
   32240 typedef struct winFile winFile;
   32241 struct winFile {
   32242   const sqlite3_io_methods *pMethod; /*** Must be first ***/
   32243   sqlite3_vfs *pVfs;      /* The VFS used to open this file */
   32244   HANDLE h;               /* Handle for accessing the file */
   32245   u8 locktype;            /* Type of lock currently held on this file */
   32246   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
   32247   u8 ctrlFlags;           /* Flags.  See WINFILE_* below */
   32248   DWORD lastErrno;        /* The Windows errno from the last I/O error */
   32249 #ifndef SQLITE_OMIT_WAL
   32250   winShm *pShm;           /* Instance of shared memory on this file */
   32251 #endif
   32252   const char *zPath;      /* Full pathname of this file */
   32253   int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
   32254 #if SQLITE_OS_WINCE
   32255   LPWSTR zDeleteOnClose;  /* Name of file to delete when closing */
   32256   HANDLE hMutex;          /* Mutex used to control access to shared lock */
   32257   HANDLE hShared;         /* Shared memory segment used for locking */
   32258   winceLock local;        /* Locks obtained by this instance of winFile */
   32259   winceLock *shared;      /* Global shared lock memory for the file  */
   32260 #endif
   32261 #if SQLITE_MAX_MMAP_SIZE>0
   32262   int nFetchOut;                /* Number of outstanding xFetch references */
   32263   HANDLE hMap;                  /* Handle for accessing memory mapping */
   32264   void *pMapRegion;             /* Area memory mapped */
   32265   sqlite3_int64 mmapSize;       /* Usable size of mapped region */
   32266   sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
   32267   sqlite3_int64 mmapSizeMax;    /* Configured FCNTL_MMAP_SIZE value */
   32268 #endif
   32269 };
   32270 
   32271 /*
   32272 ** Allowed values for winFile.ctrlFlags
   32273 */
   32274 #define WINFILE_RDONLY          0x02   /* Connection is read only */
   32275 #define WINFILE_PERSIST_WAL     0x04   /* Persistent WAL mode */
   32276 #define WINFILE_PSOW            0x10   /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
   32277 
   32278 /*
   32279  * The size of the buffer used by sqlite3_win32_write_debug().
   32280  */
   32281 #ifndef SQLITE_WIN32_DBG_BUF_SIZE
   32282 #  define SQLITE_WIN32_DBG_BUF_SIZE   ((int)(4096-sizeof(DWORD)))
   32283 #endif
   32284 
   32285 /*
   32286  * The value used with sqlite3_win32_set_directory() to specify that
   32287  * the data directory should be changed.
   32288  */
   32289 #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
   32290 #  define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
   32291 #endif
   32292 
   32293 /*
   32294  * The value used with sqlite3_win32_set_directory() to specify that
   32295  * the temporary directory should be changed.
   32296  */
   32297 #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
   32298 #  define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
   32299 #endif
   32300 
   32301 /*
   32302  * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
   32303  * various Win32 API heap functions instead of our own.
   32304  */
   32305 #ifdef SQLITE_WIN32_MALLOC
   32306 
   32307 /*
   32308  * If this is non-zero, an isolated heap will be created by the native Win32
   32309  * allocator subsystem; otherwise, the default process heap will be used.  This
   32310  * setting has no effect when compiling for WinRT.  By default, this is enabled
   32311  * and an isolated heap will be created to store all allocated data.
   32312  *
   32313  ******************************************************************************
   32314  * WARNING: It is important to note that when this setting is non-zero and the
   32315  *          winMemShutdown function is called (e.g. by the sqlite3_shutdown
   32316  *          function), all data that was allocated using the isolated heap will
   32317  *          be freed immediately and any attempt to access any of that freed
   32318  *          data will almost certainly result in an immediate access violation.
   32319  ******************************************************************************
   32320  */
   32321 #ifndef SQLITE_WIN32_HEAP_CREATE
   32322 #  define SQLITE_WIN32_HEAP_CREATE    (TRUE)
   32323 #endif
   32324 
   32325 /*
   32326  * The initial size of the Win32-specific heap.  This value may be zero.
   32327  */
   32328 #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
   32329 #  define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \
   32330                                        (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
   32331 #endif
   32332 
   32333 /*
   32334  * The maximum size of the Win32-specific heap.  This value may be zero.
   32335  */
   32336 #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
   32337 #  define SQLITE_WIN32_HEAP_MAX_SIZE  (0)
   32338 #endif
   32339 
   32340 /*
   32341  * The extra flags to use in calls to the Win32 heap APIs.  This value may be
   32342  * zero for the default behavior.
   32343  */
   32344 #ifndef SQLITE_WIN32_HEAP_FLAGS
   32345 #  define SQLITE_WIN32_HEAP_FLAGS     (0)
   32346 #endif
   32347 
   32348 
   32349 /*
   32350 ** The winMemData structure stores information required by the Win32-specific
   32351 ** sqlite3_mem_methods implementation.
   32352 */
   32353 typedef struct winMemData winMemData;
   32354 struct winMemData {
   32355 #ifndef NDEBUG
   32356   u32 magic1;   /* Magic number to detect structure corruption. */
   32357 #endif
   32358   HANDLE hHeap; /* The handle to our heap. */
   32359   BOOL bOwned;  /* Do we own the heap (i.e. destroy it on shutdown)? */
   32360 #ifndef NDEBUG
   32361   u32 magic2;   /* Magic number to detect structure corruption. */
   32362 #endif
   32363 };
   32364 
   32365 #ifndef NDEBUG
   32366 #define WINMEM_MAGIC1     0x42b2830b
   32367 #define WINMEM_MAGIC2     0xbd4d7cf4
   32368 #endif
   32369 
   32370 static struct winMemData win_mem_data = {
   32371 #ifndef NDEBUG
   32372   WINMEM_MAGIC1,
   32373 #endif
   32374   NULL, FALSE
   32375 #ifndef NDEBUG
   32376   ,WINMEM_MAGIC2
   32377 #endif
   32378 };
   32379 
   32380 #ifndef NDEBUG
   32381 #define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
   32382 #define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
   32383 #define winMemAssertMagic()  winMemAssertMagic1(); winMemAssertMagic2();
   32384 #else
   32385 #define winMemAssertMagic()
   32386 #endif
   32387 
   32388 #define winMemGetDataPtr()  &win_mem_data
   32389 #define winMemGetHeap()     win_mem_data.hHeap
   32390 #define winMemGetOwned()    win_mem_data.bOwned
   32391 
   32392 static void *winMemMalloc(int nBytes);
   32393 static void winMemFree(void *pPrior);
   32394 static void *winMemRealloc(void *pPrior, int nBytes);
   32395 static int winMemSize(void *p);
   32396 static int winMemRoundup(int n);
   32397 static int winMemInit(void *pAppData);
   32398 static void winMemShutdown(void *pAppData);
   32399 
   32400 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
   32401 #endif /* SQLITE_WIN32_MALLOC */
   32402 
   32403 /*
   32404 ** The following variable is (normally) set once and never changes
   32405 ** thereafter.  It records whether the operating system is Win9x
   32406 ** or WinNT.
   32407 **
   32408 ** 0:   Operating system unknown.
   32409 ** 1:   Operating system is Win9x.
   32410 ** 2:   Operating system is WinNT.
   32411 **
   32412 ** In order to facilitate testing on a WinNT system, the test fixture
   32413 ** can manually set this value to 1 to emulate Win98 behavior.
   32414 */
   32415 #ifdef SQLITE_TEST
   32416 SQLITE_API LONG volatile sqlite3_os_type = 0;
   32417 #else
   32418 static LONG volatile sqlite3_os_type = 0;
   32419 #endif
   32420 
   32421 #ifndef SYSCALL
   32422 #  define SYSCALL sqlite3_syscall_ptr
   32423 #endif
   32424 
   32425 /*
   32426 ** This function is not available on Windows CE or WinRT.
   32427  */
   32428 
   32429 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
   32430 #  define osAreFileApisANSI()       1
   32431 #endif
   32432 
   32433 /*
   32434 ** Many system calls are accessed through pointer-to-functions so that
   32435 ** they may be overridden at runtime to facilitate fault injection during
   32436 ** testing and sandboxing.  The following array holds the names and pointers
   32437 ** to all overrideable system calls.
   32438 */
   32439 static struct win_syscall {
   32440   const char *zName;            /* Name of the system call */
   32441   sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
   32442   sqlite3_syscall_ptr pDefault; /* Default value */
   32443 } aSyscall[] = {
   32444 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
   32445   { "AreFileApisANSI",         (SYSCALL)AreFileApisANSI,         0 },
   32446 #else
   32447   { "AreFileApisANSI",         (SYSCALL)0,                       0 },
   32448 #endif
   32449 
   32450 #ifndef osAreFileApisANSI
   32451 #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
   32452 #endif
   32453 
   32454 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
   32455   { "CharLowerW",              (SYSCALL)CharLowerW,              0 },
   32456 #else
   32457   { "CharLowerW",              (SYSCALL)0,                       0 },
   32458 #endif
   32459 
   32460 #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
   32461 
   32462 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
   32463   { "CharUpperW",              (SYSCALL)CharUpperW,              0 },
   32464 #else
   32465   { "CharUpperW",              (SYSCALL)0,                       0 },
   32466 #endif
   32467 
   32468 #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
   32469 
   32470   { "CloseHandle",             (SYSCALL)CloseHandle,             0 },
   32471 
   32472 #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
   32473 
   32474 #if defined(SQLITE_WIN32_HAS_ANSI)
   32475   { "CreateFileA",             (SYSCALL)CreateFileA,             0 },
   32476 #else
   32477   { "CreateFileA",             (SYSCALL)0,                       0 },
   32478 #endif
   32479 
   32480 #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
   32481         LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
   32482 
   32483 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
   32484   { "CreateFileW",             (SYSCALL)CreateFileW,             0 },
   32485 #else
   32486   { "CreateFileW",             (SYSCALL)0,                       0 },
   32487 #endif
   32488 
   32489 #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
   32490         LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
   32491 
   32492 #if (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
   32493         !defined(SQLITE_OMIT_WAL))
   32494   { "CreateFileMappingA",      (SYSCALL)CreateFileMappingA,      0 },
   32495 #else
   32496   { "CreateFileMappingA",      (SYSCALL)0,                       0 },
   32497 #endif
   32498 
   32499 #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
   32500         DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
   32501 
   32502 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
   32503         !defined(SQLITE_OMIT_WAL))
   32504   { "CreateFileMappingW",      (SYSCALL)CreateFileMappingW,      0 },
   32505 #else
   32506   { "CreateFileMappingW",      (SYSCALL)0,                       0 },
   32507 #endif
   32508 
   32509 #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
   32510         DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
   32511 
   32512 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
   32513   { "CreateMutexW",            (SYSCALL)CreateMutexW,            0 },
   32514 #else
   32515   { "CreateMutexW",            (SYSCALL)0,                       0 },
   32516 #endif
   32517 
   32518 #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
   32519         LPCWSTR))aSyscall[8].pCurrent)
   32520 
   32521 #if defined(SQLITE_WIN32_HAS_ANSI)
   32522   { "DeleteFileA",             (SYSCALL)DeleteFileA,             0 },
   32523 #else
   32524   { "DeleteFileA",             (SYSCALL)0,                       0 },
   32525 #endif
   32526 
   32527 #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
   32528 
   32529 #if defined(SQLITE_WIN32_HAS_WIDE)
   32530   { "DeleteFileW",             (SYSCALL)DeleteFileW,             0 },
   32531 #else
   32532   { "DeleteFileW",             (SYSCALL)0,                       0 },
   32533 #endif
   32534 
   32535 #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
   32536 
   32537 #if SQLITE_OS_WINCE
   32538   { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
   32539 #else
   32540   { "FileTimeToLocalFileTime", (SYSCALL)0,                       0 },
   32541 #endif
   32542 
   32543 #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
   32544         LPFILETIME))aSyscall[11].pCurrent)
   32545 
   32546 #if SQLITE_OS_WINCE
   32547   { "FileTimeToSystemTime",    (SYSCALL)FileTimeToSystemTime,    0 },
   32548 #else
   32549   { "FileTimeToSystemTime",    (SYSCALL)0,                       0 },
   32550 #endif
   32551 
   32552 #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
   32553         LPSYSTEMTIME))aSyscall[12].pCurrent)
   32554 
   32555   { "FlushFileBuffers",        (SYSCALL)FlushFileBuffers,        0 },
   32556 
   32557 #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
   32558 
   32559 #if defined(SQLITE_WIN32_HAS_ANSI)
   32560   { "FormatMessageA",          (SYSCALL)FormatMessageA,          0 },
   32561 #else
   32562   { "FormatMessageA",          (SYSCALL)0,                       0 },
   32563 #endif
   32564 
   32565 #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
   32566         DWORD,va_list*))aSyscall[14].pCurrent)
   32567 
   32568 #if defined(SQLITE_WIN32_HAS_WIDE)
   32569   { "FormatMessageW",          (SYSCALL)FormatMessageW,          0 },
   32570 #else
   32571   { "FormatMessageW",          (SYSCALL)0,                       0 },
   32572 #endif
   32573 
   32574 #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
   32575         DWORD,va_list*))aSyscall[15].pCurrent)
   32576 
   32577 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
   32578   { "FreeLibrary",             (SYSCALL)FreeLibrary,             0 },
   32579 #else
   32580   { "FreeLibrary",             (SYSCALL)0,                       0 },
   32581 #endif
   32582 
   32583 #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
   32584 
   32585   { "GetCurrentProcessId",     (SYSCALL)GetCurrentProcessId,     0 },
   32586 
   32587 #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
   32588 
   32589 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
   32590   { "GetDiskFreeSpaceA",       (SYSCALL)GetDiskFreeSpaceA,       0 },
   32591 #else
   32592   { "GetDiskFreeSpaceA",       (SYSCALL)0,                       0 },
   32593 #endif
   32594 
   32595 #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
   32596         LPDWORD))aSyscall[18].pCurrent)
   32597 
   32598 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
   32599   { "GetDiskFreeSpaceW",       (SYSCALL)GetDiskFreeSpaceW,       0 },
   32600 #else
   32601   { "GetDiskFreeSpaceW",       (SYSCALL)0,                       0 },
   32602 #endif
   32603 
   32604 #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
   32605         LPDWORD))aSyscall[19].pCurrent)
   32606 
   32607 #if defined(SQLITE_WIN32_HAS_ANSI)
   32608   { "GetFileAttributesA",      (SYSCALL)GetFileAttributesA,      0 },
   32609 #else
   32610   { "GetFileAttributesA",      (SYSCALL)0,                       0 },
   32611 #endif
   32612 
   32613 #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
   32614 
   32615 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
   32616   { "GetFileAttributesW",      (SYSCALL)GetFileAttributesW,      0 },
   32617 #else
   32618   { "GetFileAttributesW",      (SYSCALL)0,                       0 },
   32619 #endif
   32620 
   32621 #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
   32622 
   32623 #if defined(SQLITE_WIN32_HAS_WIDE)
   32624   { "GetFileAttributesExW",    (SYSCALL)GetFileAttributesExW,    0 },
   32625 #else
   32626   { "GetFileAttributesExW",    (SYSCALL)0,                       0 },
   32627 #endif
   32628 
   32629 #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
   32630         LPVOID))aSyscall[22].pCurrent)
   32631 
   32632 #if !SQLITE_OS_WINRT
   32633   { "GetFileSize",             (SYSCALL)GetFileSize,             0 },
   32634 #else
   32635   { "GetFileSize",             (SYSCALL)0,                       0 },
   32636 #endif
   32637 
   32638 #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
   32639 
   32640 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
   32641   { "GetFullPathNameA",        (SYSCALL)GetFullPathNameA,        0 },
   32642 #else
   32643   { "GetFullPathNameA",        (SYSCALL)0,                       0 },
   32644 #endif
   32645 
   32646 #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
   32647         LPSTR*))aSyscall[24].pCurrent)
   32648 
   32649 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
   32650   { "GetFullPathNameW",        (SYSCALL)GetFullPathNameW,        0 },
   32651 #else
   32652   { "GetFullPathNameW",        (SYSCALL)0,                       0 },
   32653 #endif
   32654 
   32655 #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
   32656         LPWSTR*))aSyscall[25].pCurrent)
   32657 
   32658   { "GetLastError",            (SYSCALL)GetLastError,            0 },
   32659 
   32660 #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
   32661 
   32662 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
   32663 #if SQLITE_OS_WINCE
   32664   /* The GetProcAddressA() routine is only available on Windows CE. */
   32665   { "GetProcAddressA",         (SYSCALL)GetProcAddressA,         0 },
   32666 #else
   32667   /* All other Windows platforms expect GetProcAddress() to take
   32668   ** an ANSI string regardless of the _UNICODE setting */
   32669   { "GetProcAddressA",         (SYSCALL)GetProcAddress,          0 },
   32670 #endif
   32671 #else
   32672   { "GetProcAddressA",         (SYSCALL)0,                       0 },
   32673 #endif
   32674 
   32675 #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
   32676         LPCSTR))aSyscall[27].pCurrent)
   32677 
   32678 #if !SQLITE_OS_WINRT
   32679   { "GetSystemInfo",           (SYSCALL)GetSystemInfo,           0 },
   32680 #else
   32681   { "GetSystemInfo",           (SYSCALL)0,                       0 },
   32682 #endif
   32683 
   32684 #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
   32685 
   32686   { "GetSystemTime",           (SYSCALL)GetSystemTime,           0 },
   32687 
   32688 #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
   32689 
   32690 #if !SQLITE_OS_WINCE
   32691   { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
   32692 #else
   32693   { "GetSystemTimeAsFileTime", (SYSCALL)0,                       0 },
   32694 #endif
   32695 
   32696 #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
   32697         LPFILETIME))aSyscall[30].pCurrent)
   32698 
   32699 #if defined(SQLITE_WIN32_HAS_ANSI)
   32700   { "GetTempPathA",            (SYSCALL)GetTempPathA,            0 },
   32701 #else
   32702   { "GetTempPathA",            (SYSCALL)0,                       0 },
   32703 #endif
   32704 
   32705 #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
   32706 
   32707 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
   32708   { "GetTempPathW",            (SYSCALL)GetTempPathW,            0 },
   32709 #else
   32710   { "GetTempPathW",            (SYSCALL)0,                       0 },
   32711 #endif
   32712 
   32713 #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
   32714 
   32715 #if !SQLITE_OS_WINRT
   32716   { "GetTickCount",            (SYSCALL)GetTickCount,            0 },
   32717 #else
   32718   { "GetTickCount",            (SYSCALL)0,                       0 },
   32719 #endif
   32720 
   32721 #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
   32722 
   32723 #if defined(SQLITE_WIN32_HAS_ANSI) && defined(SQLITE_WIN32_GETVERSIONEX) && \
   32724         SQLITE_WIN32_GETVERSIONEX
   32725   { "GetVersionExA",           (SYSCALL)GetVersionExA,           0 },
   32726 #else
   32727   { "GetVersionExA",           (SYSCALL)0,                       0 },
   32728 #endif
   32729 
   32730 #define osGetVersionExA ((BOOL(WINAPI*)( \
   32731         LPOSVERSIONINFOA))aSyscall[34].pCurrent)
   32732 
   32733 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
   32734         defined(SQLITE_WIN32_GETVERSIONEX) && SQLITE_WIN32_GETVERSIONEX
   32735   { "GetVersionExW",           (SYSCALL)GetVersionExW,           0 },
   32736 #else
   32737   { "GetVersionExW",           (SYSCALL)0,                       0 },
   32738 #endif
   32739 
   32740 #define osGetVersionExW ((BOOL(WINAPI*)( \
   32741         LPOSVERSIONINFOW))aSyscall[35].pCurrent)
   32742 
   32743   { "HeapAlloc",               (SYSCALL)HeapAlloc,               0 },
   32744 
   32745 #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
   32746         SIZE_T))aSyscall[36].pCurrent)
   32747 
   32748 #if !SQLITE_OS_WINRT
   32749   { "HeapCreate",              (SYSCALL)HeapCreate,              0 },
   32750 #else
   32751   { "HeapCreate",              (SYSCALL)0,                       0 },
   32752 #endif
   32753 
   32754 #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
   32755         SIZE_T))aSyscall[37].pCurrent)
   32756 
   32757 #if !SQLITE_OS_WINRT
   32758   { "HeapDestroy",             (SYSCALL)HeapDestroy,             0 },
   32759 #else
   32760   { "HeapDestroy",             (SYSCALL)0,                       0 },
   32761 #endif
   32762 
   32763 #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
   32764 
   32765   { "HeapFree",                (SYSCALL)HeapFree,                0 },
   32766 
   32767 #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
   32768 
   32769   { "HeapReAlloc",             (SYSCALL)HeapReAlloc,             0 },
   32770 
   32771 #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
   32772         SIZE_T))aSyscall[40].pCurrent)
   32773 
   32774   { "HeapSize",                (SYSCALL)HeapSize,                0 },
   32775 
   32776 #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
   32777         LPCVOID))aSyscall[41].pCurrent)
   32778 
   32779 #if !SQLITE_OS_WINRT
   32780   { "HeapValidate",            (SYSCALL)HeapValidate,            0 },
   32781 #else
   32782   { "HeapValidate",            (SYSCALL)0,                       0 },
   32783 #endif
   32784 
   32785 #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
   32786         LPCVOID))aSyscall[42].pCurrent)
   32787 
   32788 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
   32789   { "HeapCompact",             (SYSCALL)HeapCompact,             0 },
   32790 #else
   32791   { "HeapCompact",             (SYSCALL)0,                       0 },
   32792 #endif
   32793 
   32794 #define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
   32795 
   32796 #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
   32797   { "LoadLibraryA",            (SYSCALL)LoadLibraryA,            0 },
   32798 #else
   32799   { "LoadLibraryA",            (SYSCALL)0,                       0 },
   32800 #endif
   32801 
   32802 #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
   32803 
   32804 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
   32805         !defined(SQLITE_OMIT_LOAD_EXTENSION)
   32806   { "LoadLibraryW",            (SYSCALL)LoadLibraryW,            0 },
   32807 #else
   32808   { "LoadLibraryW",            (SYSCALL)0,                       0 },
   32809 #endif
   32810 
   32811 #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
   32812 
   32813 #if !SQLITE_OS_WINRT
   32814   { "LocalFree",               (SYSCALL)LocalFree,               0 },
   32815 #else
   32816   { "LocalFree",               (SYSCALL)0,                       0 },
   32817 #endif
   32818 
   32819 #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
   32820 
   32821 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
   32822   { "LockFile",                (SYSCALL)LockFile,                0 },
   32823 #else
   32824   { "LockFile",                (SYSCALL)0,                       0 },
   32825 #endif
   32826 
   32827 #ifndef osLockFile
   32828 #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
   32829         DWORD))aSyscall[47].pCurrent)
   32830 #endif
   32831 
   32832 #if !SQLITE_OS_WINCE
   32833   { "LockFileEx",              (SYSCALL)LockFileEx,              0 },
   32834 #else
   32835   { "LockFileEx",              (SYSCALL)0,                       0 },
   32836 #endif
   32837 
   32838 #ifndef osLockFileEx
   32839 #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
   32840         LPOVERLAPPED))aSyscall[48].pCurrent)
   32841 #endif
   32842 
   32843 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL))
   32844   { "MapViewOfFile",           (SYSCALL)MapViewOfFile,           0 },
   32845 #else
   32846   { "MapViewOfFile",           (SYSCALL)0,                       0 },
   32847 #endif
   32848 
   32849 #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
   32850         SIZE_T))aSyscall[49].pCurrent)
   32851 
   32852   { "MultiByteToWideChar",     (SYSCALL)MultiByteToWideChar,     0 },
   32853 
   32854 #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
   32855         int))aSyscall[50].pCurrent)
   32856 
   32857   { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
   32858 
   32859 #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
   32860         LARGE_INTEGER*))aSyscall[51].pCurrent)
   32861 
   32862   { "ReadFile",                (SYSCALL)ReadFile,                0 },
   32863 
   32864 #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
   32865         LPOVERLAPPED))aSyscall[52].pCurrent)
   32866 
   32867   { "SetEndOfFile",            (SYSCALL)SetEndOfFile,            0 },
   32868 
   32869 #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
   32870 
   32871 #if !SQLITE_OS_WINRT
   32872   { "SetFilePointer",          (SYSCALL)SetFilePointer,          0 },
   32873 #else
   32874   { "SetFilePointer",          (SYSCALL)0,                       0 },
   32875 #endif
   32876 
   32877 #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
   32878         DWORD))aSyscall[54].pCurrent)
   32879 
   32880 #if !SQLITE_OS_WINRT
   32881   { "Sleep",                   (SYSCALL)Sleep,                   0 },
   32882 #else
   32883   { "Sleep",                   (SYSCALL)0,                       0 },
   32884 #endif
   32885 
   32886 #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
   32887 
   32888   { "SystemTimeToFileTime",    (SYSCALL)SystemTimeToFileTime,    0 },
   32889 
   32890 #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
   32891         LPFILETIME))aSyscall[56].pCurrent)
   32892 
   32893 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
   32894   { "UnlockFile",              (SYSCALL)UnlockFile,              0 },
   32895 #else
   32896   { "UnlockFile",              (SYSCALL)0,                       0 },
   32897 #endif
   32898 
   32899 #ifndef osUnlockFile
   32900 #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
   32901         DWORD))aSyscall[57].pCurrent)
   32902 #endif
   32903 
   32904 #if !SQLITE_OS_WINCE
   32905   { "UnlockFileEx",            (SYSCALL)UnlockFileEx,            0 },
   32906 #else
   32907   { "UnlockFileEx",            (SYSCALL)0,                       0 },
   32908 #endif
   32909 
   32910 #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
   32911         LPOVERLAPPED))aSyscall[58].pCurrent)
   32912 
   32913 #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL)
   32914   { "UnmapViewOfFile",         (SYSCALL)UnmapViewOfFile,         0 },
   32915 #else
   32916   { "UnmapViewOfFile",         (SYSCALL)0,                       0 },
   32917 #endif
   32918 
   32919 #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
   32920 
   32921   { "WideCharToMultiByte",     (SYSCALL)WideCharToMultiByte,     0 },
   32922 
   32923 #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
   32924         LPCSTR,LPBOOL))aSyscall[60].pCurrent)
   32925 
   32926   { "WriteFile",               (SYSCALL)WriteFile,               0 },
   32927 
   32928 #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
   32929         LPOVERLAPPED))aSyscall[61].pCurrent)
   32930 
   32931 #if SQLITE_OS_WINRT
   32932   { "CreateEventExW",          (SYSCALL)CreateEventExW,          0 },
   32933 #else
   32934   { "CreateEventExW",          (SYSCALL)0,                       0 },
   32935 #endif
   32936 
   32937 #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
   32938         DWORD,DWORD))aSyscall[62].pCurrent)
   32939 
   32940 #if !SQLITE_OS_WINRT
   32941   { "WaitForSingleObject",     (SYSCALL)WaitForSingleObject,     0 },
   32942 #else
   32943   { "WaitForSingleObject",     (SYSCALL)0,                       0 },
   32944 #endif
   32945 
   32946 #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
   32947         DWORD))aSyscall[63].pCurrent)
   32948 
   32949 #if SQLITE_OS_WINRT
   32950   { "WaitForSingleObjectEx",   (SYSCALL)WaitForSingleObjectEx,   0 },
   32951 #else
   32952   { "WaitForSingleObjectEx",   (SYSCALL)0,                       0 },
   32953 #endif
   32954 
   32955 #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
   32956         BOOL))aSyscall[64].pCurrent)
   32957 
   32958 #if SQLITE_OS_WINRT
   32959   { "SetFilePointerEx",        (SYSCALL)SetFilePointerEx,        0 },
   32960 #else
   32961   { "SetFilePointerEx",        (SYSCALL)0,                       0 },
   32962 #endif
   32963 
   32964 #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
   32965         PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
   32966 
   32967 #if SQLITE_OS_WINRT
   32968   { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
   32969 #else
   32970   { "GetFileInformationByHandleEx", (SYSCALL)0,                  0 },
   32971 #endif
   32972 
   32973 #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
   32974         FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
   32975 
   32976 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
   32977   { "MapViewOfFileFromApp",    (SYSCALL)MapViewOfFileFromApp,    0 },
   32978 #else
   32979   { "MapViewOfFileFromApp",    (SYSCALL)0,                       0 },
   32980 #endif
   32981 
   32982 #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
   32983         SIZE_T))aSyscall[67].pCurrent)
   32984 
   32985 #if SQLITE_OS_WINRT
   32986   { "CreateFile2",             (SYSCALL)CreateFile2,             0 },
   32987 #else
   32988   { "CreateFile2",             (SYSCALL)0,                       0 },
   32989 #endif
   32990 
   32991 #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
   32992         LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
   32993 
   32994 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
   32995   { "LoadPackagedLibrary",     (SYSCALL)LoadPackagedLibrary,     0 },
   32996 #else
   32997   { "LoadPackagedLibrary",     (SYSCALL)0,                       0 },
   32998 #endif
   32999 
   33000 #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
   33001         DWORD))aSyscall[69].pCurrent)
   33002 
   33003 #if SQLITE_OS_WINRT
   33004   { "GetTickCount64",          (SYSCALL)GetTickCount64,          0 },
   33005 #else
   33006   { "GetTickCount64",          (SYSCALL)0,                       0 },
   33007 #endif
   33008 
   33009 #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
   33010 
   33011 #if SQLITE_OS_WINRT
   33012   { "GetNativeSystemInfo",     (SYSCALL)GetNativeSystemInfo,     0 },
   33013 #else
   33014   { "GetNativeSystemInfo",     (SYSCALL)0,                       0 },
   33015 #endif
   33016 
   33017 #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
   33018         LPSYSTEM_INFO))aSyscall[71].pCurrent)
   33019 
   33020 #if defined(SQLITE_WIN32_HAS_ANSI)
   33021   { "OutputDebugStringA",      (SYSCALL)OutputDebugStringA,      0 },
   33022 #else
   33023   { "OutputDebugStringA",      (SYSCALL)0,                       0 },
   33024 #endif
   33025 
   33026 #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
   33027 
   33028 #if defined(SQLITE_WIN32_HAS_WIDE)
   33029   { "OutputDebugStringW",      (SYSCALL)OutputDebugStringW,      0 },
   33030 #else
   33031   { "OutputDebugStringW",      (SYSCALL)0,                       0 },
   33032 #endif
   33033 
   33034 #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
   33035 
   33036   { "GetProcessHeap",          (SYSCALL)GetProcessHeap,          0 },
   33037 
   33038 #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
   33039 
   33040 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
   33041   { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
   33042 #else
   33043   { "CreateFileMappingFromApp", (SYSCALL)0,                      0 },
   33044 #endif
   33045 
   33046 #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
   33047         LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
   33048 
   33049 /*
   33050 ** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
   33051 **       is really just a macro that uses a compiler intrinsic (e.g. x64).
   33052 **       So do not try to make this is into a redefinable interface.
   33053 */
   33054 #if defined(InterlockedCompareExchange)
   33055   { "InterlockedCompareExchange", (SYSCALL)0,                    0 },
   33056 
   33057 #define osInterlockedCompareExchange InterlockedCompareExchange
   33058 #else
   33059   { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
   33060 
   33061 #define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG volatile*, \
   33062         LONG,LONG))aSyscall[76].pCurrent)
   33063 #endif /* defined(InterlockedCompareExchange) */
   33064 
   33065 }; /* End of the overrideable system calls */
   33066 
   33067 /*
   33068 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
   33069 ** "win32" VFSes.  Return SQLITE_OK opon successfully updating the
   33070 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
   33071 ** system call named zName.
   33072 */
   33073 static int winSetSystemCall(
   33074   sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
   33075   const char *zName,            /* Name of system call to override */
   33076   sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
   33077 ){
   33078   unsigned int i;
   33079   int rc = SQLITE_NOTFOUND;
   33080 
   33081   UNUSED_PARAMETER(pNotUsed);
   33082   if( zName==0 ){
   33083     /* If no zName is given, restore all system calls to their default
   33084     ** settings and return NULL
   33085     */
   33086     rc = SQLITE_OK;
   33087     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
   33088       if( aSyscall[i].pDefault ){
   33089         aSyscall[i].pCurrent = aSyscall[i].pDefault;
   33090       }
   33091     }
   33092   }else{
   33093     /* If zName is specified, operate on only the one system call
   33094     ** specified.
   33095     */
   33096     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
   33097       if( strcmp(zName, aSyscall[i].zName)==0 ){
   33098         if( aSyscall[i].pDefault==0 ){
   33099           aSyscall[i].pDefault = aSyscall[i].pCurrent;
   33100         }
   33101         rc = SQLITE_OK;
   33102         if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
   33103         aSyscall[i].pCurrent = pNewFunc;
   33104         break;
   33105       }
   33106     }
   33107   }
   33108   return rc;
   33109 }
   33110 
   33111 /*
   33112 ** Return the value of a system call.  Return NULL if zName is not a
   33113 ** recognized system call name.  NULL is also returned if the system call
   33114 ** is currently undefined.
   33115 */
   33116 static sqlite3_syscall_ptr winGetSystemCall(
   33117   sqlite3_vfs *pNotUsed,
   33118   const char *zName
   33119 ){
   33120   unsigned int i;
   33121 
   33122   UNUSED_PARAMETER(pNotUsed);
   33123   for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
   33124     if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
   33125   }
   33126   return 0;
   33127 }
   33128 
   33129 /*
   33130 ** Return the name of the first system call after zName.  If zName==NULL
   33131 ** then return the name of the first system call.  Return NULL if zName
   33132 ** is the last system call or if zName is not the name of a valid
   33133 ** system call.
   33134 */
   33135 static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
   33136   int i = -1;
   33137 
   33138   UNUSED_PARAMETER(p);
   33139   if( zName ){
   33140     for(i=0; i<ArraySize(aSyscall)-1; i++){
   33141       if( strcmp(zName, aSyscall[i].zName)==0 ) break;
   33142     }
   33143   }
   33144   for(i++; i<ArraySize(aSyscall); i++){
   33145     if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
   33146   }
   33147   return 0;
   33148 }
   33149 
   33150 #ifdef SQLITE_WIN32_MALLOC
   33151 /*
   33152 ** If a Win32 native heap has been configured, this function will attempt to
   33153 ** compact it.  Upon success, SQLITE_OK will be returned.  Upon failure, one
   33154 ** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned.  The
   33155 ** "pnLargest" argument, if non-zero, will be used to return the size of the
   33156 ** largest committed free block in the heap, in bytes.
   33157 */
   33158 SQLITE_API int sqlite3_win32_compact_heap(LPUINT pnLargest){
   33159   int rc = SQLITE_OK;
   33160   UINT nLargest = 0;
   33161   HANDLE hHeap;
   33162 
   33163   winMemAssertMagic();
   33164   hHeap = winMemGetHeap();
   33165   assert( hHeap!=0 );
   33166   assert( hHeap!=INVALID_HANDLE_VALUE );
   33167 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
   33168   assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
   33169 #endif
   33170 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
   33171   if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
   33172     DWORD lastErrno = osGetLastError();
   33173     if( lastErrno==NO_ERROR ){
   33174       sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
   33175                   (void*)hHeap);
   33176       rc = SQLITE_NOMEM;
   33177     }else{
   33178       sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
   33179                   osGetLastError(), (void*)hHeap);
   33180       rc = SQLITE_ERROR;
   33181     }
   33182   }
   33183 #else
   33184   sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
   33185               (void*)hHeap);
   33186   rc = SQLITE_NOTFOUND;
   33187 #endif
   33188   if( pnLargest ) *pnLargest = nLargest;
   33189   return rc;
   33190 }
   33191 
   33192 /*
   33193 ** If a Win32 native heap has been configured, this function will attempt to
   33194 ** destroy and recreate it.  If the Win32 native heap is not isolated and/or
   33195 ** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
   33196 ** be returned and no changes will be made to the Win32 native heap.
   33197 */
   33198 SQLITE_API int sqlite3_win32_reset_heap(){
   33199   int rc;
   33200   MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
   33201   MUTEX_LOGIC( sqlite3_mutex *pMem; )    /* The memsys static mutex */
   33202   MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
   33203   MUTEX_LOGIC( pMem = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); )
   33204   sqlite3_mutex_enter(pMaster);
   33205   sqlite3_mutex_enter(pMem);
   33206   winMemAssertMagic();
   33207   if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
   33208     /*
   33209     ** At this point, there should be no outstanding memory allocations on
   33210     ** the heap.  Also, since both the master and memsys locks are currently
   33211     ** being held by us, no other function (i.e. from another thread) should
   33212     ** be able to even access the heap.  Attempt to destroy and recreate our
   33213     ** isolated Win32 native heap now.
   33214     */
   33215     assert( winMemGetHeap()!=NULL );
   33216     assert( winMemGetOwned() );
   33217     assert( sqlite3_memory_used()==0 );
   33218     winMemShutdown(winMemGetDataPtr());
   33219     assert( winMemGetHeap()==NULL );
   33220     assert( !winMemGetOwned() );
   33221     assert( sqlite3_memory_used()==0 );
   33222     rc = winMemInit(winMemGetDataPtr());
   33223     assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
   33224     assert( rc!=SQLITE_OK || winMemGetOwned() );
   33225     assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
   33226   }else{
   33227     /*
   33228     ** The Win32 native heap cannot be modified because it may be in use.
   33229     */
   33230     rc = SQLITE_BUSY;
   33231   }
   33232   sqlite3_mutex_leave(pMem);
   33233   sqlite3_mutex_leave(pMaster);
   33234   return rc;
   33235 }
   33236 #endif /* SQLITE_WIN32_MALLOC */
   33237 
   33238 /*
   33239 ** This function outputs the specified (ANSI) string to the Win32 debugger
   33240 ** (if available).
   33241 */
   33242 
   33243 SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
   33244   char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
   33245   int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
   33246   if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
   33247   assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
   33248 #if defined(SQLITE_WIN32_HAS_ANSI)
   33249   if( nMin>0 ){
   33250     memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
   33251     memcpy(zDbgBuf, zBuf, nMin);
   33252     osOutputDebugStringA(zDbgBuf);
   33253   }else{
   33254     osOutputDebugStringA(zBuf);
   33255   }
   33256 #elif defined(SQLITE_WIN32_HAS_WIDE)
   33257   memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
   33258   if ( osMultiByteToWideChar(
   33259           osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
   33260           nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
   33261     return;
   33262   }
   33263   osOutputDebugStringW((LPCWSTR)zDbgBuf);
   33264 #else
   33265   if( nMin>0 ){
   33266     memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
   33267     memcpy(zDbgBuf, zBuf, nMin);
   33268     fprintf(stderr, "%s", zDbgBuf);
   33269   }else{
   33270     fprintf(stderr, "%s", zBuf);
   33271   }
   33272 #endif
   33273 }
   33274 
   33275 /*
   33276 ** The following routine suspends the current thread for at least ms
   33277 ** milliseconds.  This is equivalent to the Win32 Sleep() interface.
   33278 */
   33279 #if SQLITE_OS_WINRT
   33280 static HANDLE sleepObj = NULL;
   33281 #endif
   33282 
   33283 SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
   33284 #if SQLITE_OS_WINRT
   33285   if ( sleepObj==NULL ){
   33286     sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
   33287                                 SYNCHRONIZE);
   33288   }
   33289   assert( sleepObj!=NULL );
   33290   osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
   33291 #else
   33292   osSleep(milliseconds);
   33293 #endif
   33294 }
   33295 
   33296 /*
   33297 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
   33298 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
   33299 **
   33300 ** Here is an interesting observation:  Win95, Win98, and WinME lack
   33301 ** the LockFileEx() API.  But we can still statically link against that
   33302 ** API as long as we don't call it when running Win95/98/ME.  A call to
   33303 ** this routine is used to determine if the host is Win95/98/ME or
   33304 ** WinNT/2K/XP so that we will know whether or not we can safely call
   33305 ** the LockFileEx() API.
   33306 */
   33307 
   33308 #if !defined(SQLITE_WIN32_GETVERSIONEX) || !SQLITE_WIN32_GETVERSIONEX
   33309 # define osIsNT()  (1)
   33310 #elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
   33311 # define osIsNT()  (1)
   33312 #elif !defined(SQLITE_WIN32_HAS_WIDE)
   33313 # define osIsNT()  (0)
   33314 #else
   33315 # define osIsNT()  ((sqlite3_os_type==2) || sqlite3_win32_is_nt())
   33316 #endif
   33317 
   33318 /*
   33319 ** This function determines if the machine is running a version of Windows
   33320 ** based on the NT kernel.
   33321 */
   33322 SQLITE_API int sqlite3_win32_is_nt(void){
   33323 #if defined(SQLITE_WIN32_GETVERSIONEX) && SQLITE_WIN32_GETVERSIONEX
   33324   if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){
   33325 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
   33326         defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WIN8
   33327     OSVERSIONINFOW sInfo;
   33328     sInfo.dwOSVersionInfoSize = sizeof(sInfo);
   33329     osGetVersionExW(&sInfo);
   33330     osInterlockedCompareExchange(&sqlite3_os_type,
   33331         (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
   33332 #elif defined(SQLITE_WIN32_HAS_ANSI)
   33333     OSVERSIONINFOA sInfo;
   33334     sInfo.dwOSVersionInfoSize = sizeof(sInfo);
   33335     osGetVersionExA(&sInfo);
   33336     osInterlockedCompareExchange(&sqlite3_os_type,
   33337         (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
   33338 #endif
   33339   }
   33340   return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
   33341 #elif SQLITE_TEST
   33342   return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
   33343 #else
   33344   return 1;
   33345 #endif
   33346 }
   33347 
   33348 #ifdef SQLITE_WIN32_MALLOC
   33349 /*
   33350 ** Allocate nBytes of memory.
   33351 */
   33352 static void *winMemMalloc(int nBytes){
   33353   HANDLE hHeap;
   33354   void *p;
   33355 
   33356   winMemAssertMagic();
   33357   hHeap = winMemGetHeap();
   33358   assert( hHeap!=0 );
   33359   assert( hHeap!=INVALID_HANDLE_VALUE );
   33360 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
   33361   assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
   33362 #endif
   33363   assert( nBytes>=0 );
   33364   p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
   33365   if( !p ){
   33366     sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
   33367                 nBytes, osGetLastError(), (void*)hHeap);
   33368   }
   33369   return p;
   33370 }
   33371 
   33372 /*
   33373 ** Free memory.
   33374 */
   33375 static void winMemFree(void *pPrior){
   33376   HANDLE hHeap;
   33377 
   33378   winMemAssertMagic();
   33379   hHeap = winMemGetHeap();
   33380   assert( hHeap!=0 );
   33381   assert( hHeap!=INVALID_HANDLE_VALUE );
   33382 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
   33383   assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
   33384 #endif
   33385   if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
   33386   if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
   33387     sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
   33388                 pPrior, osGetLastError(), (void*)hHeap);
   33389   }
   33390 }
   33391 
   33392 /*
   33393 ** Change the size of an existing memory allocation
   33394 */
   33395 static void *winMemRealloc(void *pPrior, int nBytes){
   33396   HANDLE hHeap;
   33397   void *p;
   33398 
   33399   winMemAssertMagic();
   33400   hHeap = winMemGetHeap();
   33401   assert( hHeap!=0 );
   33402   assert( hHeap!=INVALID_HANDLE_VALUE );
   33403 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
   33404   assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
   33405 #endif
   33406   assert( nBytes>=0 );
   33407   if( !pPrior ){
   33408     p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
   33409   }else{
   33410     p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
   33411   }
   33412   if( !p ){
   33413     sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
   33414                 pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
   33415                 (void*)hHeap);
   33416   }
   33417   return p;
   33418 }
   33419 
   33420 /*
   33421 ** Return the size of an outstanding allocation, in bytes.
   33422 */
   33423 static int winMemSize(void *p){
   33424   HANDLE hHeap;
   33425   SIZE_T n;
   33426 
   33427   winMemAssertMagic();
   33428   hHeap = winMemGetHeap();
   33429   assert( hHeap!=0 );
   33430   assert( hHeap!=INVALID_HANDLE_VALUE );
   33431 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
   33432   assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
   33433 #endif
   33434   if( !p ) return 0;
   33435   n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
   33436   if( n==(SIZE_T)-1 ){
   33437     sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
   33438                 p, osGetLastError(), (void*)hHeap);
   33439     return 0;
   33440   }
   33441   return (int)n;
   33442 }
   33443 
   33444 /*
   33445 ** Round up a request size to the next valid allocation size.
   33446 */
   33447 static int winMemRoundup(int n){
   33448   return n;
   33449 }
   33450 
   33451 /*
   33452 ** Initialize this module.
   33453 */
   33454 static int winMemInit(void *pAppData){
   33455   winMemData *pWinMemData = (winMemData *)pAppData;
   33456 
   33457   if( !pWinMemData ) return SQLITE_ERROR;
   33458   assert( pWinMemData->magic1==WINMEM_MAGIC1 );
   33459   assert( pWinMemData->magic2==WINMEM_MAGIC2 );
   33460 
   33461 #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
   33462   if( !pWinMemData->hHeap ){
   33463     DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
   33464     DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
   33465     if( dwMaximumSize==0 ){
   33466       dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
   33467     }else if( dwInitialSize>dwMaximumSize ){
   33468       dwInitialSize = dwMaximumSize;
   33469     }
   33470     pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
   33471                                       dwInitialSize, dwMaximumSize);
   33472     if( !pWinMemData->hHeap ){
   33473       sqlite3_log(SQLITE_NOMEM,
   33474           "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
   33475           osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
   33476           dwMaximumSize);
   33477       return SQLITE_NOMEM;
   33478     }
   33479     pWinMemData->bOwned = TRUE;
   33480     assert( pWinMemData->bOwned );
   33481   }
   33482 #else
   33483   pWinMemData->hHeap = osGetProcessHeap();
   33484   if( !pWinMemData->hHeap ){
   33485     sqlite3_log(SQLITE_NOMEM,
   33486         "failed to GetProcessHeap (%lu)", osGetLastError());
   33487     return SQLITE_NOMEM;
   33488   }
   33489   pWinMemData->bOwned = FALSE;
   33490   assert( !pWinMemData->bOwned );
   33491 #endif
   33492   assert( pWinMemData->hHeap!=0 );
   33493   assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
   33494 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
   33495   assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
   33496 #endif
   33497   return SQLITE_OK;
   33498 }
   33499 
   33500 /*
   33501 ** Deinitialize this module.
   33502 */
   33503 static void winMemShutdown(void *pAppData){
   33504   winMemData *pWinMemData = (winMemData *)pAppData;
   33505 
   33506   if( !pWinMemData ) return;
   33507   assert( pWinMemData->magic1==WINMEM_MAGIC1 );
   33508   assert( pWinMemData->magic2==WINMEM_MAGIC2 );
   33509 
   33510   if( pWinMemData->hHeap ){
   33511     assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
   33512 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
   33513     assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
   33514 #endif
   33515     if( pWinMemData->bOwned ){
   33516       if( !osHeapDestroy(pWinMemData->hHeap) ){
   33517         sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
   33518                     osGetLastError(), (void*)pWinMemData->hHeap);
   33519       }
   33520       pWinMemData->bOwned = FALSE;
   33521     }
   33522     pWinMemData->hHeap = NULL;
   33523   }
   33524 }
   33525 
   33526 /*
   33527 ** Populate the low-level memory allocation function pointers in
   33528 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
   33529 ** arguments specify the block of memory to manage.
   33530 **
   33531 ** This routine is only called by sqlite3_config(), and therefore
   33532 ** is not required to be threadsafe (it is not).
   33533 */
   33534 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
   33535   static const sqlite3_mem_methods winMemMethods = {
   33536     winMemMalloc,
   33537     winMemFree,
   33538     winMemRealloc,
   33539     winMemSize,
   33540     winMemRoundup,
   33541     winMemInit,
   33542     winMemShutdown,
   33543     &win_mem_data
   33544   };
   33545   return &winMemMethods;
   33546 }
   33547 
   33548 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
   33549   sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
   33550 }
   33551 #endif /* SQLITE_WIN32_MALLOC */
   33552 
   33553 /*
   33554 ** Convert a UTF-8 string to Microsoft Unicode (UTF-16?).
   33555 **
   33556 ** Space to hold the returned string is obtained from malloc.
   33557 */
   33558 static LPWSTR winUtf8ToUnicode(const char *zFilename){
   33559   int nChar;
   33560   LPWSTR zWideFilename;
   33561 
   33562   nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
   33563   if( nChar==0 ){
   33564     return 0;
   33565   }
   33566   zWideFilename = sqlite3MallocZero( nChar*sizeof(zWideFilename[0]) );
   33567   if( zWideFilename==0 ){
   33568     return 0;
   33569   }
   33570   nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
   33571                                 nChar);
   33572   if( nChar==0 ){
   33573     sqlite3_free(zWideFilename);
   33574     zWideFilename = 0;
   33575   }
   33576   return zWideFilename;
   33577 }
   33578 
   33579 /*
   33580 ** Convert Microsoft Unicode to UTF-8.  Space to hold the returned string is
   33581 ** obtained from sqlite3_malloc().
   33582 */
   33583 static char *winUnicodeToUtf8(LPCWSTR zWideFilename){
   33584   int nByte;
   33585   char *zFilename;
   33586 
   33587   nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
   33588   if( nByte == 0 ){
   33589     return 0;
   33590   }
   33591   zFilename = sqlite3MallocZero( nByte );
   33592   if( zFilename==0 ){
   33593     return 0;
   33594   }
   33595   nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
   33596                                 0, 0);
   33597   if( nByte == 0 ){
   33598     sqlite3_free(zFilename);
   33599     zFilename = 0;
   33600   }
   33601   return zFilename;
   33602 }
   33603 
   33604 /*
   33605 ** Convert an ANSI string to Microsoft Unicode, based on the
   33606 ** current codepage settings for file apis.
   33607 **
   33608 ** Space to hold the returned string is obtained
   33609 ** from sqlite3_malloc.
   33610 */
   33611 static LPWSTR winMbcsToUnicode(const char *zFilename){
   33612   int nByte;
   33613   LPWSTR zMbcsFilename;
   33614   int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
   33615 
   33616   nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,
   33617                                 0)*sizeof(WCHAR);
   33618   if( nByte==0 ){
   33619     return 0;
   33620   }
   33621   zMbcsFilename = sqlite3MallocZero( nByte*sizeof(zMbcsFilename[0]) );
   33622   if( zMbcsFilename==0 ){
   33623     return 0;
   33624   }
   33625   nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,
   33626                                 nByte);
   33627   if( nByte==0 ){
   33628     sqlite3_free(zMbcsFilename);
   33629     zMbcsFilename = 0;
   33630   }
   33631   return zMbcsFilename;
   33632 }
   33633 
   33634 /*
   33635 ** Convert Microsoft Unicode to multi-byte character string, based on the
   33636 ** user's ANSI codepage.
   33637 **
   33638 ** Space to hold the returned string is obtained from
   33639 ** sqlite3_malloc().
   33640 */
   33641 static char *winUnicodeToMbcs(LPCWSTR zWideFilename){
   33642   int nByte;
   33643   char *zFilename;
   33644   int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
   33645 
   33646   nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
   33647   if( nByte == 0 ){
   33648     return 0;
   33649   }
   33650   zFilename = sqlite3MallocZero( nByte );
   33651   if( zFilename==0 ){
   33652     return 0;
   33653   }
   33654   nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,
   33655                                 nByte, 0, 0);
   33656   if( nByte == 0 ){
   33657     sqlite3_free(zFilename);
   33658     zFilename = 0;
   33659   }
   33660   return zFilename;
   33661 }
   33662 
   33663 /*
   33664 ** Convert multibyte character string to UTF-8.  Space to hold the
   33665 ** returned string is obtained from sqlite3_malloc().
   33666 */
   33667 SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
   33668   char *zFilenameUtf8;
   33669   LPWSTR zTmpWide;
   33670 
   33671   zTmpWide = winMbcsToUnicode(zFilename);
   33672   if( zTmpWide==0 ){
   33673     return 0;
   33674   }
   33675   zFilenameUtf8 = winUnicodeToUtf8(zTmpWide);
   33676   sqlite3_free(zTmpWide);
   33677   return zFilenameUtf8;
   33678 }
   33679 
   33680 /*
   33681 ** Convert UTF-8 to multibyte character string.  Space to hold the
   33682 ** returned string is obtained from sqlite3_malloc().
   33683 */
   33684 SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zFilename){
   33685   char *zFilenameMbcs;
   33686   LPWSTR zTmpWide;
   33687 
   33688   zTmpWide = winUtf8ToUnicode(zFilename);
   33689   if( zTmpWide==0 ){
   33690     return 0;
   33691   }
   33692   zFilenameMbcs = winUnicodeToMbcs(zTmpWide);
   33693   sqlite3_free(zTmpWide);
   33694   return zFilenameMbcs;
   33695 }
   33696 
   33697 /*
   33698 ** This function sets the data directory or the temporary directory based on
   33699 ** the provided arguments.  The type argument must be 1 in order to set the
   33700 ** data directory or 2 in order to set the temporary directory.  The zValue
   33701 ** argument is the name of the directory to use.  The return value will be
   33702 ** SQLITE_OK if successful.
   33703 */
   33704 SQLITE_API int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
   33705   char **ppDirectory = 0;
   33706 #ifndef SQLITE_OMIT_AUTOINIT
   33707   int rc = sqlite3_initialize();
   33708   if( rc ) return rc;
   33709 #endif
   33710   if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
   33711     ppDirectory = &sqlite3_data_directory;
   33712   }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
   33713     ppDirectory = &sqlite3_temp_directory;
   33714   }
   33715   assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
   33716           || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
   33717   );
   33718   assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
   33719   if( ppDirectory ){
   33720     char *zValueUtf8 = 0;
   33721     if( zValue && zValue[0] ){
   33722       zValueUtf8 = winUnicodeToUtf8(zValue);
   33723       if ( zValueUtf8==0 ){
   33724         return SQLITE_NOMEM;
   33725       }
   33726     }
   33727     sqlite3_free(*ppDirectory);
   33728     *ppDirectory = zValueUtf8;
   33729     return SQLITE_OK;
   33730   }
   33731   return SQLITE_ERROR;
   33732 }
   33733 
   33734 /*
   33735 ** The return value of winGetLastErrorMsg
   33736 ** is zero if the error message fits in the buffer, or non-zero
   33737 ** otherwise (if the message was truncated).
   33738 */
   33739 static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
   33740   /* FormatMessage returns 0 on failure.  Otherwise it
   33741   ** returns the number of TCHARs written to the output
   33742   ** buffer, excluding the terminating null char.
   33743   */
   33744   DWORD dwLen = 0;
   33745   char *zOut = 0;
   33746 
   33747   if( osIsNT() ){
   33748 #if SQLITE_OS_WINRT
   33749     WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
   33750     dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
   33751                              FORMAT_MESSAGE_IGNORE_INSERTS,
   33752                              NULL,
   33753                              lastErrno,
   33754                              0,
   33755                              zTempWide,
   33756                              SQLITE_WIN32_MAX_ERRMSG_CHARS,
   33757                              0);
   33758 #else
   33759     LPWSTR zTempWide = NULL;
   33760     dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
   33761                              FORMAT_MESSAGE_FROM_SYSTEM |
   33762                              FORMAT_MESSAGE_IGNORE_INSERTS,
   33763                              NULL,
   33764                              lastErrno,
   33765                              0,
   33766                              (LPWSTR) &zTempWide,
   33767                              0,
   33768                              0);
   33769 #endif
   33770     if( dwLen > 0 ){
   33771       /* allocate a buffer and convert to UTF8 */
   33772       sqlite3BeginBenignMalloc();
   33773       zOut = winUnicodeToUtf8(zTempWide);
   33774       sqlite3EndBenignMalloc();
   33775 #if !SQLITE_OS_WINRT
   33776       /* free the system buffer allocated by FormatMessage */
   33777       osLocalFree(zTempWide);
   33778 #endif
   33779     }
   33780   }
   33781 #ifdef SQLITE_WIN32_HAS_ANSI
   33782   else{
   33783     char *zTemp = NULL;
   33784     dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
   33785                              FORMAT_MESSAGE_FROM_SYSTEM |
   33786                              FORMAT_MESSAGE_IGNORE_INSERTS,
   33787                              NULL,
   33788                              lastErrno,
   33789                              0,
   33790                              (LPSTR) &zTemp,
   33791                              0,
   33792                              0);
   33793     if( dwLen > 0 ){
   33794       /* allocate a buffer and convert to UTF8 */
   33795       sqlite3BeginBenignMalloc();
   33796       zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
   33797       sqlite3EndBenignMalloc();
   33798       /* free the system buffer allocated by FormatMessage */
   33799       osLocalFree(zTemp);
   33800     }
   33801   }
   33802 #endif
   33803   if( 0 == dwLen ){
   33804     sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
   33805   }else{
   33806     /* copy a maximum of nBuf chars to output buffer */
   33807     sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
   33808     /* free the UTF8 buffer */
   33809     sqlite3_free(zOut);
   33810   }
   33811   return 0;
   33812 }
   33813 
   33814 /*
   33815 **
   33816 ** This function - winLogErrorAtLine() - is only ever called via the macro
   33817 ** winLogError().
   33818 **
   33819 ** This routine is invoked after an error occurs in an OS function.
   33820 ** It logs a message using sqlite3_log() containing the current value of
   33821 ** error code and, if possible, the human-readable equivalent from
   33822 ** FormatMessage.
   33823 **
   33824 ** The first argument passed to the macro should be the error code that
   33825 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
   33826 ** The two subsequent arguments should be the name of the OS function that
   33827 ** failed and the associated file-system path, if any.
   33828 */
   33829 #define winLogError(a,b,c,d)   winLogErrorAtLine(a,b,c,d,__LINE__)
   33830 static int winLogErrorAtLine(
   33831   int errcode,                    /* SQLite error code */
   33832   DWORD lastErrno,                /* Win32 last error */
   33833   const char *zFunc,              /* Name of OS function that failed */
   33834   const char *zPath,              /* File path associated with error */
   33835   int iLine                       /* Source line number where error occurred */
   33836 ){
   33837   char zMsg[500];                 /* Human readable error text */
   33838   int i;                          /* Loop counter */
   33839 
   33840   zMsg[0] = 0;
   33841   winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
   33842   assert( errcode!=SQLITE_OK );
   33843   if( zPath==0 ) zPath = "";
   33844   for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
   33845   zMsg[i] = 0;
   33846   sqlite3_log(errcode,
   33847       "os_win.c:%d: (%lu) %s(%s) - %s",
   33848       iLine, lastErrno, zFunc, zPath, zMsg
   33849   );
   33850 
   33851   return errcode;
   33852 }
   33853 
   33854 /*
   33855 ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
   33856 ** will be retried following a locking error - probably caused by
   33857 ** antivirus software.  Also the initial delay before the first retry.
   33858 ** The delay increases linearly with each retry.
   33859 */
   33860 #ifndef SQLITE_WIN32_IOERR_RETRY
   33861 # define SQLITE_WIN32_IOERR_RETRY 10
   33862 #endif
   33863 #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
   33864 # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
   33865 #endif
   33866 static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
   33867 static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
   33868 
   33869 /*
   33870 ** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
   33871 ** error code obtained via GetLastError() is eligible to be retried.  It
   33872 ** must accept the error code DWORD as its only argument and should return
   33873 ** non-zero if the error code is transient in nature and the operation
   33874 ** responsible for generating the original error might succeed upon being
   33875 ** retried.  The argument to this macro should be a variable.
   33876 **
   33877 ** Additionally, a macro named "winIoerrCanRetry2" may be defined.  If it
   33878 ** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
   33879 ** returns zero.  The "winIoerrCanRetry2" macro is completely optional and
   33880 ** may be used to include additional error codes in the set that should
   33881 ** result in the failing I/O operation being retried by the caller.  If
   33882 ** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
   33883 ** identical to those of the "winIoerrCanRetry1" macro.
   33884 */
   33885 #if !defined(winIoerrCanRetry1)
   33886 #define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED)        || \
   33887                               ((a)==ERROR_SHARING_VIOLATION)    || \
   33888                               ((a)==ERROR_LOCK_VIOLATION)       || \
   33889                               ((a)==ERROR_DEV_NOT_EXIST)        || \
   33890                               ((a)==ERROR_NETNAME_DELETED)      || \
   33891                               ((a)==ERROR_SEM_TIMEOUT)          || \
   33892                               ((a)==ERROR_NETWORK_UNREACHABLE))
   33893 #endif
   33894 
   33895 /*
   33896 ** If a ReadFile() or WriteFile() error occurs, invoke this routine
   33897 ** to see if it should be retried.  Return TRUE to retry.  Return FALSE
   33898 ** to give up with an error.
   33899 */
   33900 static int winRetryIoerr(int *pnRetry, DWORD *pError){
   33901   DWORD e = osGetLastError();
   33902   if( *pnRetry>=winIoerrRetry ){
   33903     if( pError ){
   33904       *pError = e;
   33905     }
   33906     return 0;
   33907   }
   33908   if( winIoerrCanRetry1(e) ){
   33909     sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
   33910     ++*pnRetry;
   33911     return 1;
   33912   }
   33913 #if defined(winIoerrCanRetry2)
   33914   else if( winIoerrCanRetry2(e) ){
   33915     sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
   33916     ++*pnRetry;
   33917     return 1;
   33918   }
   33919 #endif
   33920   if( pError ){
   33921     *pError = e;
   33922   }
   33923   return 0;
   33924 }
   33925 
   33926 /*
   33927 ** Log a I/O error retry episode.
   33928 */
   33929 static void winLogIoerr(int nRetry){
   33930   if( nRetry ){
   33931     sqlite3_log(SQLITE_IOERR,
   33932       "delayed %dms for lock/sharing conflict",
   33933       winIoerrRetryDelay*nRetry*(nRetry+1)/2
   33934     );
   33935   }
   33936 }
   33937 
   33938 #if SQLITE_OS_WINCE
   33939 /*************************************************************************
   33940 ** This section contains code for WinCE only.
   33941 */
   33942 #if !defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API
   33943 /*
   33944 ** The MSVC CRT on Windows CE may not have a localtime() function.  So
   33945 ** create a substitute.
   33946 */
   33947 /* #include <time.h> */
   33948 struct tm *__cdecl localtime(const time_t *t)
   33949 {
   33950   static struct tm y;
   33951   FILETIME uTm, lTm;
   33952   SYSTEMTIME pTm;
   33953   sqlite3_int64 t64;
   33954   t64 = *t;
   33955   t64 = (t64 + 11644473600)*10000000;
   33956   uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
   33957   uTm.dwHighDateTime= (DWORD)(t64 >> 32);
   33958   osFileTimeToLocalFileTime(&uTm,&lTm);
   33959   osFileTimeToSystemTime(&lTm,&pTm);
   33960   y.tm_year = pTm.wYear - 1900;
   33961   y.tm_mon = pTm.wMonth - 1;
   33962   y.tm_wday = pTm.wDayOfWeek;
   33963   y.tm_mday = pTm.wDay;
   33964   y.tm_hour = pTm.wHour;
   33965   y.tm_min = pTm.wMinute;
   33966   y.tm_sec = pTm.wSecond;
   33967   return &y;
   33968 }
   33969 #endif
   33970 
   33971 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
   33972 
   33973 /*
   33974 ** Acquire a lock on the handle h
   33975 */
   33976 static void winceMutexAcquire(HANDLE h){
   33977    DWORD dwErr;
   33978    do {
   33979      dwErr = osWaitForSingleObject(h, INFINITE);
   33980    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
   33981 }
   33982 /*
   33983 ** Release a lock acquired by winceMutexAcquire()
   33984 */
   33985 #define winceMutexRelease(h) ReleaseMutex(h)
   33986 
   33987 /*
   33988 ** Create the mutex and shared memory used for locking in the file
   33989 ** descriptor pFile
   33990 */
   33991 static int winceCreateLock(const char *zFilename, winFile *pFile){
   33992   LPWSTR zTok;
   33993   LPWSTR zName;
   33994   DWORD lastErrno;
   33995   BOOL bLogged = FALSE;
   33996   BOOL bInit = TRUE;
   33997 
   33998   zName = winUtf8ToUnicode(zFilename);
   33999   if( zName==0 ){
   34000     /* out of memory */
   34001     return SQLITE_IOERR_NOMEM;
   34002   }
   34003 
   34004   /* Initialize the local lockdata */
   34005   memset(&pFile->local, 0, sizeof(pFile->local));
   34006 
   34007   /* Replace the backslashes from the filename and lowercase it
   34008   ** to derive a mutex name. */
   34009   zTok = osCharLowerW(zName);
   34010   for (;*zTok;zTok++){
   34011     if (*zTok == '\\') *zTok = '_';
   34012   }
   34013 
   34014   /* Create/open the named mutex */
   34015   pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
   34016   if (!pFile->hMutex){
   34017     pFile->lastErrno = osGetLastError();
   34018     sqlite3_free(zName);
   34019     return winLogError(SQLITE_IOERR, pFile->lastErrno,
   34020                        "winceCreateLock1", zFilename);
   34021   }
   34022 
   34023   /* Acquire the mutex before continuing */
   34024   winceMutexAcquire(pFile->hMutex);
   34025 
   34026   /* Since the names of named mutexes, semaphores, file mappings etc are
   34027   ** case-sensitive, take advantage of that by uppercasing the mutex name
   34028   ** and using that as the shared filemapping name.
   34029   */
   34030   osCharUpperW(zName);
   34031   pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
   34032                                         PAGE_READWRITE, 0, sizeof(winceLock),
   34033                                         zName);
   34034 
   34035   /* Set a flag that indicates we're the first to create the memory so it
   34036   ** must be zero-initialized */
   34037   lastErrno = osGetLastError();
   34038   if (lastErrno == ERROR_ALREADY_EXISTS){
   34039     bInit = FALSE;
   34040   }
   34041 
   34042   sqlite3_free(zName);
   34043 
   34044   /* If we succeeded in making the shared memory handle, map it. */
   34045   if( pFile->hShared ){
   34046     pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
   34047              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
   34048     /* If mapping failed, close the shared memory handle and erase it */
   34049     if( !pFile->shared ){
   34050       pFile->lastErrno = osGetLastError();
   34051       winLogError(SQLITE_IOERR, pFile->lastErrno,
   34052                   "winceCreateLock2", zFilename);
   34053       bLogged = TRUE;
   34054       osCloseHandle(pFile->hShared);
   34055       pFile->hShared = NULL;
   34056     }
   34057   }
   34058 
   34059   /* If shared memory could not be created, then close the mutex and fail */
   34060   if( pFile->hShared==NULL ){
   34061     if( !bLogged ){
   34062       pFile->lastErrno = lastErrno;
   34063       winLogError(SQLITE_IOERR, pFile->lastErrno,
   34064                   "winceCreateLock3", zFilename);
   34065       bLogged = TRUE;
   34066     }
   34067     winceMutexRelease(pFile->hMutex);
   34068     osCloseHandle(pFile->hMutex);
   34069     pFile->hMutex = NULL;
   34070     return SQLITE_IOERR;
   34071   }
   34072 
   34073   /* Initialize the shared memory if we're supposed to */
   34074   if( bInit ){
   34075     memset(pFile->shared, 0, sizeof(winceLock));
   34076   }
   34077 
   34078   winceMutexRelease(pFile->hMutex);
   34079   return SQLITE_OK;
   34080 }
   34081 
   34082 /*
   34083 ** Destroy the part of winFile that deals with wince locks
   34084 */
   34085 static void winceDestroyLock(winFile *pFile){
   34086   if (pFile->hMutex){
   34087     /* Acquire the mutex */
   34088     winceMutexAcquire(pFile->hMutex);
   34089 
   34090     /* The following blocks should probably assert in debug mode, but they
   34091        are to cleanup in case any locks remained open */
   34092     if (pFile->local.nReaders){
   34093       pFile->shared->nReaders --;
   34094     }
   34095     if (pFile->local.bReserved){
   34096       pFile->shared->bReserved = FALSE;
   34097     }
   34098     if (pFile->local.bPending){
   34099       pFile->shared->bPending = FALSE;
   34100     }
   34101     if (pFile->local.bExclusive){
   34102       pFile->shared->bExclusive = FALSE;
   34103     }
   34104 
   34105     /* De-reference and close our copy of the shared memory handle */
   34106     osUnmapViewOfFile(pFile->shared);
   34107     osCloseHandle(pFile->hShared);
   34108 
   34109     /* Done with the mutex */
   34110     winceMutexRelease(pFile->hMutex);
   34111     osCloseHandle(pFile->hMutex);
   34112     pFile->hMutex = NULL;
   34113   }
   34114 }
   34115 
   34116 /*
   34117 ** An implementation of the LockFile() API of Windows for CE
   34118 */
   34119 static BOOL winceLockFile(
   34120   LPHANDLE phFile,
   34121   DWORD dwFileOffsetLow,
   34122   DWORD dwFileOffsetHigh,
   34123   DWORD nNumberOfBytesToLockLow,
   34124   DWORD nNumberOfBytesToLockHigh
   34125 ){
   34126   winFile *pFile = HANDLE_TO_WINFILE(phFile);
   34127   BOOL bReturn = FALSE;
   34128 
   34129   UNUSED_PARAMETER(dwFileOffsetHigh);
   34130   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
   34131 
   34132   if (!pFile->hMutex) return TRUE;
   34133   winceMutexAcquire(pFile->hMutex);
   34134 
   34135   /* Wanting an exclusive lock? */
   34136   if (dwFileOffsetLow == (DWORD)SHARED_FIRST
   34137        && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
   34138     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
   34139        pFile->shared->bExclusive = TRUE;
   34140        pFile->local.bExclusive = TRUE;
   34141        bReturn = TRUE;
   34142     }
   34143   }
   34144 
   34145   /* Want a read-only lock? */
   34146   else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
   34147            nNumberOfBytesToLockLow == 1){
   34148     if (pFile->shared->bExclusive == 0){
   34149       pFile->local.nReaders ++;
   34150       if (pFile->local.nReaders == 1){
   34151         pFile->shared->nReaders ++;
   34152       }
   34153       bReturn = TRUE;
   34154     }
   34155   }
   34156 
   34157   /* Want a pending lock? */
   34158   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
   34159            && nNumberOfBytesToLockLow == 1){
   34160     /* If no pending lock has been acquired, then acquire it */
   34161     if (pFile->shared->bPending == 0) {
   34162       pFile->shared->bPending = TRUE;
   34163       pFile->local.bPending = TRUE;
   34164       bReturn = TRUE;
   34165     }
   34166   }
   34167 
   34168   /* Want a reserved lock? */
   34169   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
   34170            && nNumberOfBytesToLockLow == 1){
   34171     if (pFile->shared->bReserved == 0) {
   34172       pFile->shared->bReserved = TRUE;
   34173       pFile->local.bReserved = TRUE;
   34174       bReturn = TRUE;
   34175     }
   34176   }
   34177 
   34178   winceMutexRelease(pFile->hMutex);
   34179   return bReturn;
   34180 }
   34181 
   34182 /*
   34183 ** An implementation of the UnlockFile API of Windows for CE
   34184 */
   34185 static BOOL winceUnlockFile(
   34186   LPHANDLE phFile,
   34187   DWORD dwFileOffsetLow,
   34188   DWORD dwFileOffsetHigh,
   34189   DWORD nNumberOfBytesToUnlockLow,
   34190   DWORD nNumberOfBytesToUnlockHigh
   34191 ){
   34192   winFile *pFile = HANDLE_TO_WINFILE(phFile);
   34193   BOOL bReturn = FALSE;
   34194 
   34195   UNUSED_PARAMETER(dwFileOffsetHigh);
   34196   UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
   34197 
   34198   if (!pFile->hMutex) return TRUE;
   34199   winceMutexAcquire(pFile->hMutex);
   34200 
   34201   /* Releasing a reader lock or an exclusive lock */
   34202   if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
   34203     /* Did we have an exclusive lock? */
   34204     if (pFile->local.bExclusive){
   34205       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
   34206       pFile->local.bExclusive = FALSE;
   34207       pFile->shared->bExclusive = FALSE;
   34208       bReturn = TRUE;
   34209     }
   34210 
   34211     /* Did we just have a reader lock? */
   34212     else if (pFile->local.nReaders){
   34213       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
   34214              || nNumberOfBytesToUnlockLow == 1);
   34215       pFile->local.nReaders --;
   34216       if (pFile->local.nReaders == 0)
   34217       {
   34218         pFile->shared->nReaders --;
   34219       }
   34220       bReturn = TRUE;
   34221     }
   34222   }
   34223 
   34224   /* Releasing a pending lock */
   34225   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
   34226            && nNumberOfBytesToUnlockLow == 1){
   34227     if (pFile->local.bPending){
   34228       pFile->local.bPending = FALSE;
   34229       pFile->shared->bPending = FALSE;
   34230       bReturn = TRUE;
   34231     }
   34232   }
   34233   /* Releasing a reserved lock */
   34234   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
   34235            && nNumberOfBytesToUnlockLow == 1){
   34236     if (pFile->local.bReserved) {
   34237       pFile->local.bReserved = FALSE;
   34238       pFile->shared->bReserved = FALSE;
   34239       bReturn = TRUE;
   34240     }
   34241   }
   34242 
   34243   winceMutexRelease(pFile->hMutex);
   34244   return bReturn;
   34245 }
   34246 /*
   34247 ** End of the special code for wince
   34248 *****************************************************************************/
   34249 #endif /* SQLITE_OS_WINCE */
   34250 
   34251 /*
   34252 ** Lock a file region.
   34253 */
   34254 static BOOL winLockFile(
   34255   LPHANDLE phFile,
   34256   DWORD flags,
   34257   DWORD offsetLow,
   34258   DWORD offsetHigh,
   34259   DWORD numBytesLow,
   34260   DWORD numBytesHigh
   34261 ){
   34262 #if SQLITE_OS_WINCE
   34263   /*
   34264   ** NOTE: Windows CE is handled differently here due its lack of the Win32
   34265   **       API LockFile.
   34266   */
   34267   return winceLockFile(phFile, offsetLow, offsetHigh,
   34268                        numBytesLow, numBytesHigh);
   34269 #else
   34270   if( osIsNT() ){
   34271     OVERLAPPED ovlp;
   34272     memset(&ovlp, 0, sizeof(OVERLAPPED));
   34273     ovlp.Offset = offsetLow;
   34274     ovlp.OffsetHigh = offsetHigh;
   34275     return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
   34276   }else{
   34277     return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
   34278                       numBytesHigh);
   34279   }
   34280 #endif
   34281 }
   34282 
   34283 /*
   34284 ** Unlock a file region.
   34285  */
   34286 static BOOL winUnlockFile(
   34287   LPHANDLE phFile,
   34288   DWORD offsetLow,
   34289   DWORD offsetHigh,
   34290   DWORD numBytesLow,
   34291   DWORD numBytesHigh
   34292 ){
   34293 #if SQLITE_OS_WINCE
   34294   /*
   34295   ** NOTE: Windows CE is handled differently here due its lack of the Win32
   34296   **       API UnlockFile.
   34297   */
   34298   return winceUnlockFile(phFile, offsetLow, offsetHigh,
   34299                          numBytesLow, numBytesHigh);
   34300 #else
   34301   if( osIsNT() ){
   34302     OVERLAPPED ovlp;
   34303     memset(&ovlp, 0, sizeof(OVERLAPPED));
   34304     ovlp.Offset = offsetLow;
   34305     ovlp.OffsetHigh = offsetHigh;
   34306     return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
   34307   }else{
   34308     return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
   34309                         numBytesHigh);
   34310   }
   34311 #endif
   34312 }
   34313 
   34314 /*****************************************************************************
   34315 ** The next group of routines implement the I/O methods specified
   34316 ** by the sqlite3_io_methods object.
   34317 ******************************************************************************/
   34318 
   34319 /*
   34320 ** Some Microsoft compilers lack this definition.
   34321 */
   34322 #ifndef INVALID_SET_FILE_POINTER
   34323 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
   34324 #endif
   34325 
   34326 /*
   34327 ** Move the current position of the file handle passed as the first
   34328 ** argument to offset iOffset within the file. If successful, return 0.
   34329 ** Otherwise, set pFile->lastErrno and return non-zero.
   34330 */
   34331 static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
   34332 #if !SQLITE_OS_WINRT
   34333   LONG upperBits;                 /* Most sig. 32 bits of new offset */
   34334   LONG lowerBits;                 /* Least sig. 32 bits of new offset */
   34335   DWORD dwRet;                    /* Value returned by SetFilePointer() */
   34336   DWORD lastErrno;                /* Value returned by GetLastError() */
   34337 
   34338   OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
   34339 
   34340   upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
   34341   lowerBits = (LONG)(iOffset & 0xffffffff);
   34342 
   34343   /* API oddity: If successful, SetFilePointer() returns a dword
   34344   ** containing the lower 32-bits of the new file-offset. Or, if it fails,
   34345   ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
   34346   ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
   34347   ** whether an error has actually occurred, it is also necessary to call
   34348   ** GetLastError().
   34349   */
   34350   dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
   34351 
   34352   if( (dwRet==INVALID_SET_FILE_POINTER
   34353       && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
   34354     pFile->lastErrno = lastErrno;
   34355     winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
   34356                 "winSeekFile", pFile->zPath);
   34357     OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
   34358     return 1;
   34359   }
   34360 
   34361   OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
   34362   return 0;
   34363 #else
   34364   /*
   34365   ** Same as above, except that this implementation works for WinRT.
   34366   */
   34367 
   34368   LARGE_INTEGER x;                /* The new offset */
   34369   BOOL bRet;                      /* Value returned by SetFilePointerEx() */
   34370 
   34371   x.QuadPart = iOffset;
   34372   bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
   34373 
   34374   if(!bRet){
   34375     pFile->lastErrno = osGetLastError();
   34376     winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
   34377                 "winSeekFile", pFile->zPath);
   34378     OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
   34379     return 1;
   34380   }
   34381 
   34382   OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
   34383   return 0;
   34384 #endif
   34385 }
   34386 
   34387 #if SQLITE_MAX_MMAP_SIZE>0
   34388 /* Forward references to VFS helper methods used for memory mapped files */
   34389 static int winMapfile(winFile*, sqlite3_int64);
   34390 static int winUnmapfile(winFile*);
   34391 #endif
   34392 
   34393 /*
   34394 ** Close a file.
   34395 **
   34396 ** It is reported that an attempt to close a handle might sometimes
   34397 ** fail.  This is a very unreasonable result, but Windows is notorious
   34398 ** for being unreasonable so I do not doubt that it might happen.  If
   34399 ** the close fails, we pause for 100 milliseconds and try again.  As
   34400 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
   34401 ** giving up and returning an error.
   34402 */
   34403 #define MX_CLOSE_ATTEMPT 3
   34404 static int winClose(sqlite3_file *id){
   34405   int rc, cnt = 0;
   34406   winFile *pFile = (winFile*)id;
   34407 
   34408   assert( id!=0 );
   34409 #ifndef SQLITE_OMIT_WAL
   34410   assert( pFile->pShm==0 );
   34411 #endif
   34412   assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
   34413   OSTRACE(("CLOSE file=%p\n", pFile->h));
   34414 
   34415 #if SQLITE_MAX_MMAP_SIZE>0
   34416   winUnmapfile(pFile);
   34417 #endif
   34418 
   34419   do{
   34420     rc = osCloseHandle(pFile->h);
   34421     /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
   34422   }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
   34423 #if SQLITE_OS_WINCE
   34424 #define WINCE_DELETION_ATTEMPTS 3
   34425   winceDestroyLock(pFile);
   34426   if( pFile->zDeleteOnClose ){
   34427     int cnt = 0;
   34428     while(
   34429            osDeleteFileW(pFile->zDeleteOnClose)==0
   34430         && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
   34431         && cnt++ < WINCE_DELETION_ATTEMPTS
   34432     ){
   34433        sqlite3_win32_sleep(100);  /* Wait a little before trying again */
   34434     }
   34435     sqlite3_free(pFile->zDeleteOnClose);
   34436   }
   34437 #endif
   34438   if( rc ){
   34439     pFile->h = NULL;
   34440   }
   34441   OpenCounter(-1);
   34442   OSTRACE(("CLOSE file=%p, rc=%s\n", pFile->h, rc ? "ok" : "failed"));
   34443   return rc ? SQLITE_OK
   34444             : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
   34445                           "winClose", pFile->zPath);
   34446 }
   34447 
   34448 /*
   34449 ** Read data from a file into a buffer.  Return SQLITE_OK if all
   34450 ** bytes were read successfully and SQLITE_IOERR if anything goes
   34451 ** wrong.
   34452 */
   34453 static int winRead(
   34454   sqlite3_file *id,          /* File to read from */
   34455   void *pBuf,                /* Write content into this buffer */
   34456   int amt,                   /* Number of bytes to read */
   34457   sqlite3_int64 offset       /* Begin reading at this offset */
   34458 ){
   34459 #if !SQLITE_OS_WINCE
   34460   OVERLAPPED overlapped;          /* The offset for ReadFile. */
   34461 #endif
   34462   winFile *pFile = (winFile*)id;  /* file handle */
   34463   DWORD nRead;                    /* Number of bytes actually read from file */
   34464   int nRetry = 0;                 /* Number of retrys */
   34465 
   34466   assert( id!=0 );
   34467   assert( amt>0 );
   34468   assert( offset>=0 );
   34469   SimulateIOError(return SQLITE_IOERR_READ);
   34470   OSTRACE(("READ file=%p, buffer=%p, amount=%d, offset=%lld, lock=%d\n",
   34471            pFile->h, pBuf, amt, offset, pFile->locktype));
   34472 
   34473 #if SQLITE_MAX_MMAP_SIZE>0
   34474   /* Deal with as much of this read request as possible by transfering
   34475   ** data from the memory mapping using memcpy().  */
   34476   if( offset<pFile->mmapSize ){
   34477     if( offset+amt <= pFile->mmapSize ){
   34478       memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
   34479       OSTRACE(("READ-MMAP file=%p, rc=SQLITE_OK\n", pFile->h));
   34480       return SQLITE_OK;
   34481     }else{
   34482       int nCopy = (int)(pFile->mmapSize - offset);
   34483       memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
   34484       pBuf = &((u8 *)pBuf)[nCopy];
   34485       amt -= nCopy;
   34486       offset += nCopy;
   34487     }
   34488   }
   34489 #endif
   34490 
   34491 #if SQLITE_OS_WINCE
   34492   if( winSeekFile(pFile, offset) ){
   34493     OSTRACE(("READ file=%p, rc=SQLITE_FULL\n", pFile->h));
   34494     return SQLITE_FULL;
   34495   }
   34496   while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
   34497 #else
   34498   memset(&overlapped, 0, sizeof(OVERLAPPED));
   34499   overlapped.Offset = (LONG)(offset & 0xffffffff);
   34500   overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
   34501   while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
   34502          osGetLastError()!=ERROR_HANDLE_EOF ){
   34503 #endif
   34504     DWORD lastErrno;
   34505     if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
   34506     pFile->lastErrno = lastErrno;
   34507     OSTRACE(("READ file=%p, rc=SQLITE_IOERR_READ\n", pFile->h));
   34508     return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
   34509                        "winRead", pFile->zPath);
   34510   }
   34511   winLogIoerr(nRetry);
   34512   if( nRead<(DWORD)amt ){
   34513     /* Unread parts of the buffer must be zero-filled */
   34514     memset(&((char*)pBuf)[nRead], 0, amt-nRead);
   34515     OSTRACE(("READ file=%p, rc=SQLITE_IOERR_SHORT_READ\n", pFile->h));
   34516     return SQLITE_IOERR_SHORT_READ;
   34517   }
   34518 
   34519   OSTRACE(("READ file=%p, rc=SQLITE_OK\n", pFile->h));
   34520   return SQLITE_OK;
   34521 }
   34522 
   34523 /*
   34524 ** Write data from a buffer into a file.  Return SQLITE_OK on success
   34525 ** or some other error code on failure.
   34526 */
   34527 static int winWrite(
   34528   sqlite3_file *id,               /* File to write into */
   34529   const void *pBuf,               /* The bytes to be written */
   34530   int amt,                        /* Number of bytes to write */
   34531   sqlite3_int64 offset            /* Offset into the file to begin writing at */
   34532 ){
   34533   int rc = 0;                     /* True if error has occurred, else false */
   34534   winFile *pFile = (winFile*)id;  /* File handle */
   34535   int nRetry = 0;                 /* Number of retries */
   34536 
   34537   assert( amt>0 );
   34538   assert( pFile );
   34539   SimulateIOError(return SQLITE_IOERR_WRITE);
   34540   SimulateDiskfullError(return SQLITE_FULL);
   34541 
   34542   OSTRACE(("WRITE file=%p, buffer=%p, amount=%d, offset=%lld, lock=%d\n",
   34543            pFile->h, pBuf, amt, offset, pFile->locktype));
   34544 
   34545 #if SQLITE_MAX_MMAP_SIZE>0
   34546   /* Deal with as much of this write request as possible by transfering
   34547   ** data from the memory mapping using memcpy().  */
   34548   if( offset<pFile->mmapSize ){
   34549     if( offset+amt <= pFile->mmapSize ){
   34550       memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
   34551       OSTRACE(("WRITE-MMAP file=%p, rc=SQLITE_OK\n", pFile->h));
   34552       return SQLITE_OK;
   34553     }else{
   34554       int nCopy = (int)(pFile->mmapSize - offset);
   34555       memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
   34556       pBuf = &((u8 *)pBuf)[nCopy];
   34557       amt -= nCopy;
   34558       offset += nCopy;
   34559     }
   34560   }
   34561 #endif
   34562 
   34563 #if SQLITE_OS_WINCE
   34564   rc = winSeekFile(pFile, offset);
   34565   if( rc==0 ){
   34566 #else
   34567   {
   34568 #endif
   34569 #if !SQLITE_OS_WINCE
   34570     OVERLAPPED overlapped;        /* The offset for WriteFile. */
   34571 #endif
   34572     u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
   34573     int nRem = amt;               /* Number of bytes yet to be written */
   34574     DWORD nWrite;                 /* Bytes written by each WriteFile() call */
   34575     DWORD lastErrno = NO_ERROR;   /* Value returned by GetLastError() */
   34576 
   34577 #if !SQLITE_OS_WINCE
   34578     memset(&overlapped, 0, sizeof(OVERLAPPED));
   34579     overlapped.Offset = (LONG)(offset & 0xffffffff);
   34580     overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
   34581 #endif
   34582 
   34583     while( nRem>0 ){
   34584 #if SQLITE_OS_WINCE
   34585       if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
   34586 #else
   34587       if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
   34588 #endif
   34589         if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
   34590         break;
   34591       }
   34592       assert( nWrite==0 || nWrite<=(DWORD)nRem );
   34593       if( nWrite==0 || nWrite>(DWORD)nRem ){
   34594         lastErrno = osGetLastError();
   34595         break;
   34596       }
   34597 #if !SQLITE_OS_WINCE
   34598       offset += nWrite;
   34599       overlapped.Offset = (LONG)(offset & 0xffffffff);
   34600       overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
   34601 #endif
   34602       aRem += nWrite;
   34603       nRem -= nWrite;
   34604     }
   34605     if( nRem>0 ){
   34606       pFile->lastErrno = lastErrno;
   34607       rc = 1;
   34608     }
   34609   }
   34610 
   34611   if( rc ){
   34612     if(   ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
   34613        || ( pFile->lastErrno==ERROR_DISK_FULL )){
   34614       OSTRACE(("WRITE file=%p, rc=SQLITE_FULL\n", pFile->h));
   34615       return winLogError(SQLITE_FULL, pFile->lastErrno,
   34616                          "winWrite1", pFile->zPath);
   34617     }
   34618     OSTRACE(("WRITE file=%p, rc=SQLITE_IOERR_WRITE\n", pFile->h));
   34619     return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
   34620                        "winWrite2", pFile->zPath);
   34621   }else{
   34622     winLogIoerr(nRetry);
   34623   }
   34624   OSTRACE(("WRITE file=%p, rc=SQLITE_OK\n", pFile->h));
   34625   return SQLITE_OK;
   34626 }
   34627 
   34628 /*
   34629 ** Truncate an open file to a specified size
   34630 */
   34631 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
   34632   winFile *pFile = (winFile*)id;  /* File handle object */
   34633   int rc = SQLITE_OK;             /* Return code for this function */
   34634   DWORD lastErrno;
   34635 
   34636   assert( pFile );
   34637   SimulateIOError(return SQLITE_IOERR_TRUNCATE);
   34638   OSTRACE(("TRUNCATE file=%p, size=%lld, lock=%d\n",
   34639            pFile->h, nByte, pFile->locktype));
   34640 
   34641   /* If the user has configured a chunk-size for this file, truncate the
   34642   ** file so that it consists of an integer number of chunks (i.e. the
   34643   ** actual file size after the operation may be larger than the requested
   34644   ** size).
   34645   */
   34646   if( pFile->szChunk>0 ){
   34647     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
   34648   }
   34649 
   34650   /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
   34651   if( winSeekFile(pFile, nByte) ){
   34652     rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
   34653                      "winTruncate1", pFile->zPath);
   34654   }else if( 0==osSetEndOfFile(pFile->h) &&
   34655             ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
   34656     pFile->lastErrno = lastErrno;
   34657     rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
   34658                      "winTruncate2", pFile->zPath);
   34659   }
   34660 
   34661 #if SQLITE_MAX_MMAP_SIZE>0
   34662   /* If the file was truncated to a size smaller than the currently
   34663   ** mapped region, reduce the effective mapping size as well. SQLite will
   34664   ** use read() and write() to access data beyond this point from now on.
   34665   */
   34666   if( pFile->pMapRegion && nByte<pFile->mmapSize ){
   34667     pFile->mmapSize = nByte;
   34668   }
   34669 #endif
   34670 
   34671   OSTRACE(("TRUNCATE file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
   34672   return rc;
   34673 }
   34674 
   34675 #ifdef SQLITE_TEST
   34676 /*
   34677 ** Count the number of fullsyncs and normal syncs.  This is used to test
   34678 ** that syncs and fullsyncs are occuring at the right times.
   34679 */
   34680 SQLITE_API int sqlite3_sync_count = 0;
   34681 SQLITE_API int sqlite3_fullsync_count = 0;
   34682 #endif
   34683 
   34684 /*
   34685 ** Make sure all writes to a particular file are committed to disk.
   34686 */
   34687 static int winSync(sqlite3_file *id, int flags){
   34688 #ifndef SQLITE_NO_SYNC
   34689   /*
   34690   ** Used only when SQLITE_NO_SYNC is not defined.
   34691    */
   34692   BOOL rc;
   34693 #endif
   34694 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
   34695     (defined(SQLITE_TEST) && defined(SQLITE_DEBUG))
   34696   /*
   34697   ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
   34698   ** OSTRACE() macros.
   34699    */
   34700   winFile *pFile = (winFile*)id;
   34701 #else
   34702   UNUSED_PARAMETER(id);
   34703 #endif
   34704 
   34705   assert( pFile );
   34706   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
   34707   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
   34708       || (flags&0x0F)==SQLITE_SYNC_FULL
   34709   );
   34710 
   34711   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
   34712   ** line is to test that doing so does not cause any problems.
   34713   */
   34714   SimulateDiskfullError( return SQLITE_FULL );
   34715 
   34716   OSTRACE(("SYNC file=%p, flags=%x, lock=%d\n",
   34717            pFile->h, flags, pFile->locktype));
   34718 
   34719 #ifndef SQLITE_TEST
   34720   UNUSED_PARAMETER(flags);
   34721 #else
   34722   if( (flags&0x0F)==SQLITE_SYNC_FULL ){
   34723     sqlite3_fullsync_count++;
   34724   }
   34725   sqlite3_sync_count++;
   34726 #endif
   34727 
   34728   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
   34729   ** no-op
   34730   */
   34731 #ifdef SQLITE_NO_SYNC
   34732   OSTRACE(("SYNC-NOP file=%p, rc=SQLITE_OK\n", pFile->h));
   34733   return SQLITE_OK;
   34734 #else
   34735   rc = osFlushFileBuffers(pFile->h);
   34736   SimulateIOError( rc=FALSE );
   34737   if( rc ){
   34738     OSTRACE(("SYNC file=%p, rc=SQLITE_OK\n", pFile->h));
   34739     return SQLITE_OK;
   34740   }else{
   34741     pFile->lastErrno = osGetLastError();
   34742     OSTRACE(("SYNC file=%p, rc=SQLITE_IOERR_FSYNC\n", pFile->h));
   34743     return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
   34744                        "winSync", pFile->zPath);
   34745   }
   34746 #endif
   34747 }
   34748 
   34749 /*
   34750 ** Determine the current size of a file in bytes
   34751 */
   34752 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
   34753   winFile *pFile = (winFile*)id;
   34754   int rc = SQLITE_OK;
   34755 
   34756   assert( id!=0 );
   34757   assert( pSize!=0 );
   34758   SimulateIOError(return SQLITE_IOERR_FSTAT);
   34759   OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
   34760 
   34761 #if SQLITE_OS_WINRT
   34762   {
   34763     FILE_STANDARD_INFO info;
   34764     if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
   34765                                      &info, sizeof(info)) ){
   34766       *pSize = info.EndOfFile.QuadPart;
   34767     }else{
   34768       pFile->lastErrno = osGetLastError();
   34769       rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
   34770                        "winFileSize", pFile->zPath);
   34771     }
   34772   }
   34773 #else
   34774   {
   34775     DWORD upperBits;
   34776     DWORD lowerBits;
   34777     DWORD lastErrno;
   34778 
   34779     lowerBits = osGetFileSize(pFile->h, &upperBits);
   34780     *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
   34781     if(   (lowerBits == INVALID_FILE_SIZE)
   34782        && ((lastErrno = osGetLastError())!=NO_ERROR) ){
   34783       pFile->lastErrno = lastErrno;
   34784       rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
   34785                        "winFileSize", pFile->zPath);
   34786     }
   34787   }
   34788 #endif
   34789   OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
   34790            pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
   34791   return rc;
   34792 }
   34793 
   34794 /*
   34795 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
   34796 */
   34797 #ifndef LOCKFILE_FAIL_IMMEDIATELY
   34798 # define LOCKFILE_FAIL_IMMEDIATELY 1
   34799 #endif
   34800 
   34801 #ifndef LOCKFILE_EXCLUSIVE_LOCK
   34802 # define LOCKFILE_EXCLUSIVE_LOCK 2
   34803 #endif
   34804 
   34805 /*
   34806 ** Historically, SQLite has used both the LockFile and LockFileEx functions.
   34807 ** When the LockFile function was used, it was always expected to fail
   34808 ** immediately if the lock could not be obtained.  Also, it always expected to
   34809 ** obtain an exclusive lock.  These flags are used with the LockFileEx function
   34810 ** and reflect those expectations; therefore, they should not be changed.
   34811 */
   34812 #ifndef SQLITE_LOCKFILE_FLAGS
   34813 # define SQLITE_LOCKFILE_FLAGS   (LOCKFILE_FAIL_IMMEDIATELY | \
   34814                                   LOCKFILE_EXCLUSIVE_LOCK)
   34815 #endif
   34816 
   34817 /*
   34818 ** Currently, SQLite never calls the LockFileEx function without wanting the
   34819 ** call to fail immediately if the lock cannot be obtained.
   34820 */
   34821 #ifndef SQLITE_LOCKFILEEX_FLAGS
   34822 # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
   34823 #endif
   34824 
   34825 /*
   34826 ** Acquire a reader lock.
   34827 ** Different API routines are called depending on whether or not this
   34828 ** is Win9x or WinNT.
   34829 */
   34830 static int winGetReadLock(winFile *pFile){
   34831   int res;
   34832   OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
   34833   if( osIsNT() ){
   34834 #if SQLITE_OS_WINCE
   34835     /*
   34836     ** NOTE: Windows CE is handled differently here due its lack of the Win32
   34837     **       API LockFileEx.
   34838     */
   34839     res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
   34840 #else
   34841     res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
   34842                       SHARED_SIZE, 0);
   34843 #endif
   34844   }
   34845 #ifdef SQLITE_WIN32_HAS_ANSI
   34846   else{
   34847     int lk;
   34848     sqlite3_randomness(sizeof(lk), &lk);
   34849     pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
   34850     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
   34851                       SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
   34852   }
   34853 #endif
   34854   if( res == 0 ){
   34855     pFile->lastErrno = osGetLastError();
   34856     /* No need to log a failure to lock */
   34857   }
   34858   OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
   34859   return res;
   34860 }
   34861 
   34862 /*
   34863 ** Undo a readlock
   34864 */
   34865 static int winUnlockReadLock(winFile *pFile){
   34866   int res;
   34867   DWORD lastErrno;
   34868   OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
   34869   if( osIsNT() ){
   34870     res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
   34871   }
   34872 #ifdef SQLITE_WIN32_HAS_ANSI
   34873   else{
   34874     res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
   34875   }
   34876 #endif
   34877   if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
   34878     pFile->lastErrno = lastErrno;
   34879     winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
   34880                 "winUnlockReadLock", pFile->zPath);
   34881   }
   34882   OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
   34883   return res;
   34884 }
   34885 
   34886 /*
   34887 ** Lock the file with the lock specified by parameter locktype - one
   34888 ** of the following:
   34889 **
   34890 **     (1) SHARED_LOCK
   34891 **     (2) RESERVED_LOCK
   34892 **     (3) PENDING_LOCK
   34893 **     (4) EXCLUSIVE_LOCK
   34894 **
   34895 ** Sometimes when requesting one lock state, additional lock states
   34896 ** are inserted in between.  The locking might fail on one of the later
   34897 ** transitions leaving the lock state different from what it started but
   34898 ** still short of its goal.  The following chart shows the allowed
   34899 ** transitions and the inserted intermediate states:
   34900 **
   34901 **    UNLOCKED -> SHARED
   34902 **    SHARED -> RESERVED
   34903 **    SHARED -> (PENDING) -> EXCLUSIVE
   34904 **    RESERVED -> (PENDING) -> EXCLUSIVE
   34905 **    PENDING -> EXCLUSIVE
   34906 **
   34907 ** This routine will only increase a lock.  The winUnlock() routine
   34908 ** erases all locks at once and returns us immediately to locking level 0.
   34909 ** It is not possible to lower the locking level one step at a time.  You
   34910 ** must go straight to locking level 0.
   34911 */
   34912 static int winLock(sqlite3_file *id, int locktype){
   34913   int rc = SQLITE_OK;    /* Return code from subroutines */
   34914   int res = 1;           /* Result of a Windows lock call */
   34915   int newLocktype;       /* Set pFile->locktype to this value before exiting */
   34916   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
   34917   winFile *pFile = (winFile*)id;
   34918   DWORD lastErrno = NO_ERROR;
   34919 
   34920   assert( id!=0 );
   34921   OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
   34922            pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
   34923 
   34924   /* If there is already a lock of this type or more restrictive on the
   34925   ** OsFile, do nothing. Don't use the end_lock: exit path, as
   34926   ** sqlite3OsEnterMutex() hasn't been called yet.
   34927   */
   34928   if( pFile->locktype>=locktype ){
   34929     OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
   34930     return SQLITE_OK;
   34931   }
   34932 
   34933   /* Make sure the locking sequence is correct
   34934   */
   34935   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
   34936   assert( locktype!=PENDING_LOCK );
   34937   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
   34938 
   34939   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
   34940   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
   34941   ** the PENDING_LOCK byte is temporary.
   34942   */
   34943   newLocktype = pFile->locktype;
   34944   if(   (pFile->locktype==NO_LOCK)
   34945      || (   (locktype==EXCLUSIVE_LOCK)
   34946          && (pFile->locktype==RESERVED_LOCK))
   34947   ){
   34948     int cnt = 3;
   34949     while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
   34950                                          PENDING_BYTE, 0, 1, 0))==0 ){
   34951       /* Try 3 times to get the pending lock.  This is needed to work
   34952       ** around problems caused by indexing and/or anti-virus software on
   34953       ** Windows systems.
   34954       ** If you are using this code as a model for alternative VFSes, do not
   34955       ** copy this retry logic.  It is a hack intended for Windows only.
   34956       */
   34957       lastErrno = osGetLastError();
   34958       OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
   34959                pFile->h, cnt, res));
   34960       if( lastErrno==ERROR_INVALID_HANDLE ){
   34961         pFile->lastErrno = lastErrno;
   34962         rc = SQLITE_IOERR_LOCK;
   34963         OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
   34964                  pFile->h, cnt, sqlite3ErrName(rc)));
   34965         return rc;
   34966       }
   34967       if( cnt ) sqlite3_win32_sleep(1);
   34968     }
   34969     gotPendingLock = res;
   34970     if( !res ){
   34971       lastErrno = osGetLastError();
   34972     }
   34973   }
   34974 
   34975   /* Acquire a shared lock
   34976   */
   34977   if( locktype==SHARED_LOCK && res ){
   34978     assert( pFile->locktype==NO_LOCK );
   34979     res = winGetReadLock(pFile);
   34980     if( res ){
   34981       newLocktype = SHARED_LOCK;
   34982     }else{
   34983       lastErrno = osGetLastError();
   34984     }
   34985   }
   34986 
   34987   /* Acquire a RESERVED lock
   34988   */
   34989   if( locktype==RESERVED_LOCK && res ){
   34990     assert( pFile->locktype==SHARED_LOCK );
   34991     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
   34992     if( res ){
   34993       newLocktype = RESERVED_LOCK;
   34994     }else{
   34995       lastErrno = osGetLastError();
   34996     }
   34997   }
   34998 
   34999   /* Acquire a PENDING lock
   35000   */
   35001   if( locktype==EXCLUSIVE_LOCK && res ){
   35002     newLocktype = PENDING_LOCK;
   35003     gotPendingLock = 0;
   35004   }
   35005 
   35006   /* Acquire an EXCLUSIVE lock
   35007   */
   35008   if( locktype==EXCLUSIVE_LOCK && res ){
   35009     assert( pFile->locktype>=SHARED_LOCK );
   35010     res = winUnlockReadLock(pFile);
   35011     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
   35012                       SHARED_SIZE, 0);
   35013     if( res ){
   35014       newLocktype = EXCLUSIVE_LOCK;
   35015     }else{
   35016       lastErrno = osGetLastError();
   35017       winGetReadLock(pFile);
   35018     }
   35019   }
   35020 
   35021   /* If we are holding a PENDING lock that ought to be released, then
   35022   ** release it now.
   35023   */
   35024   if( gotPendingLock && locktype==SHARED_LOCK ){
   35025     winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
   35026   }
   35027 
   35028   /* Update the state of the lock has held in the file descriptor then
   35029   ** return the appropriate result code.
   35030   */
   35031   if( res ){
   35032     rc = SQLITE_OK;
   35033   }else{
   35034     pFile->lastErrno = lastErrno;
   35035     rc = SQLITE_BUSY;
   35036     OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
   35037              pFile->h, locktype, newLocktype));
   35038   }
   35039   pFile->locktype = (u8)newLocktype;
   35040   OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
   35041            pFile->h, pFile->locktype, sqlite3ErrName(rc)));
   35042   return rc;
   35043 }
   35044 
   35045 /*
   35046 ** This routine checks if there is a RESERVED lock held on the specified
   35047 ** file by this or any other process. If such a lock is held, return
   35048 ** non-zero, otherwise zero.
   35049 */
   35050 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
   35051   int res;
   35052   winFile *pFile = (winFile*)id;
   35053 
   35054   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   35055   OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
   35056 
   35057   assert( id!=0 );
   35058   if( pFile->locktype>=RESERVED_LOCK ){
   35059     res = 1;
   35060     OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
   35061   }else{
   35062     res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE, 0, 1, 0);
   35063     if( res ){
   35064       winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
   35065     }
   35066     res = !res;
   35067     OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
   35068   }
   35069   *pResOut = res;
   35070   OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
   35071            pFile->h, pResOut, *pResOut));
   35072   return SQLITE_OK;
   35073 }
   35074 
   35075 /*
   35076 ** Lower the locking level on file descriptor id to locktype.  locktype
   35077 ** must be either NO_LOCK or SHARED_LOCK.
   35078 **
   35079 ** If the locking level of the file descriptor is already at or below
   35080 ** the requested locking level, this routine is a no-op.
   35081 **
   35082 ** It is not possible for this routine to fail if the second argument
   35083 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
   35084 ** might return SQLITE_IOERR;
   35085 */
   35086 static int winUnlock(sqlite3_file *id, int locktype){
   35087   int type;
   35088   winFile *pFile = (winFile*)id;
   35089   int rc = SQLITE_OK;
   35090   assert( pFile!=0 );
   35091   assert( locktype<=SHARED_LOCK );
   35092   OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
   35093            pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
   35094   type = pFile->locktype;
   35095   if( type>=EXCLUSIVE_LOCK ){
   35096     winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
   35097     if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
   35098       /* This should never happen.  We should always be able to
   35099       ** reacquire the read lock */
   35100       rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
   35101                        "winUnlock", pFile->zPath);
   35102     }
   35103   }
   35104   if( type>=RESERVED_LOCK ){
   35105     winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
   35106   }
   35107   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
   35108     winUnlockReadLock(pFile);
   35109   }
   35110   if( type>=PENDING_LOCK ){
   35111     winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
   35112   }
   35113   pFile->locktype = (u8)locktype;
   35114   OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
   35115            pFile->h, pFile->locktype, sqlite3ErrName(rc)));
   35116   return rc;
   35117 }
   35118 
   35119 /*
   35120 ** If *pArg is inititially negative then this is a query.  Set *pArg to
   35121 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
   35122 **
   35123 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
   35124 */
   35125 static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
   35126   if( *pArg<0 ){
   35127     *pArg = (pFile->ctrlFlags & mask)!=0;
   35128   }else if( (*pArg)==0 ){
   35129     pFile->ctrlFlags &= ~mask;
   35130   }else{
   35131     pFile->ctrlFlags |= mask;
   35132   }
   35133 }
   35134 
   35135 /* Forward references to VFS helper methods used for temporary files */
   35136 static int winGetTempname(sqlite3_vfs *, char **);
   35137 static int winIsDir(const void *);
   35138 static BOOL winIsDriveLetterAndColon(const char *);
   35139 
   35140 /*
   35141 ** Control and query of the open file handle.
   35142 */
   35143 static int winFileControl(sqlite3_file *id, int op, void *pArg){
   35144   winFile *pFile = (winFile*)id;
   35145   OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
   35146   switch( op ){
   35147     case SQLITE_FCNTL_LOCKSTATE: {
   35148       *(int*)pArg = pFile->locktype;
   35149       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
   35150       return SQLITE_OK;
   35151     }
   35152     case SQLITE_LAST_ERRNO: {
   35153       *(int*)pArg = (int)pFile->lastErrno;
   35154       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
   35155       return SQLITE_OK;
   35156     }
   35157     case SQLITE_FCNTL_CHUNK_SIZE: {
   35158       pFile->szChunk = *(int *)pArg;
   35159       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
   35160       return SQLITE_OK;
   35161     }
   35162     case SQLITE_FCNTL_SIZE_HINT: {
   35163       if( pFile->szChunk>0 ){
   35164         sqlite3_int64 oldSz;
   35165         int rc = winFileSize(id, &oldSz);
   35166         if( rc==SQLITE_OK ){
   35167           sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
   35168           if( newSz>oldSz ){
   35169             SimulateIOErrorBenign(1);
   35170             rc = winTruncate(id, newSz);
   35171             SimulateIOErrorBenign(0);
   35172           }
   35173         }
   35174         OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
   35175         return rc;
   35176       }
   35177       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
   35178       return SQLITE_OK;
   35179     }
   35180     case SQLITE_FCNTL_PERSIST_WAL: {
   35181       winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
   35182       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
   35183       return SQLITE_OK;
   35184     }
   35185     case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
   35186       winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
   35187       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
   35188       return SQLITE_OK;
   35189     }
   35190     case SQLITE_FCNTL_VFSNAME: {
   35191       *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
   35192       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
   35193       return SQLITE_OK;
   35194     }
   35195     case SQLITE_FCNTL_WIN32_AV_RETRY: {
   35196       int *a = (int*)pArg;
   35197       if( a[0]>0 ){
   35198         winIoerrRetry = a[0];
   35199       }else{
   35200         a[0] = winIoerrRetry;
   35201       }
   35202       if( a[1]>0 ){
   35203         winIoerrRetryDelay = a[1];
   35204       }else{
   35205         a[1] = winIoerrRetryDelay;
   35206       }
   35207       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
   35208       return SQLITE_OK;
   35209     }
   35210 #ifdef SQLITE_TEST
   35211     case SQLITE_FCNTL_WIN32_SET_HANDLE: {
   35212       LPHANDLE phFile = (LPHANDLE)pArg;
   35213       HANDLE hOldFile = pFile->h;
   35214       pFile->h = *phFile;
   35215       *phFile = hOldFile;
   35216       OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
   35217                hOldFile, pFile->h));
   35218       return SQLITE_OK;
   35219     }
   35220 #endif
   35221     case SQLITE_FCNTL_TEMPFILENAME: {
   35222       char *zTFile = 0;
   35223       int rc = winGetTempname(pFile->pVfs, &zTFile);
   35224       if( rc==SQLITE_OK ){
   35225         *(char**)pArg = zTFile;
   35226       }
   35227       OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
   35228       return rc;
   35229     }
   35230 #if SQLITE_MAX_MMAP_SIZE>0
   35231     case SQLITE_FCNTL_MMAP_SIZE: {
   35232       i64 newLimit = *(i64*)pArg;
   35233       int rc = SQLITE_OK;
   35234       if( newLimit>sqlite3GlobalConfig.mxMmap ){
   35235         newLimit = sqlite3GlobalConfig.mxMmap;
   35236       }
   35237       *(i64*)pArg = pFile->mmapSizeMax;
   35238       if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
   35239         pFile->mmapSizeMax = newLimit;
   35240         if( pFile->mmapSize>0 ){
   35241           winUnmapfile(pFile);
   35242           rc = winMapfile(pFile, -1);
   35243         }
   35244       }
   35245       OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
   35246       return rc;
   35247     }
   35248 #endif
   35249   }
   35250   OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
   35251   return SQLITE_NOTFOUND;
   35252 }
   35253 
   35254 /*
   35255 ** Return the sector size in bytes of the underlying block device for
   35256 ** the specified file. This is almost always 512 bytes, but may be
   35257 ** larger for some devices.
   35258 **
   35259 ** SQLite code assumes this function cannot fail. It also assumes that
   35260 ** if two files are created in the same file-system directory (i.e.
   35261 ** a database and its journal file) that the sector size will be the
   35262 ** same for both.
   35263 */
   35264 static int winSectorSize(sqlite3_file *id){
   35265   (void)id;
   35266   return SQLITE_DEFAULT_SECTOR_SIZE;
   35267 }
   35268 
   35269 /*
   35270 ** Return a vector of device characteristics.
   35271 */
   35272 static int winDeviceCharacteristics(sqlite3_file *id){
   35273   winFile *p = (winFile*)id;
   35274   return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
   35275          ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
   35276 }
   35277 
   35278 /*
   35279 ** Windows will only let you create file view mappings
   35280 ** on allocation size granularity boundaries.
   35281 ** During sqlite3_os_init() we do a GetSystemInfo()
   35282 ** to get the granularity size.
   35283 */
   35284 static SYSTEM_INFO winSysInfo;
   35285 
   35286 #ifndef SQLITE_OMIT_WAL
   35287 
   35288 /*
   35289 ** Helper functions to obtain and relinquish the global mutex. The
   35290 ** global mutex is used to protect the winLockInfo objects used by
   35291 ** this file, all of which may be shared by multiple threads.
   35292 **
   35293 ** Function winShmMutexHeld() is used to assert() that the global mutex
   35294 ** is held when required. This function is only used as part of assert()
   35295 ** statements. e.g.
   35296 **
   35297 **   winShmEnterMutex()
   35298 **     assert( winShmMutexHeld() );
   35299 **   winShmLeaveMutex()
   35300 */
   35301 static void winShmEnterMutex(void){
   35302   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   35303 }
   35304 static void winShmLeaveMutex(void){
   35305   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   35306 }
   35307 #ifndef NDEBUG
   35308 static int winShmMutexHeld(void) {
   35309   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   35310 }
   35311 #endif
   35312 
   35313 /*
   35314 ** Object used to represent a single file opened and mmapped to provide
   35315 ** shared memory.  When multiple threads all reference the same
   35316 ** log-summary, each thread has its own winFile object, but they all
   35317 ** point to a single instance of this object.  In other words, each
   35318 ** log-summary is opened only once per process.
   35319 **
   35320 ** winShmMutexHeld() must be true when creating or destroying
   35321 ** this object or while reading or writing the following fields:
   35322 **
   35323 **      nRef
   35324 **      pNext
   35325 **
   35326 ** The following fields are read-only after the object is created:
   35327 **
   35328 **      fid
   35329 **      zFilename
   35330 **
   35331 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
   35332 ** winShmMutexHeld() is true when reading or writing any other field
   35333 ** in this structure.
   35334 **
   35335 */
   35336 struct winShmNode {
   35337   sqlite3_mutex *mutex;      /* Mutex to access this object */
   35338   char *zFilename;           /* Name of the file */
   35339   winFile hFile;             /* File handle from winOpen */
   35340 
   35341   int szRegion;              /* Size of shared-memory regions */
   35342   int nRegion;               /* Size of array apRegion */
   35343   struct ShmRegion {
   35344     HANDLE hMap;             /* File handle from CreateFileMapping */
   35345     void *pMap;
   35346   } *aRegion;
   35347   DWORD lastErrno;           /* The Windows errno from the last I/O error */
   35348 
   35349   int nRef;                  /* Number of winShm objects pointing to this */
   35350   winShm *pFirst;            /* All winShm objects pointing to this */
   35351   winShmNode *pNext;         /* Next in list of all winShmNode objects */
   35352 #ifdef SQLITE_DEBUG
   35353   u8 nextShmId;              /* Next available winShm.id value */
   35354 #endif
   35355 };
   35356 
   35357 /*
   35358 ** A global array of all winShmNode objects.
   35359 **
   35360 ** The winShmMutexHeld() must be true while reading or writing this list.
   35361 */
   35362 static winShmNode *winShmNodeList = 0;
   35363 
   35364 /*
   35365 ** Structure used internally by this VFS to record the state of an
   35366 ** open shared memory connection.
   35367 **
   35368 ** The following fields are initialized when this object is created and
   35369 ** are read-only thereafter:
   35370 **
   35371 **    winShm.pShmNode
   35372 **    winShm.id
   35373 **
   35374 ** All other fields are read/write.  The winShm.pShmNode->mutex must be held
   35375 ** while accessing any read/write fields.
   35376 */
   35377 struct winShm {
   35378   winShmNode *pShmNode;      /* The underlying winShmNode object */
   35379   winShm *pNext;             /* Next winShm with the same winShmNode */
   35380   u8 hasMutex;               /* True if holding the winShmNode mutex */
   35381   u16 sharedMask;            /* Mask of shared locks held */
   35382   u16 exclMask;              /* Mask of exclusive locks held */
   35383 #ifdef SQLITE_DEBUG
   35384   u8 id;                     /* Id of this connection with its winShmNode */
   35385 #endif
   35386 };
   35387 
   35388 /*
   35389 ** Constants used for locking
   35390 */
   35391 #define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
   35392 #define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
   35393 
   35394 /*
   35395 ** Apply advisory locks for all n bytes beginning at ofst.
   35396 */
   35397 #define _SHM_UNLCK  1
   35398 #define _SHM_RDLCK  2
   35399 #define _SHM_WRLCK  3
   35400 static int winShmSystemLock(
   35401   winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
   35402   int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
   35403   int ofst,             /* Offset to first byte to be locked/unlocked */
   35404   int nByte             /* Number of bytes to lock or unlock */
   35405 ){
   35406   int rc = 0;           /* Result code form Lock/UnlockFileEx() */
   35407 
   35408   /* Access to the winShmNode object is serialized by the caller */
   35409   assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
   35410 
   35411   OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
   35412            pFile->hFile.h, lockType, ofst, nByte));
   35413 
   35414   /* Release/Acquire the system-level lock */
   35415   if( lockType==_SHM_UNLCK ){
   35416     rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
   35417   }else{
   35418     /* Initialize the locking parameters */
   35419     DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
   35420     if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
   35421     rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
   35422   }
   35423 
   35424   if( rc!= 0 ){
   35425     rc = SQLITE_OK;
   35426   }else{
   35427     pFile->lastErrno =  osGetLastError();
   35428     rc = SQLITE_BUSY;
   35429   }
   35430 
   35431   OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
   35432            pFile->hFile.h, (lockType == _SHM_UNLCK) ? "winUnlockFile" :
   35433            "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
   35434 
   35435   return rc;
   35436 }
   35437 
   35438 /* Forward references to VFS methods */
   35439 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
   35440 static int winDelete(sqlite3_vfs *,const char*,int);
   35441 
   35442 /*
   35443 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
   35444 **
   35445 ** This is not a VFS shared-memory method; it is a utility function called
   35446 ** by VFS shared-memory methods.
   35447 */
   35448 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
   35449   winShmNode **pp;
   35450   winShmNode *p;
   35451   assert( winShmMutexHeld() );
   35452   OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
   35453            osGetCurrentProcessId(), deleteFlag));
   35454   pp = &winShmNodeList;
   35455   while( (p = *pp)!=0 ){
   35456     if( p->nRef==0 ){
   35457       int i;
   35458       if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
   35459       for(i=0; i<p->nRegion; i++){
   35460         BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
   35461         OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
   35462                  osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
   35463         UNUSED_VARIABLE_VALUE(bRc);
   35464         bRc = osCloseHandle(p->aRegion[i].hMap);
   35465         OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
   35466                  osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
   35467         UNUSED_VARIABLE_VALUE(bRc);
   35468       }
   35469       if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
   35470         SimulateIOErrorBenign(1);
   35471         winClose((sqlite3_file *)&p->hFile);
   35472         SimulateIOErrorBenign(0);
   35473       }
   35474       if( deleteFlag ){
   35475         SimulateIOErrorBenign(1);
   35476         sqlite3BeginBenignMalloc();
   35477         winDelete(pVfs, p->zFilename, 0);
   35478         sqlite3EndBenignMalloc();
   35479         SimulateIOErrorBenign(0);
   35480       }
   35481       *pp = p->pNext;
   35482       sqlite3_free(p->aRegion);
   35483       sqlite3_free(p);
   35484     }else{
   35485       pp = &p->pNext;
   35486     }
   35487   }
   35488 }
   35489 
   35490 /*
   35491 ** Open the shared-memory area associated with database file pDbFd.
   35492 **
   35493 ** When opening a new shared-memory file, if no other instances of that
   35494 ** file are currently open, in this process or in other processes, then
   35495 ** the file must be truncated to zero length or have its header cleared.
   35496 */
   35497 static int winOpenSharedMemory(winFile *pDbFd){
   35498   struct winShm *p;                  /* The connection to be opened */
   35499   struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
   35500   int rc;                            /* Result code */
   35501   struct winShmNode *pNew;           /* Newly allocated winShmNode */
   35502   int nName;                         /* Size of zName in bytes */
   35503 
   35504   assert( pDbFd->pShm==0 );    /* Not previously opened */
   35505 
   35506   /* Allocate space for the new sqlite3_shm object.  Also speculatively
   35507   ** allocate space for a new winShmNode and filename.
   35508   */
   35509   p = sqlite3MallocZero( sizeof(*p) );
   35510   if( p==0 ) return SQLITE_IOERR_NOMEM;
   35511   nName = sqlite3Strlen30(pDbFd->zPath);
   35512   pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
   35513   if( pNew==0 ){
   35514     sqlite3_free(p);
   35515     return SQLITE_IOERR_NOMEM;
   35516   }
   35517   pNew->zFilename = (char*)&pNew[1];
   35518   sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
   35519   sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
   35520 
   35521   /* Look to see if there is an existing winShmNode that can be used.
   35522   ** If no matching winShmNode currently exists, create a new one.
   35523   */
   35524   winShmEnterMutex();
   35525   for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
   35526     /* TBD need to come up with better match here.  Perhaps
   35527     ** use FILE_ID_BOTH_DIR_INFO Structure.
   35528     */
   35529     if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
   35530   }
   35531   if( pShmNode ){
   35532     sqlite3_free(pNew);
   35533   }else{
   35534     pShmNode = pNew;
   35535     pNew = 0;
   35536     ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
   35537     pShmNode->pNext = winShmNodeList;
   35538     winShmNodeList = pShmNode;
   35539 
   35540     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
   35541     if( pShmNode->mutex==0 ){
   35542       rc = SQLITE_IOERR_NOMEM;
   35543       goto shm_open_err;
   35544     }
   35545 
   35546     rc = winOpen(pDbFd->pVfs,
   35547                  pShmNode->zFilename,             /* Name of the file (UTF-8) */
   35548                  (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
   35549                  SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
   35550                  0);
   35551     if( SQLITE_OK!=rc ){
   35552       goto shm_open_err;
   35553     }
   35554 
   35555     /* Check to see if another process is holding the dead-man switch.
   35556     ** If not, truncate the file to zero length.
   35557     */
   35558     if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
   35559       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
   35560       if( rc!=SQLITE_OK ){
   35561         rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
   35562                          "winOpenShm", pDbFd->zPath);
   35563       }
   35564     }
   35565     if( rc==SQLITE_OK ){
   35566       winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
   35567       rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
   35568     }
   35569     if( rc ) goto shm_open_err;
   35570   }
   35571 
   35572   /* Make the new connection a child of the winShmNode */
   35573   p->pShmNode = pShmNode;
   35574 #ifdef SQLITE_DEBUG
   35575   p->id = pShmNode->nextShmId++;
   35576 #endif
   35577   pShmNode->nRef++;
   35578   pDbFd->pShm = p;
   35579   winShmLeaveMutex();
   35580 
   35581   /* The reference count on pShmNode has already been incremented under
   35582   ** the cover of the winShmEnterMutex() mutex and the pointer from the
   35583   ** new (struct winShm) object to the pShmNode has been set. All that is
   35584   ** left to do is to link the new object into the linked list starting
   35585   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
   35586   ** mutex.
   35587   */
   35588   sqlite3_mutex_enter(pShmNode->mutex);
   35589   p->pNext = pShmNode->pFirst;
   35590   pShmNode->pFirst = p;
   35591   sqlite3_mutex_leave(pShmNode->mutex);
   35592   return SQLITE_OK;
   35593 
   35594   /* Jump here on any error */
   35595 shm_open_err:
   35596   winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
   35597   winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
   35598   sqlite3_free(p);
   35599   sqlite3_free(pNew);
   35600   winShmLeaveMutex();
   35601   return rc;
   35602 }
   35603 
   35604 /*
   35605 ** Close a connection to shared-memory.  Delete the underlying
   35606 ** storage if deleteFlag is true.
   35607 */
   35608 static int winShmUnmap(
   35609   sqlite3_file *fd,          /* Database holding shared memory */
   35610   int deleteFlag             /* Delete after closing if true */
   35611 ){
   35612   winFile *pDbFd;       /* Database holding shared-memory */
   35613   winShm *p;            /* The connection to be closed */
   35614   winShmNode *pShmNode; /* The underlying shared-memory file */
   35615   winShm **pp;          /* For looping over sibling connections */
   35616 
   35617   pDbFd = (winFile*)fd;
   35618   p = pDbFd->pShm;
   35619   if( p==0 ) return SQLITE_OK;
   35620   pShmNode = p->pShmNode;
   35621 
   35622   /* Remove connection p from the set of connections associated
   35623   ** with pShmNode */
   35624   sqlite3_mutex_enter(pShmNode->mutex);
   35625   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
   35626   *pp = p->pNext;
   35627 
   35628   /* Free the connection p */
   35629   sqlite3_free(p);
   35630   pDbFd->pShm = 0;
   35631   sqlite3_mutex_leave(pShmNode->mutex);
   35632 
   35633   /* If pShmNode->nRef has reached 0, then close the underlying
   35634   ** shared-memory file, too */
   35635   winShmEnterMutex();
   35636   assert( pShmNode->nRef>0 );
   35637   pShmNode->nRef--;
   35638   if( pShmNode->nRef==0 ){
   35639     winShmPurge(pDbFd->pVfs, deleteFlag);
   35640   }
   35641   winShmLeaveMutex();
   35642 
   35643   return SQLITE_OK;
   35644 }
   35645 
   35646 /*
   35647 ** Change the lock state for a shared-memory segment.
   35648 */
   35649 static int winShmLock(
   35650   sqlite3_file *fd,          /* Database file holding the shared memory */
   35651   int ofst,                  /* First lock to acquire or release */
   35652   int n,                     /* Number of locks to acquire or release */
   35653   int flags                  /* What to do with the lock */
   35654 ){
   35655   winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
   35656   winShm *p = pDbFd->pShm;              /* The shared memory being locked */
   35657   winShm *pX;                           /* For looping over all siblings */
   35658   winShmNode *pShmNode = p->pShmNode;
   35659   int rc = SQLITE_OK;                   /* Result code */
   35660   u16 mask;                             /* Mask of locks to take or release */
   35661 
   35662   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
   35663   assert( n>=1 );
   35664   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
   35665        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
   35666        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
   35667        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
   35668   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
   35669 
   35670   mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
   35671   assert( n>1 || mask==(1<<ofst) );
   35672   sqlite3_mutex_enter(pShmNode->mutex);
   35673   if( flags & SQLITE_SHM_UNLOCK ){
   35674     u16 allMask = 0; /* Mask of locks held by siblings */
   35675 
   35676     /* See if any siblings hold this same lock */
   35677     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
   35678       if( pX==p ) continue;
   35679       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
   35680       allMask |= pX->sharedMask;
   35681     }
   35682 
   35683     /* Unlock the system-level locks */
   35684     if( (mask & allMask)==0 ){
   35685       rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
   35686     }else{
   35687       rc = SQLITE_OK;
   35688     }
   35689 
   35690     /* Undo the local locks */
   35691     if( rc==SQLITE_OK ){
   35692       p->exclMask &= ~mask;
   35693       p->sharedMask &= ~mask;
   35694     }
   35695   }else if( flags & SQLITE_SHM_SHARED ){
   35696     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
   35697 
   35698     /* Find out which shared locks are already held by sibling connections.
   35699     ** If any sibling already holds an exclusive lock, go ahead and return
   35700     ** SQLITE_BUSY.
   35701     */
   35702     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
   35703       if( (pX->exclMask & mask)!=0 ){
   35704         rc = SQLITE_BUSY;
   35705         break;
   35706       }
   35707       allShared |= pX->sharedMask;
   35708     }
   35709 
   35710     /* Get shared locks at the system level, if necessary */
   35711     if( rc==SQLITE_OK ){
   35712       if( (allShared & mask)==0 ){
   35713         rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
   35714       }else{
   35715         rc = SQLITE_OK;
   35716       }
   35717     }
   35718 
   35719     /* Get the local shared locks */
   35720     if( rc==SQLITE_OK ){
   35721       p->sharedMask |= mask;
   35722     }
   35723   }else{
   35724     /* Make sure no sibling connections hold locks that will block this
   35725     ** lock.  If any do, return SQLITE_BUSY right away.
   35726     */
   35727     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
   35728       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
   35729         rc = SQLITE_BUSY;
   35730         break;
   35731       }
   35732     }
   35733 
   35734     /* Get the exclusive locks at the system level.  Then if successful
   35735     ** also mark the local connection as being locked.
   35736     */
   35737     if( rc==SQLITE_OK ){
   35738       rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
   35739       if( rc==SQLITE_OK ){
   35740         assert( (p->sharedMask & mask)==0 );
   35741         p->exclMask |= mask;
   35742       }
   35743     }
   35744   }
   35745   sqlite3_mutex_leave(pShmNode->mutex);
   35746   OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
   35747            osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
   35748            sqlite3ErrName(rc)));
   35749   return rc;
   35750 }
   35751 
   35752 /*
   35753 ** Implement a memory barrier or memory fence on shared memory.
   35754 **
   35755 ** All loads and stores begun before the barrier must complete before
   35756 ** any load or store begun after the barrier.
   35757 */
   35758 static void winShmBarrier(
   35759   sqlite3_file *fd          /* Database holding the shared memory */
   35760 ){
   35761   UNUSED_PARAMETER(fd);
   35762   /* MemoryBarrier(); // does not work -- do not know why not */
   35763   winShmEnterMutex();
   35764   winShmLeaveMutex();
   35765 }
   35766 
   35767 /*
   35768 ** This function is called to obtain a pointer to region iRegion of the
   35769 ** shared-memory associated with the database file fd. Shared-memory regions
   35770 ** are numbered starting from zero. Each shared-memory region is szRegion
   35771 ** bytes in size.
   35772 **
   35773 ** If an error occurs, an error code is returned and *pp is set to NULL.
   35774 **
   35775 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
   35776 ** region has not been allocated (by any client, including one running in a
   35777 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
   35778 ** isWrite is non-zero and the requested shared-memory region has not yet
   35779 ** been allocated, it is allocated by this function.
   35780 **
   35781 ** If the shared-memory region has already been allocated or is allocated by
   35782 ** this call as described above, then it is mapped into this processes
   35783 ** address space (if it is not already), *pp is set to point to the mapped
   35784 ** memory and SQLITE_OK returned.
   35785 */
   35786 static int winShmMap(
   35787   sqlite3_file *fd,               /* Handle open on database file */
   35788   int iRegion,                    /* Region to retrieve */
   35789   int szRegion,                   /* Size of regions */
   35790   int isWrite,                    /* True to extend file if necessary */
   35791   void volatile **pp              /* OUT: Mapped memory */
   35792 ){
   35793   winFile *pDbFd = (winFile*)fd;
   35794   winShm *p = pDbFd->pShm;
   35795   winShmNode *pShmNode;
   35796   int rc = SQLITE_OK;
   35797 
   35798   if( !p ){
   35799     rc = winOpenSharedMemory(pDbFd);
   35800     if( rc!=SQLITE_OK ) return rc;
   35801     p = pDbFd->pShm;
   35802   }
   35803   pShmNode = p->pShmNode;
   35804 
   35805   sqlite3_mutex_enter(pShmNode->mutex);
   35806   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
   35807 
   35808   if( pShmNode->nRegion<=iRegion ){
   35809     struct ShmRegion *apNew;           /* New aRegion[] array */
   35810     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
   35811     sqlite3_int64 sz;                  /* Current size of wal-index file */
   35812 
   35813     pShmNode->szRegion = szRegion;
   35814 
   35815     /* The requested region is not mapped into this processes address space.
   35816     ** Check to see if it has been allocated (i.e. if the wal-index file is
   35817     ** large enough to contain the requested region).
   35818     */
   35819     rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
   35820     if( rc!=SQLITE_OK ){
   35821       rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
   35822                        "winShmMap1", pDbFd->zPath);
   35823       goto shmpage_out;
   35824     }
   35825 
   35826     if( sz<nByte ){
   35827       /* The requested memory region does not exist. If isWrite is set to
   35828       ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
   35829       **
   35830       ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
   35831       ** the requested memory region.
   35832       */
   35833       if( !isWrite ) goto shmpage_out;
   35834       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
   35835       if( rc!=SQLITE_OK ){
   35836         rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
   35837                          "winShmMap2", pDbFd->zPath);
   35838         goto shmpage_out;
   35839       }
   35840     }
   35841 
   35842     /* Map the requested memory region into this processes address space. */
   35843     apNew = (struct ShmRegion *)sqlite3_realloc(
   35844         pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
   35845     );
   35846     if( !apNew ){
   35847       rc = SQLITE_IOERR_NOMEM;
   35848       goto shmpage_out;
   35849     }
   35850     pShmNode->aRegion = apNew;
   35851 
   35852     while( pShmNode->nRegion<=iRegion ){
   35853       HANDLE hMap = NULL;         /* file-mapping handle */
   35854       void *pMap = 0;             /* Mapped memory region */
   35855 
   35856 #if SQLITE_OS_WINRT
   35857       hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
   35858           NULL, PAGE_READWRITE, nByte, NULL
   35859       );
   35860 #elif defined(SQLITE_WIN32_HAS_WIDE)
   35861       hMap = osCreateFileMappingW(pShmNode->hFile.h,
   35862           NULL, PAGE_READWRITE, 0, nByte, NULL
   35863       );
   35864 #elif defined(SQLITE_WIN32_HAS_ANSI)
   35865       hMap = osCreateFileMappingA(pShmNode->hFile.h,
   35866           NULL, PAGE_READWRITE, 0, nByte, NULL
   35867       );
   35868 #endif
   35869       OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
   35870                osGetCurrentProcessId(), pShmNode->nRegion, nByte,
   35871                hMap ? "ok" : "failed"));
   35872       if( hMap ){
   35873         int iOffset = pShmNode->nRegion*szRegion;
   35874         int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
   35875 #if SQLITE_OS_WINRT
   35876         pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
   35877             iOffset - iOffsetShift, szRegion + iOffsetShift
   35878         );
   35879 #else
   35880         pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
   35881             0, iOffset - iOffsetShift, szRegion + iOffsetShift
   35882         );
   35883 #endif
   35884         OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
   35885                  osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
   35886                  szRegion, pMap ? "ok" : "failed"));
   35887       }
   35888       if( !pMap ){
   35889         pShmNode->lastErrno = osGetLastError();
   35890         rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
   35891                          "winShmMap3", pDbFd->zPath);
   35892         if( hMap ) osCloseHandle(hMap);
   35893         goto shmpage_out;
   35894       }
   35895 
   35896       pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
   35897       pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
   35898       pShmNode->nRegion++;
   35899     }
   35900   }
   35901 
   35902 shmpage_out:
   35903   if( pShmNode->nRegion>iRegion ){
   35904     int iOffset = iRegion*szRegion;
   35905     int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
   35906     char *p = (char *)pShmNode->aRegion[iRegion].pMap;
   35907     *pp = (void *)&p[iOffsetShift];
   35908   }else{
   35909     *pp = 0;
   35910   }
   35911   sqlite3_mutex_leave(pShmNode->mutex);
   35912   return rc;
   35913 }
   35914 
   35915 #else
   35916 # define winShmMap     0
   35917 # define winShmLock    0
   35918 # define winShmBarrier 0
   35919 # define winShmUnmap   0
   35920 #endif /* #ifndef SQLITE_OMIT_WAL */
   35921 
   35922 /*
   35923 ** Cleans up the mapped region of the specified file, if any.
   35924 */
   35925 #if SQLITE_MAX_MMAP_SIZE>0
   35926 static int winUnmapfile(winFile *pFile){
   35927   assert( pFile!=0 );
   35928   OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
   35929            "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
   35930            osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
   35931            pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
   35932   if( pFile->pMapRegion ){
   35933     if( !osUnmapViewOfFile(pFile->pMapRegion) ){
   35934       pFile->lastErrno = osGetLastError();
   35935       OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
   35936                "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
   35937                pFile->pMapRegion));
   35938       return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
   35939                          "winUnmapfile1", pFile->zPath);
   35940     }
   35941     pFile->pMapRegion = 0;
   35942     pFile->mmapSize = 0;
   35943     pFile->mmapSizeActual = 0;
   35944   }
   35945   if( pFile->hMap!=NULL ){
   35946     if( !osCloseHandle(pFile->hMap) ){
   35947       pFile->lastErrno = osGetLastError();
   35948       OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
   35949                osGetCurrentProcessId(), pFile, pFile->hMap));
   35950       return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
   35951                          "winUnmapfile2", pFile->zPath);
   35952     }
   35953     pFile->hMap = NULL;
   35954   }
   35955   OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
   35956            osGetCurrentProcessId(), pFile));
   35957   return SQLITE_OK;
   35958 }
   35959 
   35960 /*
   35961 ** Memory map or remap the file opened by file-descriptor pFd (if the file
   35962 ** is already mapped, the existing mapping is replaced by the new). Or, if
   35963 ** there already exists a mapping for this file, and there are still
   35964 ** outstanding xFetch() references to it, this function is a no-op.
   35965 **
   35966 ** If parameter nByte is non-negative, then it is the requested size of
   35967 ** the mapping to create. Otherwise, if nByte is less than zero, then the
   35968 ** requested size is the size of the file on disk. The actual size of the
   35969 ** created mapping is either the requested size or the value configured
   35970 ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
   35971 **
   35972 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
   35973 ** recreated as a result of outstanding references) or an SQLite error
   35974 ** code otherwise.
   35975 */
   35976 static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
   35977   sqlite3_int64 nMap = nByte;
   35978   int rc;
   35979 
   35980   assert( nMap>=0 || pFd->nFetchOut==0 );
   35981   OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
   35982            osGetCurrentProcessId(), pFd, nByte));
   35983 
   35984   if( pFd->nFetchOut>0 ) return SQLITE_OK;
   35985 
   35986   if( nMap<0 ){
   35987     rc = winFileSize((sqlite3_file*)pFd, &nMap);
   35988     if( rc ){
   35989       OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
   35990                osGetCurrentProcessId(), pFd));
   35991       return SQLITE_IOERR_FSTAT;
   35992     }
   35993   }
   35994   if( nMap>pFd->mmapSizeMax ){
   35995     nMap = pFd->mmapSizeMax;
   35996   }
   35997   nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
   35998 
   35999   if( nMap==0 && pFd->mmapSize>0 ){
   36000     winUnmapfile(pFd);
   36001   }
   36002   if( nMap!=pFd->mmapSize ){
   36003     void *pNew = 0;
   36004     DWORD protect = PAGE_READONLY;
   36005     DWORD flags = FILE_MAP_READ;
   36006 
   36007     winUnmapfile(pFd);
   36008     if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
   36009       protect = PAGE_READWRITE;
   36010       flags |= FILE_MAP_WRITE;
   36011     }
   36012 #if SQLITE_OS_WINRT
   36013     pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
   36014 #elif defined(SQLITE_WIN32_HAS_WIDE)
   36015     pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
   36016                                 (DWORD)((nMap>>32) & 0xffffffff),
   36017                                 (DWORD)(nMap & 0xffffffff), NULL);
   36018 #elif defined(SQLITE_WIN32_HAS_ANSI)
   36019     pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
   36020                                 (DWORD)((nMap>>32) & 0xffffffff),
   36021                                 (DWORD)(nMap & 0xffffffff), NULL);
   36022 #endif
   36023     if( pFd->hMap==NULL ){
   36024       pFd->lastErrno = osGetLastError();
   36025       rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
   36026                        "winMapfile1", pFd->zPath);
   36027       /* Log the error, but continue normal operation using xRead/xWrite */
   36028       OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
   36029                osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
   36030       return SQLITE_OK;
   36031     }
   36032     assert( (nMap % winSysInfo.dwPageSize)==0 );
   36033     assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
   36034 #if SQLITE_OS_WINRT
   36035     pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
   36036 #else
   36037     pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
   36038 #endif
   36039     if( pNew==NULL ){
   36040       osCloseHandle(pFd->hMap);
   36041       pFd->hMap = NULL;
   36042       pFd->lastErrno = osGetLastError();
   36043       rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
   36044                        "winMapfile2", pFd->zPath);
   36045       /* Log the error, but continue normal operation using xRead/xWrite */
   36046       OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
   36047                osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
   36048       return SQLITE_OK;
   36049     }
   36050     pFd->pMapRegion = pNew;
   36051     pFd->mmapSize = nMap;
   36052     pFd->mmapSizeActual = nMap;
   36053   }
   36054 
   36055   OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
   36056            osGetCurrentProcessId(), pFd));
   36057   return SQLITE_OK;
   36058 }
   36059 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
   36060 
   36061 /*
   36062 ** If possible, return a pointer to a mapping of file fd starting at offset
   36063 ** iOff. The mapping must be valid for at least nAmt bytes.
   36064 **
   36065 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
   36066 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
   36067 ** Finally, if an error does occur, return an SQLite error code. The final
   36068 ** value of *pp is undefined in this case.
   36069 **
   36070 ** If this function does return a pointer, the caller must eventually
   36071 ** release the reference by calling winUnfetch().
   36072 */
   36073 static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
   36074 #if SQLITE_MAX_MMAP_SIZE>0
   36075   winFile *pFd = (winFile*)fd;   /* The underlying database file */
   36076 #endif
   36077   *pp = 0;
   36078 
   36079   OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
   36080            osGetCurrentProcessId(), fd, iOff, nAmt, pp));
   36081 
   36082 #if SQLITE_MAX_MMAP_SIZE>0
   36083   if( pFd->mmapSizeMax>0 ){
   36084     if( pFd->pMapRegion==0 ){
   36085       int rc = winMapfile(pFd, -1);
   36086       if( rc!=SQLITE_OK ){
   36087         OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
   36088                  osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
   36089         return rc;
   36090       }
   36091     }
   36092     if( pFd->mmapSize >= iOff+nAmt ){
   36093       *pp = &((u8 *)pFd->pMapRegion)[iOff];
   36094       pFd->nFetchOut++;
   36095     }
   36096   }
   36097 #endif
   36098 
   36099   OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
   36100            osGetCurrentProcessId(), fd, pp, *pp));
   36101   return SQLITE_OK;
   36102 }
   36103 
   36104 /*
   36105 ** If the third argument is non-NULL, then this function releases a
   36106 ** reference obtained by an earlier call to winFetch(). The second
   36107 ** argument passed to this function must be the same as the corresponding
   36108 ** argument that was passed to the winFetch() invocation.
   36109 **
   36110 ** Or, if the third argument is NULL, then this function is being called
   36111 ** to inform the VFS layer that, according to POSIX, any existing mapping
   36112 ** may now be invalid and should be unmapped.
   36113 */
   36114 static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
   36115 #if SQLITE_MAX_MMAP_SIZE>0
   36116   winFile *pFd = (winFile*)fd;   /* The underlying database file */
   36117 
   36118   /* If p==0 (unmap the entire file) then there must be no outstanding
   36119   ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
   36120   ** then there must be at least one outstanding.  */
   36121   assert( (p==0)==(pFd->nFetchOut==0) );
   36122 
   36123   /* If p!=0, it must match the iOff value. */
   36124   assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
   36125 
   36126   OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
   36127            osGetCurrentProcessId(), pFd, iOff, p));
   36128 
   36129   if( p ){
   36130     pFd->nFetchOut--;
   36131   }else{
   36132     /* FIXME:  If Windows truly always prevents truncating or deleting a
   36133     ** file while a mapping is held, then the following winUnmapfile() call
   36134     ** is unnecessary can can be omitted - potentially improving
   36135     ** performance.  */
   36136     winUnmapfile(pFd);
   36137   }
   36138 
   36139   assert( pFd->nFetchOut>=0 );
   36140 #endif
   36141 
   36142   OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
   36143            osGetCurrentProcessId(), fd));
   36144   return SQLITE_OK;
   36145 }
   36146 
   36147 /*
   36148 ** Here ends the implementation of all sqlite3_file methods.
   36149 **
   36150 ********************** End sqlite3_file Methods *******************************
   36151 ******************************************************************************/
   36152 
   36153 /*
   36154 ** This vector defines all the methods that can operate on an
   36155 ** sqlite3_file for win32.
   36156 */
   36157 static const sqlite3_io_methods winIoMethod = {
   36158   3,                              /* iVersion */
   36159   winClose,                       /* xClose */
   36160   winRead,                        /* xRead */
   36161   winWrite,                       /* xWrite */
   36162   winTruncate,                    /* xTruncate */
   36163   winSync,                        /* xSync */
   36164   winFileSize,                    /* xFileSize */
   36165   winLock,                        /* xLock */
   36166   winUnlock,                      /* xUnlock */
   36167   winCheckReservedLock,           /* xCheckReservedLock */
   36168   winFileControl,                 /* xFileControl */
   36169   winSectorSize,                  /* xSectorSize */
   36170   winDeviceCharacteristics,       /* xDeviceCharacteristics */
   36171   winShmMap,                      /* xShmMap */
   36172   winShmLock,                     /* xShmLock */
   36173   winShmBarrier,                  /* xShmBarrier */
   36174   winShmUnmap,                    /* xShmUnmap */
   36175   winFetch,                       /* xFetch */
   36176   winUnfetch                      /* xUnfetch */
   36177 };
   36178 
   36179 /****************************************************************************
   36180 **************************** sqlite3_vfs methods ****************************
   36181 **
   36182 ** This division contains the implementation of methods on the
   36183 ** sqlite3_vfs object.
   36184 */
   36185 
   36186 #if defined(__CYGWIN__)
   36187 /*
   36188 ** Convert a filename from whatever the underlying operating system
   36189 ** supports for filenames into UTF-8.  Space to hold the result is
   36190 ** obtained from malloc and must be freed by the calling function.
   36191 */
   36192 static char *winConvertToUtf8Filename(const void *zFilename){
   36193   char *zConverted = 0;
   36194   if( osIsNT() ){
   36195     zConverted = winUnicodeToUtf8(zFilename);
   36196   }
   36197 #ifdef SQLITE_WIN32_HAS_ANSI
   36198   else{
   36199     zConverted = sqlite3_win32_mbcs_to_utf8(zFilename);
   36200   }
   36201 #endif
   36202   /* caller will handle out of memory */
   36203   return zConverted;
   36204 }
   36205 #endif
   36206 
   36207 /*
   36208 ** Convert a UTF-8 filename into whatever form the underlying
   36209 ** operating system wants filenames in.  Space to hold the result
   36210 ** is obtained from malloc and must be freed by the calling
   36211 ** function.
   36212 */
   36213 static void *winConvertFromUtf8Filename(const char *zFilename){
   36214   void *zConverted = 0;
   36215   if( osIsNT() ){
   36216     zConverted = winUtf8ToUnicode(zFilename);
   36217   }
   36218 #ifdef SQLITE_WIN32_HAS_ANSI
   36219   else{
   36220     zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
   36221   }
   36222 #endif
   36223   /* caller will handle out of memory */
   36224   return zConverted;
   36225 }
   36226 
   36227 /*
   36228 ** This function returns non-zero if the specified UTF-8 string buffer
   36229 ** ends with a directory separator character or one was successfully
   36230 ** added to it.
   36231 */
   36232 static int winMakeEndInDirSep(int nBuf, char *zBuf){
   36233   if( zBuf ){
   36234     int nLen = sqlite3Strlen30(zBuf);
   36235     if( nLen>0 ){
   36236       if( winIsDirSep(zBuf[nLen-1]) ){
   36237         return 1;
   36238       }else if( nLen+1<nBuf ){
   36239         zBuf[nLen] = winGetDirSep();
   36240         zBuf[nLen+1] = '\0';
   36241         return 1;
   36242       }
   36243     }
   36244   }
   36245   return 0;
   36246 }
   36247 
   36248 /*
   36249 ** Create a temporary file name and store the resulting pointer into pzBuf.
   36250 ** The pointer returned in pzBuf must be freed via sqlite3_free().
   36251 */
   36252 static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
   36253   static char zChars[] =
   36254     "abcdefghijklmnopqrstuvwxyz"
   36255     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
   36256     "0123456789";
   36257   size_t i, j;
   36258   int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
   36259   int nMax, nBuf, nDir, nLen;
   36260   char *zBuf;
   36261 
   36262   /* It's odd to simulate an io-error here, but really this is just
   36263   ** using the io-error infrastructure to test that SQLite handles this
   36264   ** function failing.
   36265   */
   36266   SimulateIOError( return SQLITE_IOERR );
   36267 
   36268   /* Allocate a temporary buffer to store the fully qualified file
   36269   ** name for the temporary file.  If this fails, we cannot continue.
   36270   */
   36271   nMax = pVfs->mxPathname; nBuf = nMax + 2;
   36272   zBuf = sqlite3MallocZero( nBuf );
   36273   if( !zBuf ){
   36274     OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
   36275     return SQLITE_IOERR_NOMEM;
   36276   }
   36277 
   36278   /* Figure out the effective temporary directory.  First, check if one
   36279   ** has been explicitly set by the application; otherwise, use the one
   36280   ** configured by the operating system.
   36281   */
   36282   nDir = nMax - (nPre + 15);
   36283   assert( nDir>0 );
   36284   if( sqlite3_temp_directory ){
   36285     int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
   36286     if( nDirLen>0 ){
   36287       if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
   36288         nDirLen++;
   36289       }
   36290       if( nDirLen>nDir ){
   36291         sqlite3_free(zBuf);
   36292         OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
   36293         return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
   36294       }
   36295       sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
   36296     }
   36297   }
   36298 #if defined(__CYGWIN__)
   36299   else{
   36300     static const char *azDirs[] = {
   36301        0, /* getenv("SQLITE_TMPDIR") */
   36302        0, /* getenv("TMPDIR") */
   36303        0, /* getenv("TMP") */
   36304        0, /* getenv("TEMP") */
   36305        0, /* getenv("USERPROFILE") */
   36306        "/var/tmp",
   36307        "/usr/tmp",
   36308        "/tmp",
   36309        ".",
   36310        0        /* List terminator */
   36311     };
   36312     unsigned int i;
   36313     const char *zDir = 0;
   36314 
   36315     if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
   36316     if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
   36317     if( !azDirs[2] ) azDirs[2] = getenv("TMP");
   36318     if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
   36319     if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
   36320     for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
   36321       void *zConverted;
   36322       if( zDir==0 ) continue;
   36323       /* If the path starts with a drive letter followed by the colon
   36324       ** character, assume it is already a native Win32 path; otherwise,
   36325       ** it must be converted to a native Win32 path via the Cygwin API
   36326       ** prior to using it.
   36327       */
   36328       if( winIsDriveLetterAndColon(zDir) ){
   36329         zConverted = winConvertFromUtf8Filename(zDir);
   36330         if( !zConverted ){
   36331           sqlite3_free(zBuf);
   36332           OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
   36333           return SQLITE_IOERR_NOMEM;
   36334         }
   36335         if( winIsDir(zConverted) ){
   36336           sqlite3_snprintf(nMax, zBuf, "%s", zDir);
   36337           sqlite3_free(zConverted);
   36338           break;
   36339         }
   36340         sqlite3_free(zConverted);
   36341       }else{
   36342         zConverted = sqlite3MallocZero( nMax+1 );
   36343         if( !zConverted ){
   36344           sqlite3_free(zBuf);
   36345           OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
   36346           return SQLITE_IOERR_NOMEM;
   36347         }
   36348         if( cygwin_conv_path(
   36349                 osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
   36350                 zConverted, nMax+1)<0 ){
   36351           sqlite3_free(zConverted);
   36352           sqlite3_free(zBuf);
   36353           OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
   36354           return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
   36355                              "winGetTempname2", zDir);
   36356         }
   36357         if( winIsDir(zConverted) ){
   36358           /* At this point, we know the candidate directory exists and should
   36359           ** be used.  However, we may need to convert the string containing
   36360           ** its name into UTF-8 (i.e. if it is UTF-16 right now).
   36361           */
   36362           char *zUtf8 = winConvertToUtf8Filename(zConverted);
   36363           if( !zUtf8 ){
   36364             sqlite3_free(zConverted);
   36365             sqlite3_free(zBuf);
   36366             OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
   36367             return SQLITE_IOERR_NOMEM;
   36368           }
   36369           sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
   36370           sqlite3_free(zUtf8);
   36371           sqlite3_free(zConverted);
   36372           break;
   36373         }
   36374         sqlite3_free(zConverted);
   36375       }
   36376     }
   36377   }
   36378 #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
   36379   else if( osIsNT() ){
   36380     char *zMulti;
   36381     LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
   36382     if( !zWidePath ){
   36383       sqlite3_free(zBuf);
   36384       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
   36385       return SQLITE_IOERR_NOMEM;
   36386     }
   36387     if( osGetTempPathW(nMax, zWidePath)==0 ){
   36388       sqlite3_free(zWidePath);
   36389       sqlite3_free(zBuf);
   36390       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
   36391       return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
   36392                          "winGetTempname2", 0);
   36393     }
   36394     zMulti = winUnicodeToUtf8(zWidePath);
   36395     if( zMulti ){
   36396       sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
   36397       sqlite3_free(zMulti);
   36398       sqlite3_free(zWidePath);
   36399     }else{
   36400       sqlite3_free(zWidePath);
   36401       sqlite3_free(zBuf);
   36402       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
   36403       return SQLITE_IOERR_NOMEM;
   36404     }
   36405   }
   36406 #ifdef SQLITE_WIN32_HAS_ANSI
   36407   else{
   36408     char *zUtf8;
   36409     char *zMbcsPath = sqlite3MallocZero( nMax );
   36410     if( !zMbcsPath ){
   36411       sqlite3_free(zBuf);
   36412       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
   36413       return SQLITE_IOERR_NOMEM;
   36414     }
   36415     if( osGetTempPathA(nMax, zMbcsPath)==0 ){
   36416       sqlite3_free(zBuf);
   36417       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
   36418       return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
   36419                          "winGetTempname3", 0);
   36420     }
   36421     zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
   36422     if( zUtf8 ){
   36423       sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
   36424       sqlite3_free(zUtf8);
   36425     }else{
   36426       sqlite3_free(zBuf);
   36427       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
   36428       return SQLITE_IOERR_NOMEM;
   36429     }
   36430   }
   36431 #endif /* SQLITE_WIN32_HAS_ANSI */
   36432 #endif /* !SQLITE_OS_WINRT */
   36433 
   36434   /*
   36435   ** Check to make sure the temporary directory ends with an appropriate
   36436   ** separator.  If it does not and there is not enough space left to add
   36437   ** one, fail.
   36438   */
   36439   if( !winMakeEndInDirSep(nDir+1, zBuf) ){
   36440     sqlite3_free(zBuf);
   36441     OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
   36442     return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
   36443   }
   36444 
   36445   /*
   36446   ** Check that the output buffer is large enough for the temporary file
   36447   ** name in the following format:
   36448   **
   36449   **   "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
   36450   **
   36451   ** If not, return SQLITE_ERROR.  The number 17 is used here in order to
   36452   ** account for the space used by the 15 character random suffix and the
   36453   ** two trailing NUL characters.  The final directory separator character
   36454   ** has already added if it was not already present.
   36455   */
   36456   nLen = sqlite3Strlen30(zBuf);
   36457   if( (nLen + nPre + 17) > nBuf ){
   36458     sqlite3_free(zBuf);
   36459     OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
   36460     return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
   36461   }
   36462 
   36463   sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
   36464 
   36465   j = sqlite3Strlen30(zBuf);
   36466   sqlite3_randomness(15, &zBuf[j]);
   36467   for(i=0; i<15; i++, j++){
   36468     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
   36469   }
   36470   zBuf[j] = 0;
   36471   zBuf[j+1] = 0;
   36472   *pzBuf = zBuf;
   36473 
   36474   OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
   36475   return SQLITE_OK;
   36476 }
   36477 
   36478 /*
   36479 ** Return TRUE if the named file is really a directory.  Return false if
   36480 ** it is something other than a directory, or if there is any kind of memory
   36481 ** allocation failure.
   36482 */
   36483 static int winIsDir(const void *zConverted){
   36484   DWORD attr;
   36485   int rc = 0;
   36486   DWORD lastErrno;
   36487 
   36488   if( osIsNT() ){
   36489     int cnt = 0;
   36490     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
   36491     memset(&sAttrData, 0, sizeof(sAttrData));
   36492     while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
   36493                              GetFileExInfoStandard,
   36494                              &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
   36495     if( !rc ){
   36496       return 0; /* Invalid name? */
   36497     }
   36498     attr = sAttrData.dwFileAttributes;
   36499 #if SQLITE_OS_WINCE==0
   36500   }else{
   36501     attr = osGetFileAttributesA((char*)zConverted);
   36502 #endif
   36503   }
   36504   return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
   36505 }
   36506 
   36507 /*
   36508 ** Open a file.
   36509 */
   36510 static int winOpen(
   36511   sqlite3_vfs *pVfs,        /* Used to get maximum path name length */
   36512   const char *zName,        /* Name of the file (UTF-8) */
   36513   sqlite3_file *id,         /* Write the SQLite file handle here */
   36514   int flags,                /* Open mode flags */
   36515   int *pOutFlags            /* Status return flags */
   36516 ){
   36517   HANDLE h;
   36518   DWORD lastErrno = 0;
   36519   DWORD dwDesiredAccess;
   36520   DWORD dwShareMode;
   36521   DWORD dwCreationDisposition;
   36522   DWORD dwFlagsAndAttributes = 0;
   36523 #if SQLITE_OS_WINCE
   36524   int isTemp = 0;
   36525 #endif
   36526   winFile *pFile = (winFile*)id;
   36527   void *zConverted;              /* Filename in OS encoding */
   36528   const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
   36529   int cnt = 0;
   36530 
   36531   /* If argument zPath is a NULL pointer, this function is required to open
   36532   ** a temporary file. Use this buffer to store the file name in.
   36533   */
   36534   char *zTmpname = 0; /* For temporary filename, if necessary. */
   36535 
   36536   int rc = SQLITE_OK;            /* Function Return Code */
   36537 #if !defined(NDEBUG) || SQLITE_OS_WINCE
   36538   int eType = flags&0xFFFFFF00;  /* Type of file to open */
   36539 #endif
   36540 
   36541   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
   36542   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
   36543   int isCreate     = (flags & SQLITE_OPEN_CREATE);
   36544   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
   36545   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
   36546 
   36547 #ifndef NDEBUG
   36548   int isOpenJournal = (isCreate && (
   36549         eType==SQLITE_OPEN_MASTER_JOURNAL
   36550      || eType==SQLITE_OPEN_MAIN_JOURNAL
   36551      || eType==SQLITE_OPEN_WAL
   36552   ));
   36553 #endif
   36554 
   36555   OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
   36556            zUtf8Name, id, flags, pOutFlags));
   36557 
   36558   /* Check the following statements are true:
   36559   **
   36560   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
   36561   **   (b) if CREATE is set, then READWRITE must also be set, and
   36562   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
   36563   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
   36564   */
   36565   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
   36566   assert(isCreate==0 || isReadWrite);
   36567   assert(isExclusive==0 || isCreate);
   36568   assert(isDelete==0 || isCreate);
   36569 
   36570   /* The main DB, main journal, WAL file and master journal are never
   36571   ** automatically deleted. Nor are they ever temporary files.  */
   36572   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
   36573   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
   36574   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
   36575   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
   36576 
   36577   /* Assert that the upper layer has set one of the "file-type" flags. */
   36578   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
   36579        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
   36580        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
   36581        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
   36582   );
   36583 
   36584   assert( pFile!=0 );
   36585   memset(pFile, 0, sizeof(winFile));
   36586   pFile->h = INVALID_HANDLE_VALUE;
   36587 
   36588 #if SQLITE_OS_WINRT
   36589   if( !zUtf8Name && !sqlite3_temp_directory ){
   36590     sqlite3_log(SQLITE_ERROR,
   36591         "sqlite3_temp_directory variable should be set for WinRT");
   36592   }
   36593 #endif
   36594 
   36595   /* If the second argument to this function is NULL, generate a
   36596   ** temporary file name to use
   36597   */
   36598   if( !zUtf8Name ){
   36599     assert( isDelete && !isOpenJournal );
   36600     rc = winGetTempname(pVfs, &zTmpname);
   36601     if( rc!=SQLITE_OK ){
   36602       OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
   36603       return rc;
   36604     }
   36605     zUtf8Name = zTmpname;
   36606   }
   36607 
   36608   /* Database filenames are double-zero terminated if they are not
   36609   ** URIs with parameters.  Hence, they can always be passed into
   36610   ** sqlite3_uri_parameter().
   36611   */
   36612   assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
   36613        zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
   36614 
   36615   /* Convert the filename to the system encoding. */
   36616   zConverted = winConvertFromUtf8Filename(zUtf8Name);
   36617   if( zConverted==0 ){
   36618     sqlite3_free(zTmpname);
   36619     OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
   36620     return SQLITE_IOERR_NOMEM;
   36621   }
   36622 
   36623   if( winIsDir(zConverted) ){
   36624     sqlite3_free(zConverted);
   36625     sqlite3_free(zTmpname);
   36626     OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
   36627     return SQLITE_CANTOPEN_ISDIR;
   36628   }
   36629 
   36630   if( isReadWrite ){
   36631     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
   36632   }else{
   36633     dwDesiredAccess = GENERIC_READ;
   36634   }
   36635 
   36636   /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
   36637   ** created. SQLite doesn't use it to indicate "exclusive access"
   36638   ** as it is usually understood.
   36639   */
   36640   if( isExclusive ){
   36641     /* Creates a new file, only if it does not already exist. */
   36642     /* If the file exists, it fails. */
   36643     dwCreationDisposition = CREATE_NEW;
   36644   }else if( isCreate ){
   36645     /* Open existing file, or create if it doesn't exist */
   36646     dwCreationDisposition = OPEN_ALWAYS;
   36647   }else{
   36648     /* Opens a file, only if it exists. */
   36649     dwCreationDisposition = OPEN_EXISTING;
   36650   }
   36651 
   36652   dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
   36653 
   36654   if( isDelete ){
   36655 #if SQLITE_OS_WINCE
   36656     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
   36657     isTemp = 1;
   36658 #else
   36659     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
   36660                                | FILE_ATTRIBUTE_HIDDEN
   36661                                | FILE_FLAG_DELETE_ON_CLOSE;
   36662 #endif
   36663   }else{
   36664     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
   36665   }
   36666   /* Reports from the internet are that performance is always
   36667   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
   36668 #if SQLITE_OS_WINCE
   36669   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
   36670 #endif
   36671 
   36672   if( osIsNT() ){
   36673 #if SQLITE_OS_WINRT
   36674     CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
   36675     extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
   36676     extendedParameters.dwFileAttributes =
   36677             dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
   36678     extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
   36679     extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
   36680     extendedParameters.lpSecurityAttributes = NULL;
   36681     extendedParameters.hTemplateFile = NULL;
   36682     while( (h = osCreateFile2((LPCWSTR)zConverted,
   36683                               dwDesiredAccess,
   36684                               dwShareMode,
   36685                               dwCreationDisposition,
   36686                               &extendedParameters))==INVALID_HANDLE_VALUE &&
   36687                               winRetryIoerr(&cnt, &lastErrno) ){
   36688                /* Noop */
   36689     }
   36690 #else
   36691     while( (h = osCreateFileW((LPCWSTR)zConverted,
   36692                               dwDesiredAccess,
   36693                               dwShareMode, NULL,
   36694                               dwCreationDisposition,
   36695                               dwFlagsAndAttributes,
   36696                               NULL))==INVALID_HANDLE_VALUE &&
   36697                               winRetryIoerr(&cnt, &lastErrno) ){
   36698                /* Noop */
   36699     }
   36700 #endif
   36701   }
   36702 #ifdef SQLITE_WIN32_HAS_ANSI
   36703   else{
   36704     while( (h = osCreateFileA((LPCSTR)zConverted,
   36705                               dwDesiredAccess,
   36706                               dwShareMode, NULL,
   36707                               dwCreationDisposition,
   36708                               dwFlagsAndAttributes,
   36709                               NULL))==INVALID_HANDLE_VALUE &&
   36710                               winRetryIoerr(&cnt, &lastErrno) ){
   36711                /* Noop */
   36712     }
   36713   }
   36714 #endif
   36715   winLogIoerr(cnt);
   36716 
   36717   OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
   36718            dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
   36719 
   36720   if( h==INVALID_HANDLE_VALUE ){
   36721     pFile->lastErrno = lastErrno;
   36722     winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
   36723     sqlite3_free(zConverted);
   36724     sqlite3_free(zTmpname);
   36725     if( isReadWrite && !isExclusive ){
   36726       return winOpen(pVfs, zName, id,
   36727          ((flags|SQLITE_OPEN_READONLY) &
   36728                      ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
   36729          pOutFlags);
   36730     }else{
   36731       return SQLITE_CANTOPEN_BKPT;
   36732     }
   36733   }
   36734 
   36735   if( pOutFlags ){
   36736     if( isReadWrite ){
   36737       *pOutFlags = SQLITE_OPEN_READWRITE;
   36738     }else{
   36739       *pOutFlags = SQLITE_OPEN_READONLY;
   36740     }
   36741   }
   36742 
   36743   OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
   36744            "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
   36745            *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
   36746 
   36747 #if SQLITE_OS_WINCE
   36748   if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
   36749        && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
   36750   ){
   36751     osCloseHandle(h);
   36752     sqlite3_free(zConverted);
   36753     sqlite3_free(zTmpname);
   36754     OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
   36755     return rc;
   36756   }
   36757   if( isTemp ){
   36758     pFile->zDeleteOnClose = zConverted;
   36759   }else
   36760 #endif
   36761   {
   36762     sqlite3_free(zConverted);
   36763   }
   36764 
   36765   sqlite3_free(zTmpname);
   36766   pFile->pMethod = &winIoMethod;
   36767   pFile->pVfs = pVfs;
   36768   pFile->h = h;
   36769   if( isReadonly ){
   36770     pFile->ctrlFlags |= WINFILE_RDONLY;
   36771   }
   36772   if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
   36773     pFile->ctrlFlags |= WINFILE_PSOW;
   36774   }
   36775   pFile->lastErrno = NO_ERROR;
   36776   pFile->zPath = zName;
   36777 #if SQLITE_MAX_MMAP_SIZE>0
   36778   pFile->hMap = NULL;
   36779   pFile->pMapRegion = 0;
   36780   pFile->mmapSize = 0;
   36781   pFile->mmapSizeActual = 0;
   36782   pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
   36783 #endif
   36784 
   36785   OpenCounter(+1);
   36786   return rc;
   36787 }
   36788 
   36789 /*
   36790 ** Delete the named file.
   36791 **
   36792 ** Note that Windows does not allow a file to be deleted if some other
   36793 ** process has it open.  Sometimes a virus scanner or indexing program
   36794 ** will open a journal file shortly after it is created in order to do
   36795 ** whatever it does.  While this other process is holding the
   36796 ** file open, we will be unable to delete it.  To work around this
   36797 ** problem, we delay 100 milliseconds and try to delete again.  Up
   36798 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
   36799 ** up and returning an error.
   36800 */
   36801 static int winDelete(
   36802   sqlite3_vfs *pVfs,          /* Not used on win32 */
   36803   const char *zFilename,      /* Name of file to delete */
   36804   int syncDir                 /* Not used on win32 */
   36805 ){
   36806   int cnt = 0;
   36807   int rc;
   36808   DWORD attr;
   36809   DWORD lastErrno = 0;
   36810   void *zConverted;
   36811   UNUSED_PARAMETER(pVfs);
   36812   UNUSED_PARAMETER(syncDir);
   36813 
   36814   SimulateIOError(return SQLITE_IOERR_DELETE);
   36815   OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
   36816 
   36817   zConverted = winConvertFromUtf8Filename(zFilename);
   36818   if( zConverted==0 ){
   36819     OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
   36820     return SQLITE_IOERR_NOMEM;
   36821   }
   36822   if( osIsNT() ){
   36823     do {
   36824 #if SQLITE_OS_WINRT
   36825       WIN32_FILE_ATTRIBUTE_DATA sAttrData;
   36826       memset(&sAttrData, 0, sizeof(sAttrData));
   36827       if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
   36828                                   &sAttrData) ){
   36829         attr = sAttrData.dwFileAttributes;
   36830       }else{
   36831         lastErrno = osGetLastError();
   36832         if( lastErrno==ERROR_FILE_NOT_FOUND
   36833          || lastErrno==ERROR_PATH_NOT_FOUND ){
   36834           rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
   36835         }else{
   36836           rc = SQLITE_ERROR;
   36837         }
   36838         break;
   36839       }
   36840 #else
   36841       attr = osGetFileAttributesW(zConverted);
   36842 #endif
   36843       if ( attr==INVALID_FILE_ATTRIBUTES ){
   36844         lastErrno = osGetLastError();
   36845         if( lastErrno==ERROR_FILE_NOT_FOUND
   36846          || lastErrno==ERROR_PATH_NOT_FOUND ){
   36847           rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
   36848         }else{
   36849           rc = SQLITE_ERROR;
   36850         }
   36851         break;
   36852       }
   36853       if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
   36854         rc = SQLITE_ERROR; /* Files only. */
   36855         break;
   36856       }
   36857       if ( osDeleteFileW(zConverted) ){
   36858         rc = SQLITE_OK; /* Deleted OK. */
   36859         break;
   36860       }
   36861       if ( !winRetryIoerr(&cnt, &lastErrno) ){
   36862         rc = SQLITE_ERROR; /* No more retries. */
   36863         break;
   36864       }
   36865     } while(1);
   36866   }
   36867 #ifdef SQLITE_WIN32_HAS_ANSI
   36868   else{
   36869     do {
   36870       attr = osGetFileAttributesA(zConverted);
   36871       if ( attr==INVALID_FILE_ATTRIBUTES ){
   36872         lastErrno = osGetLastError();
   36873         if( lastErrno==ERROR_FILE_NOT_FOUND
   36874          || lastErrno==ERROR_PATH_NOT_FOUND ){
   36875           rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
   36876         }else{
   36877           rc = SQLITE_ERROR;
   36878         }
   36879         break;
   36880       }
   36881       if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
   36882         rc = SQLITE_ERROR; /* Files only. */
   36883         break;
   36884       }
   36885       if ( osDeleteFileA(zConverted) ){
   36886         rc = SQLITE_OK; /* Deleted OK. */
   36887         break;
   36888       }
   36889       if ( !winRetryIoerr(&cnt, &lastErrno) ){
   36890         rc = SQLITE_ERROR; /* No more retries. */
   36891         break;
   36892       }
   36893     } while(1);
   36894   }
   36895 #endif
   36896   if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
   36897     rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
   36898   }else{
   36899     winLogIoerr(cnt);
   36900   }
   36901   sqlite3_free(zConverted);
   36902   OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
   36903   return rc;
   36904 }
   36905 
   36906 /*
   36907 ** Check the existence and status of a file.
   36908 */
   36909 static int winAccess(
   36910   sqlite3_vfs *pVfs,         /* Not used on win32 */
   36911   const char *zFilename,     /* Name of file to check */
   36912   int flags,                 /* Type of test to make on this file */
   36913   int *pResOut               /* OUT: Result */
   36914 ){
   36915   DWORD attr;
   36916   int rc = 0;
   36917   DWORD lastErrno = 0;
   36918   void *zConverted;
   36919   UNUSED_PARAMETER(pVfs);
   36920 
   36921   SimulateIOError( return SQLITE_IOERR_ACCESS; );
   36922   OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
   36923            zFilename, flags, pResOut));
   36924 
   36925   zConverted = winConvertFromUtf8Filename(zFilename);
   36926   if( zConverted==0 ){
   36927     OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
   36928     return SQLITE_IOERR_NOMEM;
   36929   }
   36930   if( osIsNT() ){
   36931     int cnt = 0;
   36932     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
   36933     memset(&sAttrData, 0, sizeof(sAttrData));
   36934     while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
   36935                              GetFileExInfoStandard,
   36936                              &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
   36937     if( rc ){
   36938       /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
   36939       ** as if it does not exist.
   36940       */
   36941       if(    flags==SQLITE_ACCESS_EXISTS
   36942           && sAttrData.nFileSizeHigh==0
   36943           && sAttrData.nFileSizeLow==0 ){
   36944         attr = INVALID_FILE_ATTRIBUTES;
   36945       }else{
   36946         attr = sAttrData.dwFileAttributes;
   36947       }
   36948     }else{
   36949       winLogIoerr(cnt);
   36950       if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
   36951         sqlite3_free(zConverted);
   36952         return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
   36953                            zFilename);
   36954       }else{
   36955         attr = INVALID_FILE_ATTRIBUTES;
   36956       }
   36957     }
   36958   }
   36959 #ifdef SQLITE_WIN32_HAS_ANSI
   36960   else{
   36961     attr = osGetFileAttributesA((char*)zConverted);
   36962   }
   36963 #endif
   36964   sqlite3_free(zConverted);
   36965   switch( flags ){
   36966     case SQLITE_ACCESS_READ:
   36967     case SQLITE_ACCESS_EXISTS:
   36968       rc = attr!=INVALID_FILE_ATTRIBUTES;
   36969       break;
   36970     case SQLITE_ACCESS_READWRITE:
   36971       rc = attr!=INVALID_FILE_ATTRIBUTES &&
   36972              (attr & FILE_ATTRIBUTE_READONLY)==0;
   36973       break;
   36974     default:
   36975       assert(!"Invalid flags argument");
   36976   }
   36977   *pResOut = rc;
   36978   OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
   36979            zFilename, pResOut, *pResOut));
   36980   return SQLITE_OK;
   36981 }
   36982 
   36983 /*
   36984 ** Returns non-zero if the specified path name starts with a drive letter
   36985 ** followed by a colon character.
   36986 */
   36987 static BOOL winIsDriveLetterAndColon(
   36988   const char *zPathname
   36989 ){
   36990   return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
   36991 }
   36992 
   36993 /*
   36994 ** Returns non-zero if the specified path name should be used verbatim.  If
   36995 ** non-zero is returned from this function, the calling function must simply
   36996 ** use the provided path name verbatim -OR- resolve it into a full path name
   36997 ** using the GetFullPathName Win32 API function (if available).
   36998 */
   36999 static BOOL winIsVerbatimPathname(
   37000   const char *zPathname
   37001 ){
   37002   /*
   37003   ** If the path name starts with a forward slash or a backslash, it is either
   37004   ** a legal UNC name, a volume relative path, or an absolute path name in the
   37005   ** "Unix" format on Windows.  There is no easy way to differentiate between
   37006   ** the final two cases; therefore, we return the safer return value of TRUE
   37007   ** so that callers of this function will simply use it verbatim.
   37008   */
   37009   if ( winIsDirSep(zPathname[0]) ){
   37010     return TRUE;
   37011   }
   37012 
   37013   /*
   37014   ** If the path name starts with a letter and a colon it is either a volume
   37015   ** relative path or an absolute path.  Callers of this function must not
   37016   ** attempt to treat it as a relative path name (i.e. they should simply use
   37017   ** it verbatim).
   37018   */
   37019   if ( winIsDriveLetterAndColon(zPathname) ){
   37020     return TRUE;
   37021   }
   37022 
   37023   /*
   37024   ** If we get to this point, the path name should almost certainly be a purely
   37025   ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
   37026   */
   37027   return FALSE;
   37028 }
   37029 
   37030 /*
   37031 ** Turn a relative pathname into a full pathname.  Write the full
   37032 ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
   37033 ** bytes in size.
   37034 */
   37035 static int winFullPathname(
   37036   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
   37037   const char *zRelative,        /* Possibly relative input path */
   37038   int nFull,                    /* Size of output buffer in bytes */
   37039   char *zFull                   /* Output buffer */
   37040 ){
   37041 
   37042 #if defined(__CYGWIN__)
   37043   SimulateIOError( return SQLITE_ERROR );
   37044   UNUSED_PARAMETER(nFull);
   37045   assert( nFull>=pVfs->mxPathname );
   37046   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
   37047     /*
   37048     ** NOTE: We are dealing with a relative path name and the data
   37049     **       directory has been set.  Therefore, use it as the basis
   37050     **       for converting the relative path name to an absolute
   37051     **       one by prepending the data directory and a slash.
   37052     */
   37053     char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
   37054     if( !zOut ){
   37055       return SQLITE_IOERR_NOMEM;
   37056     }
   37057     if( cygwin_conv_path(
   37058             (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
   37059             CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
   37060       sqlite3_free(zOut);
   37061       return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
   37062                          "winFullPathname1", zRelative);
   37063     }else{
   37064       char *zUtf8 = winConvertToUtf8Filename(zOut);
   37065       if( !zUtf8 ){
   37066         sqlite3_free(zOut);
   37067         return SQLITE_IOERR_NOMEM;
   37068       }
   37069       sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
   37070                        sqlite3_data_directory, winGetDirSep(), zUtf8);
   37071       sqlite3_free(zUtf8);
   37072       sqlite3_free(zOut);
   37073     }
   37074   }else{
   37075     char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
   37076     if( !zOut ){
   37077       return SQLITE_IOERR_NOMEM;
   37078     }
   37079     if( cygwin_conv_path(
   37080             (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
   37081             zRelative, zOut, pVfs->mxPathname+1)<0 ){
   37082       sqlite3_free(zOut);
   37083       return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
   37084                          "winFullPathname2", zRelative);
   37085     }else{
   37086       char *zUtf8 = winConvertToUtf8Filename(zOut);
   37087       if( !zUtf8 ){
   37088         sqlite3_free(zOut);
   37089         return SQLITE_IOERR_NOMEM;
   37090       }
   37091       sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
   37092       sqlite3_free(zUtf8);
   37093       sqlite3_free(zOut);
   37094     }
   37095   }
   37096   return SQLITE_OK;
   37097 #endif
   37098 
   37099 #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
   37100   SimulateIOError( return SQLITE_ERROR );
   37101   /* WinCE has no concept of a relative pathname, or so I am told. */
   37102   /* WinRT has no way to convert a relative path to an absolute one. */
   37103   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
   37104     /*
   37105     ** NOTE: We are dealing with a relative path name and the data
   37106     **       directory has been set.  Therefore, use it as the basis
   37107     **       for converting the relative path name to an absolute
   37108     **       one by prepending the data directory and a backslash.
   37109     */
   37110     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
   37111                      sqlite3_data_directory, winGetDirSep(), zRelative);
   37112   }else{
   37113     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
   37114   }
   37115   return SQLITE_OK;
   37116 #endif
   37117 
   37118 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
   37119   DWORD nByte;
   37120   void *zConverted;
   37121   char *zOut;
   37122 
   37123   /* If this path name begins with "/X:", where "X" is any alphabetic
   37124   ** character, discard the initial "/" from the pathname.
   37125   */
   37126   if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
   37127     zRelative++;
   37128   }
   37129 
   37130   /* It's odd to simulate an io-error here, but really this is just
   37131   ** using the io-error infrastructure to test that SQLite handles this
   37132   ** function failing. This function could fail if, for example, the
   37133   ** current working directory has been unlinked.
   37134   */
   37135   SimulateIOError( return SQLITE_ERROR );
   37136   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
   37137     /*
   37138     ** NOTE: We are dealing with a relative path name and the data
   37139     **       directory has been set.  Therefore, use it as the basis
   37140     **       for converting the relative path name to an absolute
   37141     **       one by prepending the data directory and a backslash.
   37142     */
   37143     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
   37144                      sqlite3_data_directory, winGetDirSep(), zRelative);
   37145     return SQLITE_OK;
   37146   }
   37147   zConverted = winConvertFromUtf8Filename(zRelative);
   37148   if( zConverted==0 ){
   37149     return SQLITE_IOERR_NOMEM;
   37150   }
   37151   if( osIsNT() ){
   37152     LPWSTR zTemp;
   37153     nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
   37154     if( nByte==0 ){
   37155       sqlite3_free(zConverted);
   37156       return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
   37157                          "winFullPathname1", zRelative);
   37158     }
   37159     nByte += 3;
   37160     zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
   37161     if( zTemp==0 ){
   37162       sqlite3_free(zConverted);
   37163       return SQLITE_IOERR_NOMEM;
   37164     }
   37165     nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
   37166     if( nByte==0 ){
   37167       sqlite3_free(zConverted);
   37168       sqlite3_free(zTemp);
   37169       return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
   37170                          "winFullPathname2", zRelative);
   37171     }
   37172     sqlite3_free(zConverted);
   37173     zOut = winUnicodeToUtf8(zTemp);
   37174     sqlite3_free(zTemp);
   37175   }
   37176 #ifdef SQLITE_WIN32_HAS_ANSI
   37177   else{
   37178     char *zTemp;
   37179     nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
   37180     if( nByte==0 ){
   37181       sqlite3_free(zConverted);
   37182       return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
   37183                          "winFullPathname3", zRelative);
   37184     }
   37185     nByte += 3;
   37186     zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
   37187     if( zTemp==0 ){
   37188       sqlite3_free(zConverted);
   37189       return SQLITE_IOERR_NOMEM;
   37190     }
   37191     nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
   37192     if( nByte==0 ){
   37193       sqlite3_free(zConverted);
   37194       sqlite3_free(zTemp);
   37195       return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
   37196                          "winFullPathname4", zRelative);
   37197     }
   37198     sqlite3_free(zConverted);
   37199     zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
   37200     sqlite3_free(zTemp);
   37201   }
   37202 #endif
   37203   if( zOut ){
   37204     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
   37205     sqlite3_free(zOut);
   37206     return SQLITE_OK;
   37207   }else{
   37208     return SQLITE_IOERR_NOMEM;
   37209   }
   37210 #endif
   37211 }
   37212 
   37213 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   37214 /*
   37215 ** Interfaces for opening a shared library, finding entry points
   37216 ** within the shared library, and closing the shared library.
   37217 */
   37218 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
   37219   HANDLE h;
   37220 #if defined(__CYGWIN__)
   37221   int nFull = pVfs->mxPathname+1;
   37222   char *zFull = sqlite3MallocZero( nFull );
   37223   void *zConverted = 0;
   37224   if( zFull==0 ){
   37225     OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
   37226     return 0;
   37227   }
   37228   if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
   37229     sqlite3_free(zFull);
   37230     OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
   37231     return 0;
   37232   }
   37233   zConverted = winConvertFromUtf8Filename(zFull);
   37234   sqlite3_free(zFull);
   37235 #else
   37236   void *zConverted = winConvertFromUtf8Filename(zFilename);
   37237   UNUSED_PARAMETER(pVfs);
   37238 #endif
   37239   if( zConverted==0 ){
   37240     OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
   37241     return 0;
   37242   }
   37243   if( osIsNT() ){
   37244 #if SQLITE_OS_WINRT
   37245     h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
   37246 #else
   37247     h = osLoadLibraryW((LPCWSTR)zConverted);
   37248 #endif
   37249   }
   37250 #ifdef SQLITE_WIN32_HAS_ANSI
   37251   else{
   37252     h = osLoadLibraryA((char*)zConverted);
   37253   }
   37254 #endif
   37255   OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
   37256   sqlite3_free(zConverted);
   37257   return (void*)h;
   37258 }
   37259 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
   37260   UNUSED_PARAMETER(pVfs);
   37261   winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
   37262 }
   37263 static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
   37264   FARPROC proc;
   37265   UNUSED_PARAMETER(pVfs);
   37266   proc = osGetProcAddressA((HANDLE)pH, zSym);
   37267   OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
   37268            (void*)pH, zSym, (void*)proc));
   37269   return (void(*)(void))proc;
   37270 }
   37271 static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
   37272   UNUSED_PARAMETER(pVfs);
   37273   osFreeLibrary((HANDLE)pHandle);
   37274   OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
   37275 }
   37276 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
   37277   #define winDlOpen  0
   37278   #define winDlError 0
   37279   #define winDlSym   0
   37280   #define winDlClose 0
   37281 #endif
   37282 
   37283 
   37284 /*
   37285 ** Write up to nBuf bytes of randomness into zBuf.
   37286 */
   37287 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
   37288   int n = 0;
   37289   UNUSED_PARAMETER(pVfs);
   37290 #if defined(SQLITE_TEST)
   37291   n = nBuf;
   37292   memset(zBuf, 0, nBuf);
   37293 #else
   37294   if( sizeof(SYSTEMTIME)<=nBuf-n ){
   37295     SYSTEMTIME x;
   37296     osGetSystemTime(&x);
   37297     memcpy(&zBuf[n], &x, sizeof(x));
   37298     n += sizeof(x);
   37299   }
   37300   if( sizeof(DWORD)<=nBuf-n ){
   37301     DWORD pid = osGetCurrentProcessId();
   37302     memcpy(&zBuf[n], &pid, sizeof(pid));
   37303     n += sizeof(pid);
   37304   }
   37305 #if SQLITE_OS_WINRT
   37306   if( sizeof(ULONGLONG)<=nBuf-n ){
   37307     ULONGLONG cnt = osGetTickCount64();
   37308     memcpy(&zBuf[n], &cnt, sizeof(cnt));
   37309     n += sizeof(cnt);
   37310   }
   37311 #else
   37312   if( sizeof(DWORD)<=nBuf-n ){
   37313     DWORD cnt = osGetTickCount();
   37314     memcpy(&zBuf[n], &cnt, sizeof(cnt));
   37315     n += sizeof(cnt);
   37316   }
   37317 #endif
   37318   if( sizeof(LARGE_INTEGER)<=nBuf-n ){
   37319     LARGE_INTEGER i;
   37320     osQueryPerformanceCounter(&i);
   37321     memcpy(&zBuf[n], &i, sizeof(i));
   37322     n += sizeof(i);
   37323   }
   37324 #endif
   37325   return n;
   37326 }
   37327 
   37328 
   37329 /*
   37330 ** Sleep for a little while.  Return the amount of time slept.
   37331 */
   37332 static int winSleep(sqlite3_vfs *pVfs, int microsec){
   37333   sqlite3_win32_sleep((microsec+999)/1000);
   37334   UNUSED_PARAMETER(pVfs);
   37335   return ((microsec+999)/1000)*1000;
   37336 }
   37337 
   37338 /*
   37339 ** The following variable, if set to a non-zero value, is interpreted as
   37340 ** the number of seconds since 1970 and is used to set the result of
   37341 ** sqlite3OsCurrentTime() during testing.
   37342 */
   37343 #ifdef SQLITE_TEST
   37344 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
   37345 #endif
   37346 
   37347 /*
   37348 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
   37349 ** the current time and date as a Julian Day number times 86_400_000.  In
   37350 ** other words, write into *piNow the number of milliseconds since the Julian
   37351 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
   37352 ** proleptic Gregorian calendar.
   37353 **
   37354 ** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
   37355 ** cannot be found.
   37356 */
   37357 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
   37358   /* FILETIME structure is a 64-bit value representing the number of
   37359      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
   37360   */
   37361   FILETIME ft;
   37362   static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
   37363 #ifdef SQLITE_TEST
   37364   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
   37365 #endif
   37366   /* 2^32 - to avoid use of LL and warnings in gcc */
   37367   static const sqlite3_int64 max32BitValue =
   37368       (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
   37369       (sqlite3_int64)294967296;
   37370 
   37371 #if SQLITE_OS_WINCE
   37372   SYSTEMTIME time;
   37373   osGetSystemTime(&time);
   37374   /* if SystemTimeToFileTime() fails, it returns zero. */
   37375   if (!osSystemTimeToFileTime(&time,&ft)){
   37376     return SQLITE_ERROR;
   37377   }
   37378 #else
   37379   osGetSystemTimeAsFileTime( &ft );
   37380 #endif
   37381 
   37382   *piNow = winFiletimeEpoch +
   37383             ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
   37384                (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
   37385 
   37386 #ifdef SQLITE_TEST
   37387   if( sqlite3_current_time ){
   37388     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
   37389   }
   37390 #endif
   37391   UNUSED_PARAMETER(pVfs);
   37392   return SQLITE_OK;
   37393 }
   37394 
   37395 /*
   37396 ** Find the current time (in Universal Coordinated Time).  Write the
   37397 ** current time and date as a Julian Day number into *prNow and
   37398 ** return 0.  Return 1 if the time and date cannot be found.
   37399 */
   37400 static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
   37401   int rc;
   37402   sqlite3_int64 i;
   37403   rc = winCurrentTimeInt64(pVfs, &i);
   37404   if( !rc ){
   37405     *prNow = i/86400000.0;
   37406   }
   37407   return rc;
   37408 }
   37409 
   37410 /*
   37411 ** The idea is that this function works like a combination of
   37412 ** GetLastError() and FormatMessage() on Windows (or errno and
   37413 ** strerror_r() on Unix). After an error is returned by an OS
   37414 ** function, SQLite calls this function with zBuf pointing to
   37415 ** a buffer of nBuf bytes. The OS layer should populate the
   37416 ** buffer with a nul-terminated UTF-8 encoded error message
   37417 ** describing the last IO error to have occurred within the calling
   37418 ** thread.
   37419 **
   37420 ** If the error message is too large for the supplied buffer,
   37421 ** it should be truncated. The return value of xGetLastError
   37422 ** is zero if the error message fits in the buffer, or non-zero
   37423 ** otherwise (if the message was truncated). If non-zero is returned,
   37424 ** then it is not necessary to include the nul-terminator character
   37425 ** in the output buffer.
   37426 **
   37427 ** Not supplying an error message will have no adverse effect
   37428 ** on SQLite. It is fine to have an implementation that never
   37429 ** returns an error message:
   37430 **
   37431 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
   37432 **     assert(zBuf[0]=='\0');
   37433 **     return 0;
   37434 **   }
   37435 **
   37436 ** However if an error message is supplied, it will be incorporated
   37437 ** by sqlite into the error message available to the user using
   37438 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
   37439 */
   37440 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
   37441   UNUSED_PARAMETER(pVfs);
   37442   return winGetLastErrorMsg(osGetLastError(), nBuf, zBuf);
   37443 }
   37444 
   37445 /*
   37446 ** Initialize and deinitialize the operating system interface.
   37447 */
   37448 SQLITE_API int sqlite3_os_init(void){
   37449   static sqlite3_vfs winVfs = {
   37450     3,                   /* iVersion */
   37451     sizeof(winFile),     /* szOsFile */
   37452     SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
   37453     0,                   /* pNext */
   37454     "win32",             /* zName */
   37455     0,                   /* pAppData */
   37456     winOpen,             /* xOpen */
   37457     winDelete,           /* xDelete */
   37458     winAccess,           /* xAccess */
   37459     winFullPathname,     /* xFullPathname */
   37460     winDlOpen,           /* xDlOpen */
   37461     winDlError,          /* xDlError */
   37462     winDlSym,            /* xDlSym */
   37463     winDlClose,          /* xDlClose */
   37464     winRandomness,       /* xRandomness */
   37465     winSleep,            /* xSleep */
   37466     winCurrentTime,      /* xCurrentTime */
   37467     winGetLastError,     /* xGetLastError */
   37468     winCurrentTimeInt64, /* xCurrentTimeInt64 */
   37469     winSetSystemCall,    /* xSetSystemCall */
   37470     winGetSystemCall,    /* xGetSystemCall */
   37471     winNextSystemCall,   /* xNextSystemCall */
   37472   };
   37473 #if defined(SQLITE_WIN32_HAS_WIDE)
   37474   static sqlite3_vfs winLongPathVfs = {
   37475     3,                   /* iVersion */
   37476     sizeof(winFile),     /* szOsFile */
   37477     SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
   37478     0,                   /* pNext */
   37479     "win32-longpath",    /* zName */
   37480     0,                   /* pAppData */
   37481     winOpen,             /* xOpen */
   37482     winDelete,           /* xDelete */
   37483     winAccess,           /* xAccess */
   37484     winFullPathname,     /* xFullPathname */
   37485     winDlOpen,           /* xDlOpen */
   37486     winDlError,          /* xDlError */
   37487     winDlSym,            /* xDlSym */
   37488     winDlClose,          /* xDlClose */
   37489     winRandomness,       /* xRandomness */
   37490     winSleep,            /* xSleep */
   37491     winCurrentTime,      /* xCurrentTime */
   37492     winGetLastError,     /* xGetLastError */
   37493     winCurrentTimeInt64, /* xCurrentTimeInt64 */
   37494     winSetSystemCall,    /* xSetSystemCall */
   37495     winGetSystemCall,    /* xGetSystemCall */
   37496     winNextSystemCall,   /* xNextSystemCall */
   37497   };
   37498 #endif
   37499 
   37500   /* Double-check that the aSyscall[] array has been constructed
   37501   ** correctly.  See ticket [bb3a86e890c8e96ab] */
   37502   assert( ArraySize(aSyscall)==77 );
   37503 
   37504   /* get memory map allocation granularity */
   37505   memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
   37506 #if SQLITE_OS_WINRT
   37507   osGetNativeSystemInfo(&winSysInfo);
   37508 #else
   37509   osGetSystemInfo(&winSysInfo);
   37510 #endif
   37511   assert( winSysInfo.dwAllocationGranularity>0 );
   37512   assert( winSysInfo.dwPageSize>0 );
   37513 
   37514   sqlite3_vfs_register(&winVfs, 1);
   37515 
   37516 #if defined(SQLITE_WIN32_HAS_WIDE)
   37517   sqlite3_vfs_register(&winLongPathVfs, 0);
   37518 #endif
   37519 
   37520   return SQLITE_OK;
   37521 }
   37522 
   37523 SQLITE_API int sqlite3_os_end(void){
   37524 #if SQLITE_OS_WINRT
   37525   if( sleepObj!=NULL ){
   37526     osCloseHandle(sleepObj);
   37527     sleepObj = NULL;
   37528   }
   37529 #endif
   37530   return SQLITE_OK;
   37531 }
   37532 
   37533 #endif /* SQLITE_OS_WIN */
   37534 
   37535 /************** End of os_win.c **********************************************/
   37536 /************** Begin file bitvec.c ******************************************/
   37537 /*
   37538 ** 2008 February 16
   37539 **
   37540 ** The author disclaims copyright to this source code.  In place of
   37541 ** a legal notice, here is a blessing:
   37542 **
   37543 **    May you do good and not evil.
   37544 **    May you find forgiveness for yourself and forgive others.
   37545 **    May you share freely, never taking more than you give.
   37546 **
   37547 *************************************************************************
   37548 ** This file implements an object that represents a fixed-length
   37549 ** bitmap.  Bits are numbered starting with 1.
   37550 **
   37551 ** A bitmap is used to record which pages of a database file have been
   37552 ** journalled during a transaction, or which pages have the "dont-write"
   37553 ** property.  Usually only a few pages are meet either condition.
   37554 ** So the bitmap is usually sparse and has low cardinality.
   37555 ** But sometimes (for example when during a DROP of a large table) most
   37556 ** or all of the pages in a database can get journalled.  In those cases,
   37557 ** the bitmap becomes dense with high cardinality.  The algorithm needs
   37558 ** to handle both cases well.
   37559 **
   37560 ** The size of the bitmap is fixed when the object is created.
   37561 **
   37562 ** All bits are clear when the bitmap is created.  Individual bits
   37563 ** may be set or cleared one at a time.
   37564 **
   37565 ** Test operations are about 100 times more common that set operations.
   37566 ** Clear operations are exceedingly rare.  There are usually between
   37567 ** 5 and 500 set operations per Bitvec object, though the number of sets can
   37568 ** sometimes grow into tens of thousands or larger.  The size of the
   37569 ** Bitvec object is the number of pages in the database file at the
   37570 ** start of a transaction, and is thus usually less than a few thousand,
   37571 ** but can be as large as 2 billion for a really big database.
   37572 */
   37573 
   37574 /* Size of the Bitvec structure in bytes. */
   37575 #define BITVEC_SZ        512
   37576 
   37577 /* Round the union size down to the nearest pointer boundary, since that's how
   37578 ** it will be aligned within the Bitvec struct. */
   37579 #define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
   37580 
   37581 /* Type of the array "element" for the bitmap representation.
   37582 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
   37583 ** Setting this to the "natural word" size of your CPU may improve
   37584 ** performance. */
   37585 #define BITVEC_TELEM     u8
   37586 /* Size, in bits, of the bitmap element. */
   37587 #define BITVEC_SZELEM    8
   37588 /* Number of elements in a bitmap array. */
   37589 #define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
   37590 /* Number of bits in the bitmap array. */
   37591 #define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
   37592 
   37593 /* Number of u32 values in hash table. */
   37594 #define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
   37595 /* Maximum number of entries in hash table before
   37596 ** sub-dividing and re-hashing. */
   37597 #define BITVEC_MXHASH    (BITVEC_NINT/2)
   37598 /* Hashing function for the aHash representation.
   37599 ** Empirical testing showed that the *37 multiplier
   37600 ** (an arbitrary prime)in the hash function provided
   37601 ** no fewer collisions than the no-op *1. */
   37602 #define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
   37603 
   37604 #define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
   37605 
   37606 
   37607 /*
   37608 ** A bitmap is an instance of the following structure.
   37609 **
   37610 ** This bitmap records the existence of zero or more bits
   37611 ** with values between 1 and iSize, inclusive.
   37612 **
   37613 ** There are three possible representations of the bitmap.
   37614 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
   37615 ** bitmap.  The least significant bit is bit 1.
   37616 **
   37617 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
   37618 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
   37619 **
   37620 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
   37621 ** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
   37622 ** handles up to iDivisor separate values of i.  apSub[0] holds
   37623 ** values between 1 and iDivisor.  apSub[1] holds values between
   37624 ** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
   37625 ** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
   37626 ** to hold deal with values between 1 and iDivisor.
   37627 */
   37628 struct Bitvec {
   37629   u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
   37630   u32 nSet;       /* Number of bits that are set - only valid for aHash
   37631                   ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
   37632                   ** this would be 125. */
   37633   u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
   37634                   /* Should >=0 for apSub element. */
   37635                   /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
   37636                   /* For a BITVEC_SZ of 512, this would be 34,359,739. */
   37637   union {
   37638     BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
   37639     u32 aHash[BITVEC_NINT];      /* Hash table representation */
   37640     Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
   37641   } u;
   37642 };
   37643 
   37644 /*
   37645 ** Create a new bitmap object able to handle bits between 0 and iSize,
   37646 ** inclusive.  Return a pointer to the new object.  Return NULL if
   37647 ** malloc fails.
   37648 */
   37649 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
   37650   Bitvec *p;
   37651   assert( sizeof(*p)==BITVEC_SZ );
   37652   p = sqlite3MallocZero( sizeof(*p) );
   37653   if( p ){
   37654     p->iSize = iSize;
   37655   }
   37656   return p;
   37657 }
   37658 
   37659 /*
   37660 ** Check to see if the i-th bit is set.  Return true or false.
   37661 ** If p is NULL (if the bitmap has not been created) or if
   37662 ** i is out of range, then return false.
   37663 */
   37664 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
   37665   if( p==0 ) return 0;
   37666   if( i>p->iSize || i==0 ) return 0;
   37667   i--;
   37668   while( p->iDivisor ){
   37669     u32 bin = i/p->iDivisor;
   37670     i = i%p->iDivisor;
   37671     p = p->u.apSub[bin];
   37672     if (!p) {
   37673       return 0;
   37674     }
   37675   }
   37676   if( p->iSize<=BITVEC_NBIT ){
   37677     return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
   37678   } else{
   37679     u32 h = BITVEC_HASH(i++);
   37680     while( p->u.aHash[h] ){
   37681       if( p->u.aHash[h]==i ) return 1;
   37682       h = (h+1) % BITVEC_NINT;
   37683     }
   37684     return 0;
   37685   }
   37686 }
   37687 
   37688 /*
   37689 ** Set the i-th bit.  Return 0 on success and an error code if
   37690 ** anything goes wrong.
   37691 **
   37692 ** This routine might cause sub-bitmaps to be allocated.  Failing
   37693 ** to get the memory needed to hold the sub-bitmap is the only
   37694 ** that can go wrong with an insert, assuming p and i are valid.
   37695 **
   37696 ** The calling function must ensure that p is a valid Bitvec object
   37697 ** and that the value for "i" is within range of the Bitvec object.
   37698 ** Otherwise the behavior is undefined.
   37699 */
   37700 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
   37701   u32 h;
   37702   if( p==0 ) return SQLITE_OK;
   37703   assert( i>0 );
   37704   assert( i<=p->iSize );
   37705   i--;
   37706   while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
   37707     u32 bin = i/p->iDivisor;
   37708     i = i%p->iDivisor;
   37709     if( p->u.apSub[bin]==0 ){
   37710       p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
   37711       if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
   37712     }
   37713     p = p->u.apSub[bin];
   37714   }
   37715   if( p->iSize<=BITVEC_NBIT ){
   37716     p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
   37717     return SQLITE_OK;
   37718   }
   37719   h = BITVEC_HASH(i++);
   37720   /* if there wasn't a hash collision, and this doesn't */
   37721   /* completely fill the hash, then just add it without */
   37722   /* worring about sub-dividing and re-hashing. */
   37723   if( !p->u.aHash[h] ){
   37724     if (p->nSet<(BITVEC_NINT-1)) {
   37725       goto bitvec_set_end;
   37726     } else {
   37727       goto bitvec_set_rehash;
   37728     }
   37729   }
   37730   /* there was a collision, check to see if it's already */
   37731   /* in hash, if not, try to find a spot for it */
   37732   do {
   37733     if( p->u.aHash[h]==i ) return SQLITE_OK;
   37734     h++;
   37735     if( h>=BITVEC_NINT ) h = 0;
   37736   } while( p->u.aHash[h] );
   37737   /* we didn't find it in the hash.  h points to the first */
   37738   /* available free spot. check to see if this is going to */
   37739   /* make our hash too "full".  */
   37740 bitvec_set_rehash:
   37741   if( p->nSet>=BITVEC_MXHASH ){
   37742     unsigned int j;
   37743     int rc;
   37744     u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
   37745     if( aiValues==0 ){
   37746       return SQLITE_NOMEM;
   37747     }else{
   37748       memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
   37749       memset(p->u.apSub, 0, sizeof(p->u.apSub));
   37750       p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
   37751       rc = sqlite3BitvecSet(p, i);
   37752       for(j=0; j<BITVEC_NINT; j++){
   37753         if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
   37754       }
   37755       sqlite3StackFree(0, aiValues);
   37756       return rc;
   37757     }
   37758   }
   37759 bitvec_set_end:
   37760   p->nSet++;
   37761   p->u.aHash[h] = i;
   37762   return SQLITE_OK;
   37763 }
   37764 
   37765 /*
   37766 ** Clear the i-th bit.
   37767 **
   37768 ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
   37769 ** that BitvecClear can use to rebuilt its hash table.
   37770 */
   37771 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
   37772   if( p==0 ) return;
   37773   assert( i>0 );
   37774   i--;
   37775   while( p->iDivisor ){
   37776     u32 bin = i/p->iDivisor;
   37777     i = i%p->iDivisor;
   37778     p = p->u.apSub[bin];
   37779     if (!p) {
   37780       return;
   37781     }
   37782   }
   37783   if( p->iSize<=BITVEC_NBIT ){
   37784     p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
   37785   }else{
   37786     unsigned int j;
   37787     u32 *aiValues = pBuf;
   37788     memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
   37789     memset(p->u.aHash, 0, sizeof(p->u.aHash));
   37790     p->nSet = 0;
   37791     for(j=0; j<BITVEC_NINT; j++){
   37792       if( aiValues[j] && aiValues[j]!=(i+1) ){
   37793         u32 h = BITVEC_HASH(aiValues[j]-1);
   37794         p->nSet++;
   37795         while( p->u.aHash[h] ){
   37796           h++;
   37797           if( h>=BITVEC_NINT ) h = 0;
   37798         }
   37799         p->u.aHash[h] = aiValues[j];
   37800       }
   37801     }
   37802   }
   37803 }
   37804 
   37805 /*
   37806 ** Destroy a bitmap object.  Reclaim all memory used.
   37807 */
   37808 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
   37809   if( p==0 ) return;
   37810   if( p->iDivisor ){
   37811     unsigned int i;
   37812     for(i=0; i<BITVEC_NPTR; i++){
   37813       sqlite3BitvecDestroy(p->u.apSub[i]);
   37814     }
   37815   }
   37816   sqlite3_free(p);
   37817 }
   37818 
   37819 /*
   37820 ** Return the value of the iSize parameter specified when Bitvec *p
   37821 ** was created.
   37822 */
   37823 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
   37824   return p->iSize;
   37825 }
   37826 
   37827 #ifndef SQLITE_OMIT_BUILTIN_TEST
   37828 /*
   37829 ** Let V[] be an array of unsigned characters sufficient to hold
   37830 ** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
   37831 ** Then the following macros can be used to set, clear, or test
   37832 ** individual bits within V.
   37833 */
   37834 #define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
   37835 #define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
   37836 #define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
   37837 
   37838 /*
   37839 ** This routine runs an extensive test of the Bitvec code.
   37840 **
   37841 ** The input is an array of integers that acts as a program
   37842 ** to test the Bitvec.  The integers are opcodes followed
   37843 ** by 0, 1, or 3 operands, depending on the opcode.  Another
   37844 ** opcode follows immediately after the last operand.
   37845 **
   37846 ** There are 6 opcodes numbered from 0 through 5.  0 is the
   37847 ** "halt" opcode and causes the test to end.
   37848 **
   37849 **    0          Halt and return the number of errors
   37850 **    1 N S X    Set N bits beginning with S and incrementing by X
   37851 **    2 N S X    Clear N bits beginning with S and incrementing by X
   37852 **    3 N        Set N randomly chosen bits
   37853 **    4 N        Clear N randomly chosen bits
   37854 **    5 N S X    Set N bits from S increment X in array only, not in bitvec
   37855 **
   37856 ** The opcodes 1 through 4 perform set and clear operations are performed
   37857 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
   37858 ** Opcode 5 works on the linear array only, not on the Bitvec.
   37859 ** Opcode 5 is used to deliberately induce a fault in order to
   37860 ** confirm that error detection works.
   37861 **
   37862 ** At the conclusion of the test the linear array is compared
   37863 ** against the Bitvec object.  If there are any differences,
   37864 ** an error is returned.  If they are the same, zero is returned.
   37865 **
   37866 ** If a memory allocation error occurs, return -1.
   37867 */
   37868 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
   37869   Bitvec *pBitvec = 0;
   37870   unsigned char *pV = 0;
   37871   int rc = -1;
   37872   int i, nx, pc, op;
   37873   void *pTmpSpace;
   37874 
   37875   /* Allocate the Bitvec to be tested and a linear array of
   37876   ** bits to act as the reference */
   37877   pBitvec = sqlite3BitvecCreate( sz );
   37878   pV = sqlite3MallocZero( (sz+7)/8 + 1 );
   37879   pTmpSpace = sqlite3_malloc(BITVEC_SZ);
   37880   if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
   37881 
   37882   /* NULL pBitvec tests */
   37883   sqlite3BitvecSet(0, 1);
   37884   sqlite3BitvecClear(0, 1, pTmpSpace);
   37885 
   37886   /* Run the program */
   37887   pc = 0;
   37888   while( (op = aOp[pc])!=0 ){
   37889     switch( op ){
   37890       case 1:
   37891       case 2:
   37892       case 5: {
   37893         nx = 4;
   37894         i = aOp[pc+2] - 1;
   37895         aOp[pc+2] += aOp[pc+3];
   37896         break;
   37897       }
   37898       case 3:
   37899       case 4:
   37900       default: {
   37901         nx = 2;
   37902         sqlite3_randomness(sizeof(i), &i);
   37903         break;
   37904       }
   37905     }
   37906     if( (--aOp[pc+1]) > 0 ) nx = 0;
   37907     pc += nx;
   37908     i = (i & 0x7fffffff)%sz;
   37909     if( (op & 1)!=0 ){
   37910       SETBIT(pV, (i+1));
   37911       if( op!=5 ){
   37912         if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
   37913       }
   37914     }else{
   37915       CLEARBIT(pV, (i+1));
   37916       sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
   37917     }
   37918   }
   37919 
   37920   /* Test to make sure the linear array exactly matches the
   37921   ** Bitvec object.  Start with the assumption that they do
   37922   ** match (rc==0).  Change rc to non-zero if a discrepancy
   37923   ** is found.
   37924   */
   37925   rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
   37926           + sqlite3BitvecTest(pBitvec, 0)
   37927           + (sqlite3BitvecSize(pBitvec) - sz);
   37928   for(i=1; i<=sz; i++){
   37929     if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
   37930       rc = i;
   37931       break;
   37932     }
   37933   }
   37934 
   37935   /* Free allocated structure */
   37936 bitvec_end:
   37937   sqlite3_free(pTmpSpace);
   37938   sqlite3_free(pV);
   37939   sqlite3BitvecDestroy(pBitvec);
   37940   return rc;
   37941 }
   37942 #endif /* SQLITE_OMIT_BUILTIN_TEST */
   37943 
   37944 /************** End of bitvec.c **********************************************/
   37945 /************** Begin file pcache.c ******************************************/
   37946 /*
   37947 ** 2008 August 05
   37948 **
   37949 ** The author disclaims copyright to this source code.  In place of
   37950 ** a legal notice, here is a blessing:
   37951 **
   37952 **    May you do good and not evil.
   37953 **    May you find forgiveness for yourself and forgive others.
   37954 **    May you share freely, never taking more than you give.
   37955 **
   37956 *************************************************************************
   37957 ** This file implements that page cache.
   37958 */
   37959 
   37960 /*
   37961 ** A complete page cache is an instance of this structure.
   37962 */
   37963 struct PCache {
   37964   PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
   37965   PgHdr *pSynced;                     /* Last synced page in dirty page list */
   37966   int nRef;                           /* Number of referenced pages */
   37967   int szCache;                        /* Configured cache size */
   37968   int szPage;                         /* Size of every page in this cache */
   37969   int szExtra;                        /* Size of extra space for each page */
   37970   u8 bPurgeable;                      /* True if pages are on backing store */
   37971   u8 eCreate;                         /* eCreate value for for xFetch() */
   37972   int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
   37973   void *pStress;                      /* Argument to xStress */
   37974   sqlite3_pcache *pCache;             /* Pluggable cache module */
   37975   PgHdr *pPage1;                      /* Reference to page 1 */
   37976 };
   37977 
   37978 /*
   37979 ** Some of the assert() macros in this code are too expensive to run
   37980 ** even during normal debugging.  Use them only rarely on long-running
   37981 ** tests.  Enable the expensive asserts using the
   37982 ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
   37983 */
   37984 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
   37985 # define expensive_assert(X)  assert(X)
   37986 #else
   37987 # define expensive_assert(X)
   37988 #endif
   37989 
   37990 /********************************** Linked List Management ********************/
   37991 
   37992 #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
   37993 /*
   37994 ** Check that the pCache->pSynced variable is set correctly. If it
   37995 ** is not, either fail an assert or return zero. Otherwise, return
   37996 ** non-zero. This is only used in debugging builds, as follows:
   37997 **
   37998 **   expensive_assert( pcacheCheckSynced(pCache) );
   37999 */
   38000 static int pcacheCheckSynced(PCache *pCache){
   38001   PgHdr *p;
   38002   for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
   38003     assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
   38004   }
   38005   return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
   38006 }
   38007 #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
   38008 
   38009 /*
   38010 ** Remove page pPage from the list of dirty pages.
   38011 */
   38012 static void pcacheRemoveFromDirtyList(PgHdr *pPage){
   38013   PCache *p = pPage->pCache;
   38014 
   38015   assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
   38016   assert( pPage->pDirtyPrev || pPage==p->pDirty );
   38017 
   38018   /* Update the PCache1.pSynced variable if necessary. */
   38019   if( p->pSynced==pPage ){
   38020     PgHdr *pSynced = pPage->pDirtyPrev;
   38021     while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
   38022       pSynced = pSynced->pDirtyPrev;
   38023     }
   38024     p->pSynced = pSynced;
   38025   }
   38026 
   38027   if( pPage->pDirtyNext ){
   38028     pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
   38029   }else{
   38030     assert( pPage==p->pDirtyTail );
   38031     p->pDirtyTail = pPage->pDirtyPrev;
   38032   }
   38033   if( pPage->pDirtyPrev ){
   38034     pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
   38035   }else{
   38036     assert( pPage==p->pDirty );
   38037     p->pDirty = pPage->pDirtyNext;
   38038     if( p->pDirty==0 && p->bPurgeable ){
   38039       assert( p->eCreate==1 );
   38040       p->eCreate = 2;
   38041     }
   38042   }
   38043   pPage->pDirtyNext = 0;
   38044   pPage->pDirtyPrev = 0;
   38045 
   38046   expensive_assert( pcacheCheckSynced(p) );
   38047 }
   38048 
   38049 /*
   38050 ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
   38051 ** pPage).
   38052 */
   38053 static void pcacheAddToDirtyList(PgHdr *pPage){
   38054   PCache *p = pPage->pCache;
   38055 
   38056   assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
   38057 
   38058   pPage->pDirtyNext = p->pDirty;
   38059   if( pPage->pDirtyNext ){
   38060     assert( pPage->pDirtyNext->pDirtyPrev==0 );
   38061     pPage->pDirtyNext->pDirtyPrev = pPage;
   38062   }else if( p->bPurgeable ){
   38063     assert( p->eCreate==2 );
   38064     p->eCreate = 1;
   38065   }
   38066   p->pDirty = pPage;
   38067   if( !p->pDirtyTail ){
   38068     p->pDirtyTail = pPage;
   38069   }
   38070   if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
   38071     p->pSynced = pPage;
   38072   }
   38073   expensive_assert( pcacheCheckSynced(p) );
   38074 }
   38075 
   38076 /*
   38077 ** Wrapper around the pluggable caches xUnpin method. If the cache is
   38078 ** being used for an in-memory database, this function is a no-op.
   38079 */
   38080 static void pcacheUnpin(PgHdr *p){
   38081   PCache *pCache = p->pCache;
   38082   if( pCache->bPurgeable ){
   38083     if( p->pgno==1 ){
   38084       pCache->pPage1 = 0;
   38085     }
   38086     sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 0);
   38087   }
   38088 }
   38089 
   38090 /*************************************************** General Interfaces ******
   38091 **
   38092 ** Initialize and shutdown the page cache subsystem. Neither of these
   38093 ** functions are threadsafe.
   38094 */
   38095 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
   38096   if( sqlite3GlobalConfig.pcache2.xInit==0 ){
   38097     /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
   38098     ** built-in default page cache is used instead of the application defined
   38099     ** page cache. */
   38100     sqlite3PCacheSetDefault();
   38101   }
   38102   return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
   38103 }
   38104 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
   38105   if( sqlite3GlobalConfig.pcache2.xShutdown ){
   38106     /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
   38107     sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
   38108   }
   38109 }
   38110 
   38111 /*
   38112 ** Return the size in bytes of a PCache object.
   38113 */
   38114 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
   38115 
   38116 /*
   38117 ** Create a new PCache object. Storage space to hold the object
   38118 ** has already been allocated and is passed in as the p pointer.
   38119 ** The caller discovers how much space needs to be allocated by
   38120 ** calling sqlite3PcacheSize().
   38121 */
   38122 SQLITE_PRIVATE void sqlite3PcacheOpen(
   38123   int szPage,                  /* Size of every page */
   38124   int szExtra,                 /* Extra space associated with each page */
   38125   int bPurgeable,              /* True if pages are on backing store */
   38126   int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
   38127   void *pStress,               /* Argument to xStress */
   38128   PCache *p                    /* Preallocated space for the PCache */
   38129 ){
   38130   memset(p, 0, sizeof(PCache));
   38131   p->szPage = szPage;
   38132   p->szExtra = szExtra;
   38133   p->bPurgeable = bPurgeable;
   38134   p->eCreate = 2;
   38135   p->xStress = xStress;
   38136   p->pStress = pStress;
   38137   p->szCache = 100;
   38138 }
   38139 
   38140 /*
   38141 ** Change the page size for PCache object. The caller must ensure that there
   38142 ** are no outstanding page references when this function is called.
   38143 */
   38144 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
   38145   assert( pCache->nRef==0 && pCache->pDirty==0 );
   38146   if( pCache->pCache ){
   38147     sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
   38148     pCache->pCache = 0;
   38149     pCache->pPage1 = 0;
   38150   }
   38151   pCache->szPage = szPage;
   38152 }
   38153 
   38154 /*
   38155 ** Compute the number of pages of cache requested.
   38156 */
   38157 static int numberOfCachePages(PCache *p){
   38158   if( p->szCache>=0 ){
   38159     return p->szCache;
   38160   }else{
   38161     return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
   38162   }
   38163 }
   38164 
   38165 /*
   38166 ** Try to obtain a page from the cache.
   38167 */
   38168 SQLITE_PRIVATE int sqlite3PcacheFetch(
   38169   PCache *pCache,       /* Obtain the page from this cache */
   38170   Pgno pgno,            /* Page number to obtain */
   38171   int createFlag,       /* If true, create page if it does not exist already */
   38172   PgHdr **ppPage        /* Write the page here */
   38173 ){
   38174   sqlite3_pcache_page *pPage;
   38175   PgHdr *pPgHdr = 0;
   38176   int eCreate;
   38177 
   38178   assert( pCache!=0 );
   38179   assert( createFlag==1 || createFlag==0 );
   38180   assert( pgno>0 );
   38181 
   38182   /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
   38183   ** allocate it now.
   38184   */
   38185   if( !pCache->pCache ){
   38186     sqlite3_pcache *p;
   38187     if( !createFlag ){
   38188       *ppPage = 0;
   38189       return SQLITE_OK;
   38190     }
   38191     p = sqlite3GlobalConfig.pcache2.xCreate(
   38192         pCache->szPage, pCache->szExtra + sizeof(PgHdr), pCache->bPurgeable
   38193     );
   38194     if( !p ){
   38195       return SQLITE_NOMEM;
   38196     }
   38197     sqlite3GlobalConfig.pcache2.xCachesize(p, numberOfCachePages(pCache));
   38198     pCache->pCache = p;
   38199   }
   38200 
   38201   /* eCreate defines what to do if the page does not exist.
   38202   **    0     Do not allocate a new page.  (createFlag==0)
   38203   **    1     Allocate a new page if doing so is inexpensive.
   38204   **          (createFlag==1 AND bPurgeable AND pDirty)
   38205   **    2     Allocate a new page even it doing so is difficult.
   38206   **          (createFlag==1 AND !(bPurgeable AND pDirty)
   38207   */
   38208   eCreate = createFlag==0 ? 0 : pCache->eCreate;
   38209   assert( (createFlag*(1+(!pCache->bPurgeable||!pCache->pDirty)))==eCreate );
   38210   pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
   38211   if( !pPage && eCreate==1 ){
   38212     PgHdr *pPg;
   38213 
   38214     /* Find a dirty page to write-out and recycle. First try to find a
   38215     ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
   38216     ** cleared), but if that is not possible settle for any other
   38217     ** unreferenced dirty page.
   38218     */
   38219     expensive_assert( pcacheCheckSynced(pCache) );
   38220     for(pPg=pCache->pSynced;
   38221         pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
   38222         pPg=pPg->pDirtyPrev
   38223     );
   38224     pCache->pSynced = pPg;
   38225     if( !pPg ){
   38226       for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
   38227     }
   38228     if( pPg ){
   38229       int rc;
   38230 #ifdef SQLITE_LOG_CACHE_SPILL
   38231       sqlite3_log(SQLITE_FULL,
   38232                   "spill page %d making room for %d - cache used: %d/%d",
   38233                   pPg->pgno, pgno,
   38234                   sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
   38235                   numberOfCachePages(pCache));
   38236 #endif
   38237       rc = pCache->xStress(pCache->pStress, pPg);
   38238       if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
   38239         return rc;
   38240       }
   38241     }
   38242 
   38243     pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
   38244   }
   38245 
   38246   if( pPage ){
   38247     pPgHdr = (PgHdr *)pPage->pExtra;
   38248 
   38249     if( !pPgHdr->pPage ){
   38250       memset(pPgHdr, 0, sizeof(PgHdr));
   38251       pPgHdr->pPage = pPage;
   38252       pPgHdr->pData = pPage->pBuf;
   38253       pPgHdr->pExtra = (void *)&pPgHdr[1];
   38254       memset(pPgHdr->pExtra, 0, pCache->szExtra);
   38255       pPgHdr->pCache = pCache;
   38256       pPgHdr->pgno = pgno;
   38257     }
   38258     assert( pPgHdr->pCache==pCache );
   38259     assert( pPgHdr->pgno==pgno );
   38260     assert( pPgHdr->pData==pPage->pBuf );
   38261     assert( pPgHdr->pExtra==(void *)&pPgHdr[1] );
   38262 
   38263     if( 0==pPgHdr->nRef ){
   38264       pCache->nRef++;
   38265     }
   38266     pPgHdr->nRef++;
   38267     if( pgno==1 ){
   38268       pCache->pPage1 = pPgHdr;
   38269     }
   38270   }
   38271   *ppPage = pPgHdr;
   38272   return (pPgHdr==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
   38273 }
   38274 
   38275 /*
   38276 ** Decrement the reference count on a page. If the page is clean and the
   38277 ** reference count drops to 0, then it is made elible for recycling.
   38278 */
   38279 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
   38280   assert( p->nRef>0 );
   38281   p->nRef--;
   38282   if( p->nRef==0 ){
   38283     PCache *pCache = p->pCache;
   38284     pCache->nRef--;
   38285     if( (p->flags&PGHDR_DIRTY)==0 ){
   38286       pcacheUnpin(p);
   38287     }else{
   38288       /* Move the page to the head of the dirty list. */
   38289       pcacheRemoveFromDirtyList(p);
   38290       pcacheAddToDirtyList(p);
   38291     }
   38292   }
   38293 }
   38294 
   38295 /*
   38296 ** Increase the reference count of a supplied page by 1.
   38297 */
   38298 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
   38299   assert(p->nRef>0);
   38300   p->nRef++;
   38301 }
   38302 
   38303 /*
   38304 ** Drop a page from the cache. There must be exactly one reference to the
   38305 ** page. This function deletes that reference, so after it returns the
   38306 ** page pointed to by p is invalid.
   38307 */
   38308 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
   38309   PCache *pCache;
   38310   assert( p->nRef==1 );
   38311   if( p->flags&PGHDR_DIRTY ){
   38312     pcacheRemoveFromDirtyList(p);
   38313   }
   38314   pCache = p->pCache;
   38315   pCache->nRef--;
   38316   if( p->pgno==1 ){
   38317     pCache->pPage1 = 0;
   38318   }
   38319   sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 1);
   38320 }
   38321 
   38322 /*
   38323 ** Make sure the page is marked as dirty. If it isn't dirty already,
   38324 ** make it so.
   38325 */
   38326 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
   38327   p->flags &= ~PGHDR_DONT_WRITE;
   38328   assert( p->nRef>0 );
   38329   if( 0==(p->flags & PGHDR_DIRTY) ){
   38330     p->flags |= PGHDR_DIRTY;
   38331     pcacheAddToDirtyList( p);
   38332   }
   38333 }
   38334 
   38335 /*
   38336 ** Make sure the page is marked as clean. If it isn't clean already,
   38337 ** make it so.
   38338 */
   38339 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
   38340   if( (p->flags & PGHDR_DIRTY) ){
   38341     pcacheRemoveFromDirtyList(p);
   38342     p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
   38343     if( p->nRef==0 ){
   38344       pcacheUnpin(p);
   38345     }
   38346   }
   38347 }
   38348 
   38349 /*
   38350 ** Make every page in the cache clean.
   38351 */
   38352 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
   38353   PgHdr *p;
   38354   while( (p = pCache->pDirty)!=0 ){
   38355     sqlite3PcacheMakeClean(p);
   38356   }
   38357 }
   38358 
   38359 /*
   38360 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
   38361 */
   38362 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
   38363   PgHdr *p;
   38364   for(p=pCache->pDirty; p; p=p->pDirtyNext){
   38365     p->flags &= ~PGHDR_NEED_SYNC;
   38366   }
   38367   pCache->pSynced = pCache->pDirtyTail;
   38368 }
   38369 
   38370 /*
   38371 ** Change the page number of page p to newPgno.
   38372 */
   38373 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
   38374   PCache *pCache = p->pCache;
   38375   assert( p->nRef>0 );
   38376   assert( newPgno>0 );
   38377   sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
   38378   p->pgno = newPgno;
   38379   if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
   38380     pcacheRemoveFromDirtyList(p);
   38381     pcacheAddToDirtyList(p);
   38382   }
   38383 }
   38384 
   38385 /*
   38386 ** Drop every cache entry whose page number is greater than "pgno". The
   38387 ** caller must ensure that there are no outstanding references to any pages
   38388 ** other than page 1 with a page number greater than pgno.
   38389 **
   38390 ** If there is a reference to page 1 and the pgno parameter passed to this
   38391 ** function is 0, then the data area associated with page 1 is zeroed, but
   38392 ** the page object is not dropped.
   38393 */
   38394 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
   38395   if( pCache->pCache ){
   38396     PgHdr *p;
   38397     PgHdr *pNext;
   38398     for(p=pCache->pDirty; p; p=pNext){
   38399       pNext = p->pDirtyNext;
   38400       /* This routine never gets call with a positive pgno except right
   38401       ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
   38402       ** it must be that pgno==0.
   38403       */
   38404       assert( p->pgno>0 );
   38405       if( ALWAYS(p->pgno>pgno) ){
   38406         assert( p->flags&PGHDR_DIRTY );
   38407         sqlite3PcacheMakeClean(p);
   38408       }
   38409     }
   38410     if( pgno==0 && pCache->pPage1 ){
   38411       memset(pCache->pPage1->pData, 0, pCache->szPage);
   38412       pgno = 1;
   38413     }
   38414     sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
   38415   }
   38416 }
   38417 
   38418 /*
   38419 ** Close a cache.
   38420 */
   38421 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
   38422   if( pCache->pCache ){
   38423     sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
   38424   }
   38425 }
   38426 
   38427 /*
   38428 ** Discard the contents of the cache.
   38429 */
   38430 SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
   38431   sqlite3PcacheTruncate(pCache, 0);
   38432 }
   38433 
   38434 /*
   38435 ** Merge two lists of pages connected by pDirty and in pgno order.
   38436 ** Do not both fixing the pDirtyPrev pointers.
   38437 */
   38438 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
   38439   PgHdr result, *pTail;
   38440   pTail = &result;
   38441   while( pA && pB ){
   38442     if( pA->pgno<pB->pgno ){
   38443       pTail->pDirty = pA;
   38444       pTail = pA;
   38445       pA = pA->pDirty;
   38446     }else{
   38447       pTail->pDirty = pB;
   38448       pTail = pB;
   38449       pB = pB->pDirty;
   38450     }
   38451   }
   38452   if( pA ){
   38453     pTail->pDirty = pA;
   38454   }else if( pB ){
   38455     pTail->pDirty = pB;
   38456   }else{
   38457     pTail->pDirty = 0;
   38458   }
   38459   return result.pDirty;
   38460 }
   38461 
   38462 /*
   38463 ** Sort the list of pages in accending order by pgno.  Pages are
   38464 ** connected by pDirty pointers.  The pDirtyPrev pointers are
   38465 ** corrupted by this sort.
   38466 **
   38467 ** Since there cannot be more than 2^31 distinct pages in a database,
   38468 ** there cannot be more than 31 buckets required by the merge sorter.
   38469 ** One extra bucket is added to catch overflow in case something
   38470 ** ever changes to make the previous sentence incorrect.
   38471 */
   38472 #define N_SORT_BUCKET  32
   38473 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
   38474   PgHdr *a[N_SORT_BUCKET], *p;
   38475   int i;
   38476   memset(a, 0, sizeof(a));
   38477   while( pIn ){
   38478     p = pIn;
   38479     pIn = p->pDirty;
   38480     p->pDirty = 0;
   38481     for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
   38482       if( a[i]==0 ){
   38483         a[i] = p;
   38484         break;
   38485       }else{
   38486         p = pcacheMergeDirtyList(a[i], p);
   38487         a[i] = 0;
   38488       }
   38489     }
   38490     if( NEVER(i==N_SORT_BUCKET-1) ){
   38491       /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
   38492       ** the input list.  But that is impossible.
   38493       */
   38494       a[i] = pcacheMergeDirtyList(a[i], p);
   38495     }
   38496   }
   38497   p = a[0];
   38498   for(i=1; i<N_SORT_BUCKET; i++){
   38499     p = pcacheMergeDirtyList(p, a[i]);
   38500   }
   38501   return p;
   38502 }
   38503 
   38504 /*
   38505 ** Return a list of all dirty pages in the cache, sorted by page number.
   38506 */
   38507 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
   38508   PgHdr *p;
   38509   for(p=pCache->pDirty; p; p=p->pDirtyNext){
   38510     p->pDirty = p->pDirtyNext;
   38511   }
   38512   return pcacheSortDirtyList(pCache->pDirty);
   38513 }
   38514 
   38515 /*
   38516 ** Return the total number of referenced pages held by the cache.
   38517 */
   38518 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
   38519   return pCache->nRef;
   38520 }
   38521 
   38522 /*
   38523 ** Return the number of references to the page supplied as an argument.
   38524 */
   38525 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
   38526   return p->nRef;
   38527 }
   38528 
   38529 /*
   38530 ** Return the total number of pages in the cache.
   38531 */
   38532 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
   38533   int nPage = 0;
   38534   if( pCache->pCache ){
   38535     nPage = sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
   38536   }
   38537   return nPage;
   38538 }
   38539 
   38540 #ifdef SQLITE_TEST
   38541 /*
   38542 ** Get the suggested cache-size value.
   38543 */
   38544 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
   38545   return numberOfCachePages(pCache);
   38546 }
   38547 #endif
   38548 
   38549 /*
   38550 ** Set the suggested cache-size value.
   38551 */
   38552 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
   38553   pCache->szCache = mxPage;
   38554   if( pCache->pCache ){
   38555     sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
   38556                                            numberOfCachePages(pCache));
   38557   }
   38558 }
   38559 
   38560 /*
   38561 ** Free up as much memory as possible from the page cache.
   38562 */
   38563 SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
   38564   if( pCache->pCache ){
   38565     sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
   38566   }
   38567 }
   38568 
   38569 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
   38570 /*
   38571 ** For all dirty pages currently in the cache, invoke the specified
   38572 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
   38573 ** defined.
   38574 */
   38575 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
   38576   PgHdr *pDirty;
   38577   for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
   38578     xIter(pDirty);
   38579   }
   38580 }
   38581 #endif
   38582 
   38583 /************** End of pcache.c **********************************************/
   38584 /************** Begin file pcache1.c *****************************************/
   38585 /*
   38586 ** 2008 November 05
   38587 **
   38588 ** The author disclaims copyright to this source code.  In place of
   38589 ** a legal notice, here is a blessing:
   38590 **
   38591 **    May you do good and not evil.
   38592 **    May you find forgiveness for yourself and forgive others.
   38593 **    May you share freely, never taking more than you give.
   38594 **
   38595 *************************************************************************
   38596 **
   38597 ** This file implements the default page cache implementation (the
   38598 ** sqlite3_pcache interface). It also contains part of the implementation
   38599 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
   38600 ** If the default page cache implementation is overriden, then neither of
   38601 ** these two features are available.
   38602 */
   38603 
   38604 
   38605 typedef struct PCache1 PCache1;
   38606 typedef struct PgHdr1 PgHdr1;
   38607 typedef struct PgFreeslot PgFreeslot;
   38608 typedef struct PGroup PGroup;
   38609 
   38610 /* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set
   38611 ** of one or more PCaches that are able to recycle each others unpinned
   38612 ** pages when they are under memory pressure.  A PGroup is an instance of
   38613 ** the following object.
   38614 **
   38615 ** This page cache implementation works in one of two modes:
   38616 **
   38617 **   (1)  Every PCache is the sole member of its own PGroup.  There is
   38618 **        one PGroup per PCache.
   38619 **
   38620 **   (2)  There is a single global PGroup that all PCaches are a member
   38621 **        of.
   38622 **
   38623 ** Mode 1 uses more memory (since PCache instances are not able to rob
   38624 ** unused pages from other PCaches) but it also operates without a mutex,
   38625 ** and is therefore often faster.  Mode 2 requires a mutex in order to be
   38626 ** threadsafe, but recycles pages more efficiently.
   38627 **
   38628 ** For mode (1), PGroup.mutex is NULL.  For mode (2) there is only a single
   38629 ** PGroup which is the pcache1.grp global variable and its mutex is
   38630 ** SQLITE_MUTEX_STATIC_LRU.
   38631 */
   38632 struct PGroup {
   38633   sqlite3_mutex *mutex;          /* MUTEX_STATIC_LRU or NULL */
   38634   unsigned int nMaxPage;         /* Sum of nMax for purgeable caches */
   38635   unsigned int nMinPage;         /* Sum of nMin for purgeable caches */
   38636   unsigned int mxPinned;         /* nMaxpage + 10 - nMinPage */
   38637   unsigned int nCurrentPage;     /* Number of purgeable pages allocated */
   38638   PgHdr1 *pLruHead, *pLruTail;   /* LRU list of unpinned pages */
   38639 };
   38640 
   38641 /* Each page cache is an instance of the following object.  Every
   38642 ** open database file (including each in-memory database and each
   38643 ** temporary or transient database) has a single page cache which
   38644 ** is an instance of this object.
   38645 **
   38646 ** Pointers to structures of this type are cast and returned as
   38647 ** opaque sqlite3_pcache* handles.
   38648 */
   38649 struct PCache1 {
   38650   /* Cache configuration parameters. Page size (szPage) and the purgeable
   38651   ** flag (bPurgeable) are set when the cache is created. nMax may be
   38652   ** modified at any time by a call to the pcache1Cachesize() method.
   38653   ** The PGroup mutex must be held when accessing nMax.
   38654   */
   38655   PGroup *pGroup;                     /* PGroup this cache belongs to */
   38656   int szPage;                         /* Size of allocated pages in bytes */
   38657   int szExtra;                        /* Size of extra space in bytes */
   38658   int bPurgeable;                     /* True if cache is purgeable */
   38659   unsigned int nMin;                  /* Minimum number of pages reserved */
   38660   unsigned int nMax;                  /* Configured "cache_size" value */
   38661   unsigned int n90pct;                /* nMax*9/10 */
   38662   unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
   38663 
   38664   /* Hash table of all pages. The following variables may only be accessed
   38665   ** when the accessor is holding the PGroup mutex.
   38666   */
   38667   unsigned int nRecyclable;           /* Number of pages in the LRU list */
   38668   unsigned int nPage;                 /* Total number of pages in apHash */
   38669   unsigned int nHash;                 /* Number of slots in apHash[] */
   38670   PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
   38671 };
   38672 
   38673 /*
   38674 ** Each cache entry is represented by an instance of the following
   38675 ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
   38676 ** PgHdr1.pCache->szPage bytes is allocated directly before this structure
   38677 ** in memory.
   38678 */
   38679 struct PgHdr1 {
   38680   sqlite3_pcache_page page;
   38681   unsigned int iKey;             /* Key value (page number) */
   38682   u8 isPinned;                   /* Page in use, not on the LRU list */
   38683   PgHdr1 *pNext;                 /* Next in hash table chain */
   38684   PCache1 *pCache;               /* Cache that currently owns this page */
   38685   PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
   38686   PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
   38687 };
   38688 
   38689 /*
   38690 ** Free slots in the allocator used to divide up the buffer provided using
   38691 ** the SQLITE_CONFIG_PAGECACHE mechanism.
   38692 */
   38693 struct PgFreeslot {
   38694   PgFreeslot *pNext;  /* Next free slot */
   38695 };
   38696 
   38697 /*
   38698 ** Global data used by this cache.
   38699 */
   38700 static SQLITE_WSD struct PCacheGlobal {
   38701   PGroup grp;                    /* The global PGroup for mode (2) */
   38702 
   38703   /* Variables related to SQLITE_CONFIG_PAGECACHE settings.  The
   38704   ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
   38705   ** fixed at sqlite3_initialize() time and do not require mutex protection.
   38706   ** The nFreeSlot and pFree values do require mutex protection.
   38707   */
   38708   int isInit;                    /* True if initialized */
   38709   int szSlot;                    /* Size of each free slot */
   38710   int nSlot;                     /* The number of pcache slots */
   38711   int nReserve;                  /* Try to keep nFreeSlot above this */
   38712   void *pStart, *pEnd;           /* Bounds of pagecache malloc range */
   38713   /* Above requires no mutex.  Use mutex below for variable that follow. */
   38714   sqlite3_mutex *mutex;          /* Mutex for accessing the following: */
   38715   PgFreeslot *pFree;             /* Free page blocks */
   38716   int nFreeSlot;                 /* Number of unused pcache slots */
   38717   /* The following value requires a mutex to change.  We skip the mutex on
   38718   ** reading because (1) most platforms read a 32-bit integer atomically and
   38719   ** (2) even if an incorrect value is read, no great harm is done since this
   38720   ** is really just an optimization. */
   38721   int bUnderPressure;            /* True if low on PAGECACHE memory */
   38722 } pcache1_g;
   38723 
   38724 /*
   38725 ** All code in this file should access the global structure above via the
   38726 ** alias "pcache1". This ensures that the WSD emulation is used when
   38727 ** compiling for systems that do not support real WSD.
   38728 */
   38729 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
   38730 
   38731 /*
   38732 ** Macros to enter and leave the PCache LRU mutex.
   38733 */
   38734 #define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
   38735 #define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
   38736 
   38737 /******************************************************************************/
   38738 /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
   38739 
   38740 /*
   38741 ** This function is called during initialization if a static buffer is
   38742 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
   38743 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
   38744 ** enough to contain 'n' buffers of 'sz' bytes each.
   38745 **
   38746 ** This routine is called from sqlite3_initialize() and so it is guaranteed
   38747 ** to be serialized already.  There is no need for further mutexing.
   38748 */
   38749 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
   38750   if( pcache1.isInit ){
   38751     PgFreeslot *p;
   38752     sz = ROUNDDOWN8(sz);
   38753     pcache1.szSlot = sz;
   38754     pcache1.nSlot = pcache1.nFreeSlot = n;
   38755     pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
   38756     pcache1.pStart = pBuf;
   38757     pcache1.pFree = 0;
   38758     pcache1.bUnderPressure = 0;
   38759     while( n-- ){
   38760       p = (PgFreeslot*)pBuf;
   38761       p->pNext = pcache1.pFree;
   38762       pcache1.pFree = p;
   38763       pBuf = (void*)&((char*)pBuf)[sz];
   38764     }
   38765     pcache1.pEnd = pBuf;
   38766   }
   38767 }
   38768 
   38769 /*
   38770 ** Malloc function used within this file to allocate space from the buffer
   38771 ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
   38772 ** such buffer exists or there is no space left in it, this function falls
   38773 ** back to sqlite3Malloc().
   38774 **
   38775 ** Multiple threads can run this routine at the same time.  Global variables
   38776 ** in pcache1 need to be protected via mutex.
   38777 */
   38778 static void *pcache1Alloc(int nByte){
   38779   void *p = 0;
   38780   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
   38781   sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
   38782   if( nByte<=pcache1.szSlot ){
   38783     sqlite3_mutex_enter(pcache1.mutex);
   38784     p = (PgHdr1 *)pcache1.pFree;
   38785     if( p ){
   38786       pcache1.pFree = pcache1.pFree->pNext;
   38787       pcache1.nFreeSlot--;
   38788       pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
   38789       assert( pcache1.nFreeSlot>=0 );
   38790       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
   38791     }
   38792     sqlite3_mutex_leave(pcache1.mutex);
   38793   }
   38794   if( p==0 ){
   38795     /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool.  Get
   38796     ** it from sqlite3Malloc instead.
   38797     */
   38798     p = sqlite3Malloc(nByte);
   38799 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
   38800     if( p ){
   38801       int sz = sqlite3MallocSize(p);
   38802       sqlite3_mutex_enter(pcache1.mutex);
   38803       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
   38804       sqlite3_mutex_leave(pcache1.mutex);
   38805     }
   38806 #endif
   38807     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
   38808   }
   38809   return p;
   38810 }
   38811 
   38812 /*
   38813 ** Free an allocated buffer obtained from pcache1Alloc().
   38814 */
   38815 static int pcache1Free(void *p){
   38816   int nFreed = 0;
   38817   if( p==0 ) return 0;
   38818   if( p>=pcache1.pStart && p<pcache1.pEnd ){
   38819     PgFreeslot *pSlot;
   38820     sqlite3_mutex_enter(pcache1.mutex);
   38821     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
   38822     pSlot = (PgFreeslot*)p;
   38823     pSlot->pNext = pcache1.pFree;
   38824     pcache1.pFree = pSlot;
   38825     pcache1.nFreeSlot++;
   38826     pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
   38827     assert( pcache1.nFreeSlot<=pcache1.nSlot );
   38828     sqlite3_mutex_leave(pcache1.mutex);
   38829   }else{
   38830     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
   38831     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
   38832     nFreed = sqlite3MallocSize(p);
   38833 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
   38834     sqlite3_mutex_enter(pcache1.mutex);
   38835     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -nFreed);
   38836     sqlite3_mutex_leave(pcache1.mutex);
   38837 #endif
   38838     sqlite3_free(p);
   38839   }
   38840   return nFreed;
   38841 }
   38842 
   38843 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
   38844 /*
   38845 ** Return the size of a pcache allocation
   38846 */
   38847 static int pcache1MemSize(void *p){
   38848   if( p>=pcache1.pStart && p<pcache1.pEnd ){
   38849     return pcache1.szSlot;
   38850   }else{
   38851     int iSize;
   38852     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
   38853     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
   38854     iSize = sqlite3MallocSize(p);
   38855     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
   38856     return iSize;
   38857   }
   38858 }
   38859 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
   38860 
   38861 /*
   38862 ** Allocate a new page object initially associated with cache pCache.
   38863 */
   38864 static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
   38865   PgHdr1 *p = 0;
   38866   void *pPg;
   38867 
   38868   /* The group mutex must be released before pcache1Alloc() is called. This
   38869   ** is because it may call sqlite3_release_memory(), which assumes that
   38870   ** this mutex is not held. */
   38871   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
   38872   pcache1LeaveMutex(pCache->pGroup);
   38873 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
   38874   pPg = pcache1Alloc(pCache->szPage);
   38875   p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
   38876   if( !pPg || !p ){
   38877     pcache1Free(pPg);
   38878     sqlite3_free(p);
   38879     pPg = 0;
   38880   }
   38881 #else
   38882   pPg = pcache1Alloc(sizeof(PgHdr1) + pCache->szPage + pCache->szExtra);
   38883   p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
   38884 #endif
   38885   pcache1EnterMutex(pCache->pGroup);
   38886 
   38887   if( pPg ){
   38888     p->page.pBuf = pPg;
   38889     p->page.pExtra = &p[1];
   38890     if( pCache->bPurgeable ){
   38891       pCache->pGroup->nCurrentPage++;
   38892     }
   38893     return p;
   38894   }
   38895   return 0;
   38896 }
   38897 
   38898 /*
   38899 ** Free a page object allocated by pcache1AllocPage().
   38900 **
   38901 ** The pointer is allowed to be NULL, which is prudent.  But it turns out
   38902 ** that the current implementation happens to never call this routine
   38903 ** with a NULL pointer, so we mark the NULL test with ALWAYS().
   38904 */
   38905 static void pcache1FreePage(PgHdr1 *p){
   38906   if( ALWAYS(p) ){
   38907     PCache1 *pCache = p->pCache;
   38908     assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
   38909     pcache1Free(p->page.pBuf);
   38910 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
   38911     sqlite3_free(p);
   38912 #endif
   38913     if( pCache->bPurgeable ){
   38914       pCache->pGroup->nCurrentPage--;
   38915     }
   38916   }
   38917 }
   38918 
   38919 /*
   38920 ** Malloc function used by SQLite to obtain space from the buffer configured
   38921 ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
   38922 ** exists, this function falls back to sqlite3Malloc().
   38923 */
   38924 SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
   38925   return pcache1Alloc(sz);
   38926 }
   38927 
   38928 /*
   38929 ** Free an allocated buffer obtained from sqlite3PageMalloc().
   38930 */
   38931 SQLITE_PRIVATE void sqlite3PageFree(void *p){
   38932   pcache1Free(p);
   38933 }
   38934 
   38935 
   38936 /*
   38937 ** Return true if it desirable to avoid allocating a new page cache
   38938 ** entry.
   38939 **
   38940 ** If memory was allocated specifically to the page cache using
   38941 ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
   38942 ** it is desirable to avoid allocating a new page cache entry because
   38943 ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
   38944 ** for all page cache needs and we should not need to spill the
   38945 ** allocation onto the heap.
   38946 **
   38947 ** Or, the heap is used for all page cache memory but the heap is
   38948 ** under memory pressure, then again it is desirable to avoid
   38949 ** allocating a new page cache entry in order to avoid stressing
   38950 ** the heap even further.
   38951 */
   38952 static int pcache1UnderMemoryPressure(PCache1 *pCache){
   38953   if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
   38954     return pcache1.bUnderPressure;
   38955   }else{
   38956     return sqlite3HeapNearlyFull();
   38957   }
   38958 }
   38959 
   38960 /******************************************************************************/
   38961 /******** General Implementation Functions ************************************/
   38962 
   38963 /*
   38964 ** This function is used to resize the hash table used by the cache passed
   38965 ** as the first argument.
   38966 **
   38967 ** The PCache mutex must be held when this function is called.
   38968 */
   38969 static int pcache1ResizeHash(PCache1 *p){
   38970   PgHdr1 **apNew;
   38971   unsigned int nNew;
   38972   unsigned int i;
   38973 
   38974   assert( sqlite3_mutex_held(p->pGroup->mutex) );
   38975 
   38976   nNew = p->nHash*2;
   38977   if( nNew<256 ){
   38978     nNew = 256;
   38979   }
   38980 
   38981   pcache1LeaveMutex(p->pGroup);
   38982   if( p->nHash ){ sqlite3BeginBenignMalloc(); }
   38983   apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
   38984   if( p->nHash ){ sqlite3EndBenignMalloc(); }
   38985   pcache1EnterMutex(p->pGroup);
   38986   if( apNew ){
   38987     for(i=0; i<p->nHash; i++){
   38988       PgHdr1 *pPage;
   38989       PgHdr1 *pNext = p->apHash[i];
   38990       while( (pPage = pNext)!=0 ){
   38991         unsigned int h = pPage->iKey % nNew;
   38992         pNext = pPage->pNext;
   38993         pPage->pNext = apNew[h];
   38994         apNew[h] = pPage;
   38995       }
   38996     }
   38997     sqlite3_free(p->apHash);
   38998     p->apHash = apNew;
   38999     p->nHash = nNew;
   39000   }
   39001 
   39002   return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
   39003 }
   39004 
   39005 /*
   39006 ** This function is used internally to remove the page pPage from the
   39007 ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
   39008 ** LRU list, then this function is a no-op.
   39009 **
   39010 ** The PGroup mutex must be held when this function is called.
   39011 */
   39012 static void pcache1PinPage(PgHdr1 *pPage){
   39013   PCache1 *pCache;
   39014   PGroup *pGroup;
   39015 
   39016   assert( pPage!=0 );
   39017   assert( pPage->isPinned==0 );
   39018   pCache = pPage->pCache;
   39019   pGroup = pCache->pGroup;
   39020   assert( pPage->pLruNext || pPage==pGroup->pLruTail );
   39021   assert( pPage->pLruPrev || pPage==pGroup->pLruHead );
   39022   assert( sqlite3_mutex_held(pGroup->mutex) );
   39023   if( pPage->pLruPrev ){
   39024     pPage->pLruPrev->pLruNext = pPage->pLruNext;
   39025   }else{
   39026     pGroup->pLruHead = pPage->pLruNext;
   39027   }
   39028   if( pPage->pLruNext ){
   39029     pPage->pLruNext->pLruPrev = pPage->pLruPrev;
   39030   }else{
   39031     pGroup->pLruTail = pPage->pLruPrev;
   39032   }
   39033   pPage->pLruNext = 0;
   39034   pPage->pLruPrev = 0;
   39035   pPage->isPinned = 1;
   39036   pCache->nRecyclable--;
   39037 }
   39038 
   39039 
   39040 /*
   39041 ** Remove the page supplied as an argument from the hash table
   39042 ** (PCache1.apHash structure) that it is currently stored in.
   39043 **
   39044 ** The PGroup mutex must be held when this function is called.
   39045 */
   39046 static void pcache1RemoveFromHash(PgHdr1 *pPage){
   39047   unsigned int h;
   39048   PCache1 *pCache = pPage->pCache;
   39049   PgHdr1 **pp;
   39050 
   39051   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
   39052   h = pPage->iKey % pCache->nHash;
   39053   for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
   39054   *pp = (*pp)->pNext;
   39055 
   39056   pCache->nPage--;
   39057 }
   39058 
   39059 /*
   39060 ** If there are currently more than nMaxPage pages allocated, try
   39061 ** to recycle pages to reduce the number allocated to nMaxPage.
   39062 */
   39063 static void pcache1EnforceMaxPage(PGroup *pGroup){
   39064   assert( sqlite3_mutex_held(pGroup->mutex) );
   39065   while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
   39066     PgHdr1 *p = pGroup->pLruTail;
   39067     assert( p->pCache->pGroup==pGroup );
   39068     assert( p->isPinned==0 );
   39069     pcache1PinPage(p);
   39070     pcache1RemoveFromHash(p);
   39071     pcache1FreePage(p);
   39072   }
   39073 }
   39074 
   39075 /*
   39076 ** Discard all pages from cache pCache with a page number (key value)
   39077 ** greater than or equal to iLimit. Any pinned pages that meet this
   39078 ** criteria are unpinned before they are discarded.
   39079 **
   39080 ** The PCache mutex must be held when this function is called.
   39081 */
   39082 static void pcache1TruncateUnsafe(
   39083   PCache1 *pCache,             /* The cache to truncate */
   39084   unsigned int iLimit          /* Drop pages with this pgno or larger */
   39085 ){
   39086   TESTONLY( unsigned int nPage = 0; )  /* To assert pCache->nPage is correct */
   39087   unsigned int h;
   39088   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
   39089   for(h=0; h<pCache->nHash; h++){
   39090     PgHdr1 **pp = &pCache->apHash[h];
   39091     PgHdr1 *pPage;
   39092     while( (pPage = *pp)!=0 ){
   39093       if( pPage->iKey>=iLimit ){
   39094         pCache->nPage--;
   39095         *pp = pPage->pNext;
   39096         if( !pPage->isPinned ) pcache1PinPage(pPage);
   39097         pcache1FreePage(pPage);
   39098       }else{
   39099         pp = &pPage->pNext;
   39100         TESTONLY( nPage++; )
   39101       }
   39102     }
   39103   }
   39104   assert( pCache->nPage==nPage );
   39105 }
   39106 
   39107 /******************************************************************************/
   39108 /******** sqlite3_pcache Methods **********************************************/
   39109 
   39110 /*
   39111 ** Implementation of the sqlite3_pcache.xInit method.
   39112 */
   39113 static int pcache1Init(void *NotUsed){
   39114   UNUSED_PARAMETER(NotUsed);
   39115   assert( pcache1.isInit==0 );
   39116   memset(&pcache1, 0, sizeof(pcache1));
   39117   if( sqlite3GlobalConfig.bCoreMutex ){
   39118     pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
   39119     pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
   39120   }
   39121   pcache1.grp.mxPinned = 10;
   39122   pcache1.isInit = 1;
   39123   return SQLITE_OK;
   39124 }
   39125 
   39126 /*
   39127 ** Implementation of the sqlite3_pcache.xShutdown method.
   39128 ** Note that the static mutex allocated in xInit does
   39129 ** not need to be freed.
   39130 */
   39131 static void pcache1Shutdown(void *NotUsed){
   39132   UNUSED_PARAMETER(NotUsed);
   39133   assert( pcache1.isInit!=0 );
   39134   memset(&pcache1, 0, sizeof(pcache1));
   39135 }
   39136 
   39137 /*
   39138 ** Implementation of the sqlite3_pcache.xCreate method.
   39139 **
   39140 ** Allocate a new cache.
   39141 */
   39142 static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
   39143   PCache1 *pCache;      /* The newly created page cache */
   39144   PGroup *pGroup;       /* The group the new page cache will belong to */
   39145   int sz;               /* Bytes of memory required to allocate the new cache */
   39146 
   39147   /*
   39148   ** The separateCache variable is true if each PCache has its own private
   39149   ** PGroup.  In other words, separateCache is true for mode (1) where no
   39150   ** mutexing is required.
   39151   **
   39152   **   *  Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
   39153   **
   39154   **   *  Always use a unified cache in single-threaded applications
   39155   **
   39156   **   *  Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
   39157   **      use separate caches (mode-1)
   39158   */
   39159 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
   39160   const int separateCache = 0;
   39161 #else
   39162   int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
   39163 #endif
   39164 
   39165   assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
   39166   assert( szExtra < 300 );
   39167 
   39168   sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
   39169   pCache = (PCache1 *)sqlite3MallocZero(sz);
   39170   if( pCache ){
   39171     if( separateCache ){
   39172       pGroup = (PGroup*)&pCache[1];
   39173       pGroup->mxPinned = 10;
   39174     }else{
   39175       pGroup = &pcache1.grp;
   39176     }
   39177     pCache->pGroup = pGroup;
   39178     pCache->szPage = szPage;
   39179     pCache->szExtra = szExtra;
   39180     pCache->bPurgeable = (bPurgeable ? 1 : 0);
   39181     if( bPurgeable ){
   39182       pCache->nMin = 10;
   39183       pcache1EnterMutex(pGroup);
   39184       pGroup->nMinPage += pCache->nMin;
   39185       pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
   39186       pcache1LeaveMutex(pGroup);
   39187     }
   39188   }
   39189   return (sqlite3_pcache *)pCache;
   39190 }
   39191 
   39192 /*
   39193 ** Implementation of the sqlite3_pcache.xCachesize method.
   39194 **
   39195 ** Configure the cache_size limit for a cache.
   39196 */
   39197 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
   39198   PCache1 *pCache = (PCache1 *)p;
   39199   if( pCache->bPurgeable ){
   39200     PGroup *pGroup = pCache->pGroup;
   39201     pcache1EnterMutex(pGroup);
   39202     pGroup->nMaxPage += (nMax - pCache->nMax);
   39203     pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
   39204     pCache->nMax = nMax;
   39205     pCache->n90pct = pCache->nMax*9/10;
   39206     pcache1EnforceMaxPage(pGroup);
   39207     pcache1LeaveMutex(pGroup);
   39208   }
   39209 }
   39210 
   39211 /*
   39212 ** Implementation of the sqlite3_pcache.xShrink method.
   39213 **
   39214 ** Free up as much memory as possible.
   39215 */
   39216 static void pcache1Shrink(sqlite3_pcache *p){
   39217   PCache1 *pCache = (PCache1*)p;
   39218   if( pCache->bPurgeable ){
   39219     PGroup *pGroup = pCache->pGroup;
   39220     int savedMaxPage;
   39221     pcache1EnterMutex(pGroup);
   39222     savedMaxPage = pGroup->nMaxPage;
   39223     pGroup->nMaxPage = 0;
   39224     pcache1EnforceMaxPage(pGroup);
   39225     pGroup->nMaxPage = savedMaxPage;
   39226     pcache1LeaveMutex(pGroup);
   39227   }
   39228 }
   39229 
   39230 /*
   39231 ** Implementation of the sqlite3_pcache.xPagecount method.
   39232 */
   39233 static int pcache1Pagecount(sqlite3_pcache *p){
   39234   int n;
   39235   PCache1 *pCache = (PCache1*)p;
   39236   pcache1EnterMutex(pCache->pGroup);
   39237   n = pCache->nPage;
   39238   pcache1LeaveMutex(pCache->pGroup);
   39239   return n;
   39240 }
   39241 
   39242 /*
   39243 ** Implementation of the sqlite3_pcache.xFetch method.
   39244 **
   39245 ** Fetch a page by key value.
   39246 **
   39247 ** Whether or not a new page may be allocated by this function depends on
   39248 ** the value of the createFlag argument.  0 means do not allocate a new
   39249 ** page.  1 means allocate a new page if space is easily available.  2
   39250 ** means to try really hard to allocate a new page.
   39251 **
   39252 ** For a non-purgeable cache (a cache used as the storage for an in-memory
   39253 ** database) there is really no difference between createFlag 1 and 2.  So
   39254 ** the calling function (pcache.c) will never have a createFlag of 1 on
   39255 ** a non-purgeable cache.
   39256 **
   39257 ** There are three different approaches to obtaining space for a page,
   39258 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
   39259 **
   39260 **   1. Regardless of the value of createFlag, the cache is searched for a
   39261 **      copy of the requested page. If one is found, it is returned.
   39262 **
   39263 **   2. If createFlag==0 and the page is not already in the cache, NULL is
   39264 **      returned.
   39265 **
   39266 **   3. If createFlag is 1, and the page is not already in the cache, then
   39267 **      return NULL (do not allocate a new page) if any of the following
   39268 **      conditions are true:
   39269 **
   39270 **       (a) the number of pages pinned by the cache is greater than
   39271 **           PCache1.nMax, or
   39272 **
   39273 **       (b) the number of pages pinned by the cache is greater than
   39274 **           the sum of nMax for all purgeable caches, less the sum of
   39275 **           nMin for all other purgeable caches, or
   39276 **
   39277 **   4. If none of the first three conditions apply and the cache is marked
   39278 **      as purgeable, and if one of the following is true:
   39279 **
   39280 **       (a) The number of pages allocated for the cache is already
   39281 **           PCache1.nMax, or
   39282 **
   39283 **       (b) The number of pages allocated for all purgeable caches is
   39284 **           already equal to or greater than the sum of nMax for all
   39285 **           purgeable caches,
   39286 **
   39287 **       (c) The system is under memory pressure and wants to avoid
   39288 **           unnecessary pages cache entry allocations
   39289 **
   39290 **      then attempt to recycle a page from the LRU list. If it is the right
   39291 **      size, return the recycled buffer. Otherwise, free the buffer and
   39292 **      proceed to step 5.
   39293 **
   39294 **   5. Otherwise, allocate and return a new page buffer.
   39295 */
   39296 static sqlite3_pcache_page *pcache1Fetch(
   39297   sqlite3_pcache *p,
   39298   unsigned int iKey,
   39299   int createFlag
   39300 ){
   39301   unsigned int nPinned;
   39302   PCache1 *pCache = (PCache1 *)p;
   39303   PGroup *pGroup;
   39304   PgHdr1 *pPage = 0;
   39305 
   39306   assert( offsetof(PgHdr1,page)==0 );
   39307   assert( pCache->bPurgeable || createFlag!=1 );
   39308   assert( pCache->bPurgeable || pCache->nMin==0 );
   39309   assert( pCache->bPurgeable==0 || pCache->nMin==10 );
   39310   assert( pCache->nMin==0 || pCache->bPurgeable );
   39311   pcache1EnterMutex(pGroup = pCache->pGroup);
   39312 
   39313   /* Step 1: Search the hash table for an existing entry. */
   39314   if( pCache->nHash>0 ){
   39315     unsigned int h = iKey % pCache->nHash;
   39316     for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
   39317   }
   39318 
   39319   /* Step 2: Abort if no existing page is found and createFlag is 0 */
   39320   if( pPage ){
   39321     if( !pPage->isPinned ) pcache1PinPage(pPage);
   39322     goto fetch_out;
   39323   }
   39324   if( createFlag==0 ){
   39325     goto fetch_out;
   39326   }
   39327 
   39328   /* The pGroup local variable will normally be initialized by the
   39329   ** pcache1EnterMutex() macro above.  But if SQLITE_MUTEX_OMIT is defined,
   39330   ** then pcache1EnterMutex() is a no-op, so we have to initialize the
   39331   ** local variable here.  Delaying the initialization of pGroup is an
   39332   ** optimization:  The common case is to exit the module before reaching
   39333   ** this point.
   39334   */
   39335 #ifdef SQLITE_MUTEX_OMIT
   39336   pGroup = pCache->pGroup;
   39337 #endif
   39338 
   39339   /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
   39340   assert( pCache->nPage >= pCache->nRecyclable );
   39341   nPinned = pCache->nPage - pCache->nRecyclable;
   39342   assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
   39343   assert( pCache->n90pct == pCache->nMax*9/10 );
   39344   if( createFlag==1 && (
   39345         nPinned>=pGroup->mxPinned
   39346      || nPinned>=pCache->n90pct
   39347      || pcache1UnderMemoryPressure(pCache)
   39348   )){
   39349     goto fetch_out;
   39350   }
   39351 
   39352   if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
   39353     goto fetch_out;
   39354   }
   39355   assert( pCache->nHash>0 && pCache->apHash );
   39356 
   39357   /* Step 4. Try to recycle a page. */
   39358   if( pCache->bPurgeable && pGroup->pLruTail && (
   39359          (pCache->nPage+1>=pCache->nMax)
   39360       || pGroup->nCurrentPage>=pGroup->nMaxPage
   39361       || pcache1UnderMemoryPressure(pCache)
   39362   )){
   39363     PCache1 *pOther;
   39364     pPage = pGroup->pLruTail;
   39365     assert( pPage->isPinned==0 );
   39366     pcache1RemoveFromHash(pPage);
   39367     pcache1PinPage(pPage);
   39368     pOther = pPage->pCache;
   39369 
   39370     /* We want to verify that szPage and szExtra are the same for pOther
   39371     ** and pCache.  Assert that we can verify this by comparing sums. */
   39372     assert( (pCache->szPage & (pCache->szPage-1))==0 && pCache->szPage>=512 );
   39373     assert( pCache->szExtra<512 );
   39374     assert( (pOther->szPage & (pOther->szPage-1))==0 && pOther->szPage>=512 );
   39375     assert( pOther->szExtra<512 );
   39376 
   39377     if( pOther->szPage+pOther->szExtra != pCache->szPage+pCache->szExtra ){
   39378       pcache1FreePage(pPage);
   39379       pPage = 0;
   39380     }else{
   39381       pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
   39382     }
   39383   }
   39384 
   39385   /* Step 5. If a usable page buffer has still not been found,
   39386   ** attempt to allocate a new one.
   39387   */
   39388   if( !pPage ){
   39389     if( createFlag==1 ) sqlite3BeginBenignMalloc();
   39390     pPage = pcache1AllocPage(pCache);
   39391     if( createFlag==1 ) sqlite3EndBenignMalloc();
   39392   }
   39393 
   39394   if( pPage ){
   39395     unsigned int h = iKey % pCache->nHash;
   39396     pCache->nPage++;
   39397     pPage->iKey = iKey;
   39398     pPage->pNext = pCache->apHash[h];
   39399     pPage->pCache = pCache;
   39400     pPage->pLruPrev = 0;
   39401     pPage->pLruNext = 0;
   39402     pPage->isPinned = 1;
   39403     *(void **)pPage->page.pExtra = 0;
   39404     pCache->apHash[h] = pPage;
   39405   }
   39406 
   39407 fetch_out:
   39408   if( pPage && iKey>pCache->iMaxKey ){
   39409     pCache->iMaxKey = iKey;
   39410   }
   39411   pcache1LeaveMutex(pGroup);
   39412   return (sqlite3_pcache_page*)pPage;
   39413 }
   39414 
   39415 
   39416 /*
   39417 ** Implementation of the sqlite3_pcache.xUnpin method.
   39418 **
   39419 ** Mark a page as unpinned (eligible for asynchronous recycling).
   39420 */
   39421 static void pcache1Unpin(
   39422   sqlite3_pcache *p,
   39423   sqlite3_pcache_page *pPg,
   39424   int reuseUnlikely
   39425 ){
   39426   PCache1 *pCache = (PCache1 *)p;
   39427   PgHdr1 *pPage = (PgHdr1 *)pPg;
   39428   PGroup *pGroup = pCache->pGroup;
   39429 
   39430   assert( pPage->pCache==pCache );
   39431   pcache1EnterMutex(pGroup);
   39432 
   39433   /* It is an error to call this function if the page is already
   39434   ** part of the PGroup LRU list.
   39435   */
   39436   assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
   39437   assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
   39438   assert( pPage->isPinned==1 );
   39439 
   39440   if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
   39441     pcache1RemoveFromHash(pPage);
   39442     pcache1FreePage(pPage);
   39443   }else{
   39444     /* Add the page to the PGroup LRU list. */
   39445     if( pGroup->pLruHead ){
   39446       pGroup->pLruHead->pLruPrev = pPage;
   39447       pPage->pLruNext = pGroup->pLruHead;
   39448       pGroup->pLruHead = pPage;
   39449     }else{
   39450       pGroup->pLruTail = pPage;
   39451       pGroup->pLruHead = pPage;
   39452     }
   39453     pCache->nRecyclable++;
   39454     pPage->isPinned = 0;
   39455   }
   39456 
   39457   pcache1LeaveMutex(pCache->pGroup);
   39458 }
   39459 
   39460 /*
   39461 ** Implementation of the sqlite3_pcache.xRekey method.
   39462 */
   39463 static void pcache1Rekey(
   39464   sqlite3_pcache *p,
   39465   sqlite3_pcache_page *pPg,
   39466   unsigned int iOld,
   39467   unsigned int iNew
   39468 ){
   39469   PCache1 *pCache = (PCache1 *)p;
   39470   PgHdr1 *pPage = (PgHdr1 *)pPg;
   39471   PgHdr1 **pp;
   39472   unsigned int h;
   39473   assert( pPage->iKey==iOld );
   39474   assert( pPage->pCache==pCache );
   39475 
   39476   pcache1EnterMutex(pCache->pGroup);
   39477 
   39478   h = iOld%pCache->nHash;
   39479   pp = &pCache->apHash[h];
   39480   while( (*pp)!=pPage ){
   39481     pp = &(*pp)->pNext;
   39482   }
   39483   *pp = pPage->pNext;
   39484 
   39485   h = iNew%pCache->nHash;
   39486   pPage->iKey = iNew;
   39487   pPage->pNext = pCache->apHash[h];
   39488   pCache->apHash[h] = pPage;
   39489   if( iNew>pCache->iMaxKey ){
   39490     pCache->iMaxKey = iNew;
   39491   }
   39492 
   39493   pcache1LeaveMutex(pCache->pGroup);
   39494 }
   39495 
   39496 /*
   39497 ** Implementation of the sqlite3_pcache.xTruncate method.
   39498 **
   39499 ** Discard all unpinned pages in the cache with a page number equal to
   39500 ** or greater than parameter iLimit. Any pinned pages with a page number
   39501 ** equal to or greater than iLimit are implicitly unpinned.
   39502 */
   39503 static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
   39504   PCache1 *pCache = (PCache1 *)p;
   39505   pcache1EnterMutex(pCache->pGroup);
   39506   if( iLimit<=pCache->iMaxKey ){
   39507     pcache1TruncateUnsafe(pCache, iLimit);
   39508     pCache->iMaxKey = iLimit-1;
   39509   }
   39510   pcache1LeaveMutex(pCache->pGroup);
   39511 }
   39512 
   39513 /*
   39514 ** Implementation of the sqlite3_pcache.xDestroy method.
   39515 **
   39516 ** Destroy a cache allocated using pcache1Create().
   39517 */
   39518 static void pcache1Destroy(sqlite3_pcache *p){
   39519   PCache1 *pCache = (PCache1 *)p;
   39520   PGroup *pGroup = pCache->pGroup;
   39521   assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
   39522   pcache1EnterMutex(pGroup);
   39523   pcache1TruncateUnsafe(pCache, 0);
   39524   assert( pGroup->nMaxPage >= pCache->nMax );
   39525   pGroup->nMaxPage -= pCache->nMax;
   39526   assert( pGroup->nMinPage >= pCache->nMin );
   39527   pGroup->nMinPage -= pCache->nMin;
   39528   pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
   39529   pcache1EnforceMaxPage(pGroup);
   39530   pcache1LeaveMutex(pGroup);
   39531   sqlite3_free(pCache->apHash);
   39532   sqlite3_free(pCache);
   39533 }
   39534 
   39535 /*
   39536 ** This function is called during initialization (sqlite3_initialize()) to
   39537 ** install the default pluggable cache module, assuming the user has not
   39538 ** already provided an alternative.
   39539 */
   39540 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
   39541   static const sqlite3_pcache_methods2 defaultMethods = {
   39542     1,                       /* iVersion */
   39543     0,                       /* pArg */
   39544     pcache1Init,             /* xInit */
   39545     pcache1Shutdown,         /* xShutdown */
   39546     pcache1Create,           /* xCreate */
   39547     pcache1Cachesize,        /* xCachesize */
   39548     pcache1Pagecount,        /* xPagecount */
   39549     pcache1Fetch,            /* xFetch */
   39550     pcache1Unpin,            /* xUnpin */
   39551     pcache1Rekey,            /* xRekey */
   39552     pcache1Truncate,         /* xTruncate */
   39553     pcache1Destroy,          /* xDestroy */
   39554     pcache1Shrink            /* xShrink */
   39555   };
   39556   sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
   39557 }
   39558 
   39559 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
   39560 /*
   39561 ** This function is called to free superfluous dynamically allocated memory
   39562 ** held by the pager system. Memory in use by any SQLite pager allocated
   39563 ** by the current thread may be sqlite3_free()ed.
   39564 **
   39565 ** nReq is the number of bytes of memory required. Once this much has
   39566 ** been released, the function returns. The return value is the total number
   39567 ** of bytes of memory released.
   39568 */
   39569 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
   39570   int nFree = 0;
   39571   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
   39572   assert( sqlite3_mutex_notheld(pcache1.mutex) );
   39573   if( pcache1.pStart==0 ){
   39574     PgHdr1 *p;
   39575     pcache1EnterMutex(&pcache1.grp);
   39576     while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
   39577       nFree += pcache1MemSize(p->page.pBuf);
   39578 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
   39579       nFree += sqlite3MemSize(p);
   39580 #endif
   39581       assert( p->isPinned==0 );
   39582       pcache1PinPage(p);
   39583       pcache1RemoveFromHash(p);
   39584       pcache1FreePage(p);
   39585     }
   39586     pcache1LeaveMutex(&pcache1.grp);
   39587   }
   39588   return nFree;
   39589 }
   39590 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
   39591 
   39592 #ifdef SQLITE_TEST
   39593 /*
   39594 ** This function is used by test procedures to inspect the internal state
   39595 ** of the global cache.
   39596 */
   39597 SQLITE_PRIVATE void sqlite3PcacheStats(
   39598   int *pnCurrent,      /* OUT: Total number of pages cached */
   39599   int *pnMax,          /* OUT: Global maximum cache size */
   39600   int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
   39601   int *pnRecyclable    /* OUT: Total number of pages available for recycling */
   39602 ){
   39603   PgHdr1 *p;
   39604   int nRecyclable = 0;
   39605   for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
   39606     assert( p->isPinned==0 );
   39607     nRecyclable++;
   39608   }
   39609   *pnCurrent = pcache1.grp.nCurrentPage;
   39610   *pnMax = (int)pcache1.grp.nMaxPage;
   39611   *pnMin = (int)pcache1.grp.nMinPage;
   39612   *pnRecyclable = nRecyclable;
   39613 }
   39614 #endif
   39615 
   39616 /************** End of pcache1.c *********************************************/
   39617 /************** Begin file rowset.c ******************************************/
   39618 /*
   39619 ** 2008 December 3
   39620 **
   39621 ** The author disclaims copyright to this source code.  In place of
   39622 ** a legal notice, here is a blessing:
   39623 **
   39624 **    May you do good and not evil.
   39625 **    May you find forgiveness for yourself and forgive others.
   39626 **    May you share freely, never taking more than you give.
   39627 **
   39628 *************************************************************************
   39629 **
   39630 ** This module implements an object we call a "RowSet".
   39631 **
   39632 ** The RowSet object is a collection of rowids.  Rowids
   39633 ** are inserted into the RowSet in an arbitrary order.  Inserts
   39634 ** can be intermixed with tests to see if a given rowid has been
   39635 ** previously inserted into the RowSet.
   39636 **
   39637 ** After all inserts are finished, it is possible to extract the
   39638 ** elements of the RowSet in sorted order.  Once this extraction
   39639 ** process has started, no new elements may be inserted.
   39640 **
   39641 ** Hence, the primitive operations for a RowSet are:
   39642 **
   39643 **    CREATE
   39644 **    INSERT
   39645 **    TEST
   39646 **    SMALLEST
   39647 **    DESTROY
   39648 **
   39649 ** The CREATE and DESTROY primitives are the constructor and destructor,
   39650 ** obviously.  The INSERT primitive adds a new element to the RowSet.
   39651 ** TEST checks to see if an element is already in the RowSet.  SMALLEST
   39652 ** extracts the least value from the RowSet.
   39653 **
   39654 ** The INSERT primitive might allocate additional memory.  Memory is
   39655 ** allocated in chunks so most INSERTs do no allocation.  There is an
   39656 ** upper bound on the size of allocated memory.  No memory is freed
   39657 ** until DESTROY.
   39658 **
   39659 ** The TEST primitive includes a "batch" number.  The TEST primitive
   39660 ** will only see elements that were inserted before the last change
   39661 ** in the batch number.  In other words, if an INSERT occurs between
   39662 ** two TESTs where the TESTs have the same batch nubmer, then the
   39663 ** value added by the INSERT will not be visible to the second TEST.
   39664 ** The initial batch number is zero, so if the very first TEST contains
   39665 ** a non-zero batch number, it will see all prior INSERTs.
   39666 **
   39667 ** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
   39668 ** that is attempted.
   39669 **
   39670 ** The cost of an INSERT is roughly constant.  (Sometime new memory
   39671 ** has to be allocated on an INSERT.)  The cost of a TEST with a new
   39672 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
   39673 ** The cost of a TEST using the same batch number is O(logN).  The cost
   39674 ** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
   39675 ** primitives are constant time.  The cost of DESTROY is O(N).
   39676 **
   39677 ** There is an added cost of O(N) when switching between TEST and
   39678 ** SMALLEST primitives.
   39679 */
   39680 
   39681 
   39682 /*
   39683 ** Target size for allocation chunks.
   39684 */
   39685 #define ROWSET_ALLOCATION_SIZE 1024
   39686 
   39687 /*
   39688 ** The number of rowset entries per allocation chunk.
   39689 */
   39690 #define ROWSET_ENTRY_PER_CHUNK  \
   39691                        ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
   39692 
   39693 /*
   39694 ** Each entry in a RowSet is an instance of the following object.
   39695 **
   39696 ** This same object is reused to store a linked list of trees of RowSetEntry
   39697 ** objects.  In that alternative use, pRight points to the next entry
   39698 ** in the list, pLeft points to the tree, and v is unused.  The
   39699 ** RowSet.pForest value points to the head of this forest list.
   39700 */
   39701 struct RowSetEntry {
   39702   i64 v;                        /* ROWID value for this entry */
   39703   struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
   39704   struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
   39705 };
   39706 
   39707 /*
   39708 ** RowSetEntry objects are allocated in large chunks (instances of the
   39709 ** following structure) to reduce memory allocation overhead.  The
   39710 ** chunks are kept on a linked list so that they can be deallocated
   39711 ** when the RowSet is destroyed.
   39712 */
   39713 struct RowSetChunk {
   39714   struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
   39715   struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
   39716 };
   39717 
   39718 /*
   39719 ** A RowSet in an instance of the following structure.
   39720 **
   39721 ** A typedef of this structure if found in sqliteInt.h.
   39722 */
   39723 struct RowSet {
   39724   struct RowSetChunk *pChunk;    /* List of all chunk allocations */
   39725   sqlite3 *db;                   /* The database connection */
   39726   struct RowSetEntry *pEntry;    /* List of entries using pRight */
   39727   struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
   39728   struct RowSetEntry *pFresh;    /* Source of new entry objects */
   39729   struct RowSetEntry *pForest;   /* List of binary trees of entries */
   39730   u16 nFresh;                    /* Number of objects on pFresh */
   39731   u16 rsFlags;                   /* Various flags */
   39732   int iBatch;                    /* Current insert batch */
   39733 };
   39734 
   39735 /*
   39736 ** Allowed values for RowSet.rsFlags
   39737 */
   39738 #define ROWSET_SORTED  0x01   /* True if RowSet.pEntry is sorted */
   39739 #define ROWSET_NEXT    0x02   /* True if sqlite3RowSetNext() has been called */
   39740 
   39741 /*
   39742 ** Turn bulk memory into a RowSet object.  N bytes of memory
   39743 ** are available at pSpace.  The db pointer is used as a memory context
   39744 ** for any subsequent allocations that need to occur.
   39745 ** Return a pointer to the new RowSet object.
   39746 **
   39747 ** It must be the case that N is sufficient to make a Rowset.  If not
   39748 ** an assertion fault occurs.
   39749 **
   39750 ** If N is larger than the minimum, use the surplus as an initial
   39751 ** allocation of entries available to be filled.
   39752 */
   39753 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
   39754   RowSet *p;
   39755   assert( N >= ROUND8(sizeof(*p)) );
   39756   p = pSpace;
   39757   p->pChunk = 0;
   39758   p->db = db;
   39759   p->pEntry = 0;
   39760   p->pLast = 0;
   39761   p->pForest = 0;
   39762   p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
   39763   p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
   39764   p->rsFlags = ROWSET_SORTED;
   39765   p->iBatch = 0;
   39766   return p;
   39767 }
   39768 
   39769 /*
   39770 ** Deallocate all chunks from a RowSet.  This frees all memory that
   39771 ** the RowSet has allocated over its lifetime.  This routine is
   39772 ** the destructor for the RowSet.
   39773 */
   39774 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
   39775   struct RowSetChunk *pChunk, *pNextChunk;
   39776   for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
   39777     pNextChunk = pChunk->pNextChunk;
   39778     sqlite3DbFree(p->db, pChunk);
   39779   }
   39780   p->pChunk = 0;
   39781   p->nFresh = 0;
   39782   p->pEntry = 0;
   39783   p->pLast = 0;
   39784   p->pForest = 0;
   39785   p->rsFlags = ROWSET_SORTED;
   39786 }
   39787 
   39788 /*
   39789 ** Allocate a new RowSetEntry object that is associated with the
   39790 ** given RowSet.  Return a pointer to the new and completely uninitialized
   39791 ** objected.
   39792 **
   39793 ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
   39794 ** routine returns NULL.
   39795 */
   39796 static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
   39797   assert( p!=0 );
   39798   if( p->nFresh==0 ){
   39799     struct RowSetChunk *pNew;
   39800     pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
   39801     if( pNew==0 ){
   39802       return 0;
   39803     }
   39804     pNew->pNextChunk = p->pChunk;
   39805     p->pChunk = pNew;
   39806     p->pFresh = pNew->aEntry;
   39807     p->nFresh = ROWSET_ENTRY_PER_CHUNK;
   39808   }
   39809   p->nFresh--;
   39810   return p->pFresh++;
   39811 }
   39812 
   39813 /*
   39814 ** Insert a new value into a RowSet.
   39815 **
   39816 ** The mallocFailed flag of the database connection is set if a
   39817 ** memory allocation fails.
   39818 */
   39819 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
   39820   struct RowSetEntry *pEntry;  /* The new entry */
   39821   struct RowSetEntry *pLast;   /* The last prior entry */
   39822 
   39823   /* This routine is never called after sqlite3RowSetNext() */
   39824   assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
   39825 
   39826   pEntry = rowSetEntryAlloc(p);
   39827   if( pEntry==0 ) return;
   39828   pEntry->v = rowid;
   39829   pEntry->pRight = 0;
   39830   pLast = p->pLast;
   39831   if( pLast ){
   39832     if( (p->rsFlags & ROWSET_SORTED)!=0 && rowid<=pLast->v ){
   39833       p->rsFlags &= ~ROWSET_SORTED;
   39834     }
   39835     pLast->pRight = pEntry;
   39836   }else{
   39837     p->pEntry = pEntry;
   39838   }
   39839   p->pLast = pEntry;
   39840 }
   39841 
   39842 /*
   39843 ** Merge two lists of RowSetEntry objects.  Remove duplicates.
   39844 **
   39845 ** The input lists are connected via pRight pointers and are
   39846 ** assumed to each already be in sorted order.
   39847 */
   39848 static struct RowSetEntry *rowSetEntryMerge(
   39849   struct RowSetEntry *pA,    /* First sorted list to be merged */
   39850   struct RowSetEntry *pB     /* Second sorted list to be merged */
   39851 ){
   39852   struct RowSetEntry head;
   39853   struct RowSetEntry *pTail;
   39854 
   39855   pTail = &head;
   39856   while( pA && pB ){
   39857     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
   39858     assert( pB->pRight==0 || pB->v<=pB->pRight->v );
   39859     if( pA->v<pB->v ){
   39860       pTail->pRight = pA;
   39861       pA = pA->pRight;
   39862       pTail = pTail->pRight;
   39863     }else if( pB->v<pA->v ){
   39864       pTail->pRight = pB;
   39865       pB = pB->pRight;
   39866       pTail = pTail->pRight;
   39867     }else{
   39868       pA = pA->pRight;
   39869     }
   39870   }
   39871   if( pA ){
   39872     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
   39873     pTail->pRight = pA;
   39874   }else{
   39875     assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
   39876     pTail->pRight = pB;
   39877   }
   39878   return head.pRight;
   39879 }
   39880 
   39881 /*
   39882 ** Sort all elements on the list of RowSetEntry objects into order of
   39883 ** increasing v.
   39884 */
   39885 static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
   39886   unsigned int i;
   39887   struct RowSetEntry *pNext, *aBucket[40];
   39888 
   39889   memset(aBucket, 0, sizeof(aBucket));
   39890   while( pIn ){
   39891     pNext = pIn->pRight;
   39892     pIn->pRight = 0;
   39893     for(i=0; aBucket[i]; i++){
   39894       pIn = rowSetEntryMerge(aBucket[i], pIn);
   39895       aBucket[i] = 0;
   39896     }
   39897     aBucket[i] = pIn;
   39898     pIn = pNext;
   39899   }
   39900   pIn = 0;
   39901   for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
   39902     pIn = rowSetEntryMerge(pIn, aBucket[i]);
   39903   }
   39904   return pIn;
   39905 }
   39906 
   39907 
   39908 /*
   39909 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
   39910 ** Convert this tree into a linked list connected by the pRight pointers
   39911 ** and return pointers to the first and last elements of the new list.
   39912 */
   39913 static void rowSetTreeToList(
   39914   struct RowSetEntry *pIn,         /* Root of the input tree */
   39915   struct RowSetEntry **ppFirst,    /* Write head of the output list here */
   39916   struct RowSetEntry **ppLast      /* Write tail of the output list here */
   39917 ){
   39918   assert( pIn!=0 );
   39919   if( pIn->pLeft ){
   39920     struct RowSetEntry *p;
   39921     rowSetTreeToList(pIn->pLeft, ppFirst, &p);
   39922     p->pRight = pIn;
   39923   }else{
   39924     *ppFirst = pIn;
   39925   }
   39926   if( pIn->pRight ){
   39927     rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
   39928   }else{
   39929     *ppLast = pIn;
   39930   }
   39931   assert( (*ppLast)->pRight==0 );
   39932 }
   39933 
   39934 
   39935 /*
   39936 ** Convert a sorted list of elements (connected by pRight) into a binary
   39937 ** tree with depth of iDepth.  A depth of 1 means the tree contains a single
   39938 ** node taken from the head of *ppList.  A depth of 2 means a tree with
   39939 ** three nodes.  And so forth.
   39940 **
   39941 ** Use as many entries from the input list as required and update the
   39942 ** *ppList to point to the unused elements of the list.  If the input
   39943 ** list contains too few elements, then construct an incomplete tree
   39944 ** and leave *ppList set to NULL.
   39945 **
   39946 ** Return a pointer to the root of the constructed binary tree.
   39947 */
   39948 static struct RowSetEntry *rowSetNDeepTree(
   39949   struct RowSetEntry **ppList,
   39950   int iDepth
   39951 ){
   39952   struct RowSetEntry *p;         /* Root of the new tree */
   39953   struct RowSetEntry *pLeft;     /* Left subtree */
   39954   if( *ppList==0 ){
   39955     return 0;
   39956   }
   39957   if( iDepth==1 ){
   39958     p = *ppList;
   39959     *ppList = p->pRight;
   39960     p->pLeft = p->pRight = 0;
   39961     return p;
   39962   }
   39963   pLeft = rowSetNDeepTree(ppList, iDepth-1);
   39964   p = *ppList;
   39965   if( p==0 ){
   39966     return pLeft;
   39967   }
   39968   p->pLeft = pLeft;
   39969   *ppList = p->pRight;
   39970   p->pRight = rowSetNDeepTree(ppList, iDepth-1);
   39971   return p;
   39972 }
   39973 
   39974 /*
   39975 ** Convert a sorted list of elements into a binary tree. Make the tree
   39976 ** as deep as it needs to be in order to contain the entire list.
   39977 */
   39978 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
   39979   int iDepth;           /* Depth of the tree so far */
   39980   struct RowSetEntry *p;       /* Current tree root */
   39981   struct RowSetEntry *pLeft;   /* Left subtree */
   39982 
   39983   assert( pList!=0 );
   39984   p = pList;
   39985   pList = p->pRight;
   39986   p->pLeft = p->pRight = 0;
   39987   for(iDepth=1; pList; iDepth++){
   39988     pLeft = p;
   39989     p = pList;
   39990     pList = p->pRight;
   39991     p->pLeft = pLeft;
   39992     p->pRight = rowSetNDeepTree(&pList, iDepth);
   39993   }
   39994   return p;
   39995 }
   39996 
   39997 /*
   39998 ** Take all the entries on p->pEntry and on the trees in p->pForest and
   39999 ** sort them all together into one big ordered list on p->pEntry.
   40000 **
   40001 ** This routine should only be called once in the life of a RowSet.
   40002 */
   40003 static void rowSetToList(RowSet *p){
   40004 
   40005   /* This routine is called only once */
   40006   assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
   40007 
   40008   if( (p->rsFlags & ROWSET_SORTED)==0 ){
   40009     p->pEntry = rowSetEntrySort(p->pEntry);
   40010   }
   40011 
   40012   /* While this module could theoretically support it, sqlite3RowSetNext()
   40013   ** is never called after sqlite3RowSetText() for the same RowSet.  So
   40014   ** there is never a forest to deal with.  Should this change, simply
   40015   ** remove the assert() and the #if 0. */
   40016   assert( p->pForest==0 );
   40017 #if 0
   40018   while( p->pForest ){
   40019     struct RowSetEntry *pTree = p->pForest->pLeft;
   40020     if( pTree ){
   40021       struct RowSetEntry *pHead, *pTail;
   40022       rowSetTreeToList(pTree, &pHead, &pTail);
   40023       p->pEntry = rowSetEntryMerge(p->pEntry, pHead);
   40024     }
   40025     p->pForest = p->pForest->pRight;
   40026   }
   40027 #endif
   40028   p->rsFlags |= ROWSET_NEXT;  /* Verify this routine is never called again */
   40029 }
   40030 
   40031 /*
   40032 ** Extract the smallest element from the RowSet.
   40033 ** Write the element into *pRowid.  Return 1 on success.  Return
   40034 ** 0 if the RowSet is already empty.
   40035 **
   40036 ** After this routine has been called, the sqlite3RowSetInsert()
   40037 ** routine may not be called again.
   40038 */
   40039 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
   40040   assert( p!=0 );
   40041 
   40042   /* Merge the forest into a single sorted list on first call */
   40043   if( (p->rsFlags & ROWSET_NEXT)==0 ) rowSetToList(p);
   40044 
   40045   /* Return the next entry on the list */
   40046   if( p->pEntry ){
   40047     *pRowid = p->pEntry->v;
   40048     p->pEntry = p->pEntry->pRight;
   40049     if( p->pEntry==0 ){
   40050       sqlite3RowSetClear(p);
   40051     }
   40052     return 1;
   40053   }else{
   40054     return 0;
   40055   }
   40056 }
   40057 
   40058 /*
   40059 ** Check to see if element iRowid was inserted into the rowset as
   40060 ** part of any insert batch prior to iBatch.  Return 1 or 0.
   40061 **
   40062 ** If this is the first test of a new batch and if there exist entires
   40063 ** on pRowSet->pEntry, then sort those entires into the forest at
   40064 ** pRowSet->pForest so that they can be tested.
   40065 */
   40066 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){
   40067   struct RowSetEntry *p, *pTree;
   40068 
   40069   /* This routine is never called after sqlite3RowSetNext() */
   40070   assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
   40071 
   40072   /* Sort entries into the forest on the first test of a new batch
   40073   */
   40074   if( iBatch!=pRowSet->iBatch ){
   40075     p = pRowSet->pEntry;
   40076     if( p ){
   40077       struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
   40078       if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){
   40079         p = rowSetEntrySort(p);
   40080       }
   40081       for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
   40082         ppPrevTree = &pTree->pRight;
   40083         if( pTree->pLeft==0 ){
   40084           pTree->pLeft = rowSetListToTree(p);
   40085           break;
   40086         }else{
   40087           struct RowSetEntry *pAux, *pTail;
   40088           rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
   40089           pTree->pLeft = 0;
   40090           p = rowSetEntryMerge(pAux, p);
   40091         }
   40092       }
   40093       if( pTree==0 ){
   40094         *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
   40095         if( pTree ){
   40096           pTree->v = 0;
   40097           pTree->pRight = 0;
   40098           pTree->pLeft = rowSetListToTree(p);
   40099         }
   40100       }
   40101       pRowSet->pEntry = 0;
   40102       pRowSet->pLast = 0;
   40103       pRowSet->rsFlags |= ROWSET_SORTED;
   40104     }
   40105     pRowSet->iBatch = iBatch;
   40106   }
   40107 
   40108   /* Test to see if the iRowid value appears anywhere in the forest.
   40109   ** Return 1 if it does and 0 if not.
   40110   */
   40111   for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
   40112     p = pTree->pLeft;
   40113     while( p ){
   40114       if( p->v<iRowid ){
   40115         p = p->pRight;
   40116       }else if( p->v>iRowid ){
   40117         p = p->pLeft;
   40118       }else{
   40119         return 1;
   40120       }
   40121     }
   40122   }
   40123   return 0;
   40124 }
   40125 
   40126 /************** End of rowset.c **********************************************/
   40127 /************** Begin file pager.c *******************************************/
   40128 /*
   40129 ** 2001 September 15
   40130 **
   40131 ** The author disclaims copyright to this source code.  In place of
   40132 ** a legal notice, here is a blessing:
   40133 **
   40134 **    May you do good and not evil.
   40135 **    May you find forgiveness for yourself and forgive others.
   40136 **    May you share freely, never taking more than you give.
   40137 **
   40138 *************************************************************************
   40139 ** This is the implementation of the page cache subsystem or "pager".
   40140 **
   40141 ** The pager is used to access a database disk file.  It implements
   40142 ** atomic commit and rollback through the use of a journal file that
   40143 ** is separate from the database file.  The pager also implements file
   40144 ** locking to prevent two processes from writing the same database
   40145 ** file simultaneously, or one process from reading the database while
   40146 ** another is writing.
   40147 */
   40148 #ifndef SQLITE_OMIT_DISKIO
   40149 /************** Include wal.h in the middle of pager.c ***********************/
   40150 /************** Begin file wal.h *********************************************/
   40151 /*
   40152 ** 2010 February 1
   40153 **
   40154 ** The author disclaims copyright to this source code.  In place of
   40155 ** a legal notice, here is a blessing:
   40156 **
   40157 **    May you do good and not evil.
   40158 **    May you find forgiveness for yourself and forgive others.
   40159 **    May you share freely, never taking more than you give.
   40160 **
   40161 *************************************************************************
   40162 ** This header file defines the interface to the write-ahead logging
   40163 ** system. Refer to the comments below and the header comment attached to
   40164 ** the implementation of each function in log.c for further details.
   40165 */
   40166 
   40167 #ifndef _WAL_H_
   40168 #define _WAL_H_
   40169 
   40170 
   40171 /* Additional values that can be added to the sync_flags argument of
   40172 ** sqlite3WalFrames():
   40173 */
   40174 #define WAL_SYNC_TRANSACTIONS  0x20   /* Sync at the end of each transaction */
   40175 #define SQLITE_SYNC_MASK       0x13   /* Mask off the SQLITE_SYNC_* values */
   40176 
   40177 #ifdef SQLITE_OMIT_WAL
   40178 # define sqlite3WalOpen(x,y,z)                   0
   40179 # define sqlite3WalLimit(x,y)
   40180 # define sqlite3WalClose(w,x,y,z)                0
   40181 # define sqlite3WalBeginReadTransaction(y,z)     0
   40182 # define sqlite3WalEndReadTransaction(z)
   40183 # define sqlite3WalDbsize(y)                     0
   40184 # define sqlite3WalBeginWriteTransaction(y)      0
   40185 # define sqlite3WalEndWriteTransaction(x)        0
   40186 # define sqlite3WalUndo(x,y,z)                   0
   40187 # define sqlite3WalSavepoint(y,z)
   40188 # define sqlite3WalSavepointUndo(y,z)            0
   40189 # define sqlite3WalFrames(u,v,w,x,y,z)           0
   40190 # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
   40191 # define sqlite3WalCallback(z)                   0
   40192 # define sqlite3WalExclusiveMode(y,z)            0
   40193 # define sqlite3WalHeapMemory(z)                 0
   40194 # define sqlite3WalFramesize(z)                  0
   40195 # define sqlite3WalFindFrame(x,y,z)              0
   40196 #else
   40197 
   40198 #define WAL_SAVEPOINT_NDATA 4
   40199 
   40200 /* Connection to a write-ahead log (WAL) file.
   40201 ** There is one object of this type for each pager.
   40202 */
   40203 typedef struct Wal Wal;
   40204 
   40205 /* Open and close a connection to a write-ahead log. */
   40206 SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
   40207 SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
   40208 
   40209 /* Set the limiting size of a WAL file. */
   40210 SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
   40211 
   40212 /* Used by readers to open (lock) and close (unlock) a snapshot.  A
   40213 ** snapshot is like a read-transaction.  It is the state of the database
   40214 ** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
   40215 ** preserves the current state even if the other threads or processes
   40216 ** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
   40217 ** transaction and releases the lock.
   40218 */
   40219 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
   40220 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
   40221 
   40222 /* Read a page from the write-ahead log, if it is present. */
   40223 SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
   40224 SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
   40225 
   40226 /* If the WAL is not empty, return the size of the database. */
   40227 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
   40228 
   40229 /* Obtain or release the WRITER lock. */
   40230 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
   40231 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
   40232 
   40233 /* Undo any frames written (but not committed) to the log */
   40234 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
   40235 
   40236 /* Return an integer that records the current (uncommitted) write
   40237 ** position in the WAL */
   40238 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
   40239 
   40240 /* Move the write position of the WAL back to iFrame.  Called in
   40241 ** response to a ROLLBACK TO command. */
   40242 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
   40243 
   40244 /* Write a frame or frames to the log. */
   40245 SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
   40246 
   40247 /* Copy pages from the log to the database file */
   40248 SQLITE_PRIVATE int sqlite3WalCheckpoint(
   40249   Wal *pWal,                      /* Write-ahead log connection */
   40250   int eMode,                      /* One of PASSIVE, FULL and RESTART */
   40251   int (*xBusy)(void*),            /* Function to call when busy */
   40252   void *pBusyArg,                 /* Context argument for xBusyHandler */
   40253   int sync_flags,                 /* Flags to sync db file with (or 0) */
   40254   int nBuf,                       /* Size of buffer nBuf */
   40255   u8 *zBuf,                       /* Temporary buffer to use */
   40256   int *pnLog,                     /* OUT: Number of frames in WAL */
   40257   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
   40258 );
   40259 
   40260 /* Return the value to pass to a sqlite3_wal_hook callback, the
   40261 ** number of frames in the WAL at the point of the last commit since
   40262 ** sqlite3WalCallback() was called.  If no commits have occurred since
   40263 ** the last call, then return 0.
   40264 */
   40265 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
   40266 
   40267 /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
   40268 ** by the pager layer on the database file.
   40269 */
   40270 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
   40271 
   40272 /* Return true if the argument is non-NULL and the WAL module is using
   40273 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
   40274 ** WAL module is using shared-memory, return false.
   40275 */
   40276 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
   40277 
   40278 #ifdef SQLITE_ENABLE_ZIPVFS
   40279 /* If the WAL file is not empty, return the number of bytes of content
   40280 ** stored in each frame (i.e. the db page-size when the WAL was created).
   40281 */
   40282 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
   40283 #endif
   40284 
   40285 #endif /* ifndef SQLITE_OMIT_WAL */
   40286 #endif /* _WAL_H_ */
   40287 
   40288 /************** End of wal.h *************************************************/
   40289 /************** Continuing where we left off in pager.c **********************/
   40290 
   40291 
   40292 /******************* NOTES ON THE DESIGN OF THE PAGER ************************
   40293 **
   40294 ** This comment block describes invariants that hold when using a rollback
   40295 ** journal.  These invariants do not apply for journal_mode=WAL,
   40296 ** journal_mode=MEMORY, or journal_mode=OFF.
   40297 **
   40298 ** Within this comment block, a page is deemed to have been synced
   40299 ** automatically as soon as it is written when PRAGMA synchronous=OFF.
   40300 ** Otherwise, the page is not synced until the xSync method of the VFS
   40301 ** is called successfully on the file containing the page.
   40302 **
   40303 ** Definition:  A page of the database file is said to be "overwriteable" if
   40304 ** one or more of the following are true about the page:
   40305 **
   40306 **     (a)  The original content of the page as it was at the beginning of
   40307 **          the transaction has been written into the rollback journal and
   40308 **          synced.
   40309 **
   40310 **     (b)  The page was a freelist leaf page at the start of the transaction.
   40311 **
   40312 **     (c)  The page number is greater than the largest page that existed in
   40313 **          the database file at the start of the transaction.
   40314 **
   40315 ** (1) A page of the database file is never overwritten unless one of the
   40316 **     following are true:
   40317 **
   40318 **     (a) The page and all other pages on the same sector are overwriteable.
   40319 **
   40320 **     (b) The atomic page write optimization is enabled, and the entire
   40321 **         transaction other than the update of the transaction sequence
   40322 **         number consists of a single page change.
   40323 **
   40324 ** (2) The content of a page written into the rollback journal exactly matches
   40325 **     both the content in the database when the rollback journal was written
   40326 **     and the content in the database at the beginning of the current
   40327 **     transaction.
   40328 **
   40329 ** (3) Writes to the database file are an integer multiple of the page size
   40330 **     in length and are aligned on a page boundary.
   40331 **
   40332 ** (4) Reads from the database file are either aligned on a page boundary and
   40333 **     an integer multiple of the page size in length or are taken from the
   40334 **     first 100 bytes of the database file.
   40335 **
   40336 ** (5) All writes to the database file are synced prior to the rollback journal
   40337 **     being deleted, truncated, or zeroed.
   40338 **
   40339 ** (6) If a master journal file is used, then all writes to the database file
   40340 **     are synced prior to the master journal being deleted.
   40341 **
   40342 ** Definition: Two databases (or the same database at two points it time)
   40343 ** are said to be "logically equivalent" if they give the same answer to
   40344 ** all queries.  Note in particular the content of freelist leaf
   40345 ** pages can be changed arbitarily without effecting the logical equivalence
   40346 ** of the database.
   40347 **
   40348 ** (7) At any time, if any subset, including the empty set and the total set,
   40349 **     of the unsynced changes to a rollback journal are removed and the
   40350 **     journal is rolled back, the resulting database file will be logical
   40351 **     equivalent to the database file at the beginning of the transaction.
   40352 **
   40353 ** (8) When a transaction is rolled back, the xTruncate method of the VFS
   40354 **     is called to restore the database file to the same size it was at
   40355 **     the beginning of the transaction.  (In some VFSes, the xTruncate
   40356 **     method is a no-op, but that does not change the fact the SQLite will
   40357 **     invoke it.)
   40358 **
   40359 ** (9) Whenever the database file is modified, at least one bit in the range
   40360 **     of bytes from 24 through 39 inclusive will be changed prior to releasing
   40361 **     the EXCLUSIVE lock, thus signaling other connections on the same
   40362 **     database to flush their caches.
   40363 **
   40364 ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
   40365 **      than one billion transactions.
   40366 **
   40367 ** (11) A database file is well-formed at the beginning and at the conclusion
   40368 **      of every transaction.
   40369 **
   40370 ** (12) An EXCLUSIVE lock is held on the database file when writing to
   40371 **      the database file.
   40372 **
   40373 ** (13) A SHARED lock is held on the database file while reading any
   40374 **      content out of the database file.
   40375 **
   40376 ******************************************************************************/
   40377 
   40378 /*
   40379 ** Macros for troubleshooting.  Normally turned off
   40380 */
   40381 #if 0
   40382 int sqlite3PagerTrace=1;  /* True to enable tracing */
   40383 #define sqlite3DebugPrintf printf
   40384 #define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
   40385 #else
   40386 #define PAGERTRACE(X)
   40387 #endif
   40388 
   40389 /*
   40390 ** The following two macros are used within the PAGERTRACE() macros above
   40391 ** to print out file-descriptors.
   40392 **
   40393 ** PAGERID() takes a pointer to a Pager struct as its argument. The
   40394 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
   40395 ** struct as its argument.
   40396 */
   40397 #define PAGERID(p) ((int)(p->fd))
   40398 #define FILEHANDLEID(fd) ((int)fd)
   40399 
   40400 /*
   40401 ** The Pager.eState variable stores the current 'state' of a pager. A
   40402 ** pager may be in any one of the seven states shown in the following
   40403 ** state diagram.
   40404 **
   40405 **                            OPEN <------+------+
   40406 **                              |         |      |
   40407 **                              V         |      |
   40408 **               +---------> READER-------+      |
   40409 **               |              |                |
   40410 **               |              V                |
   40411 **               |<-------WRITER_LOCKED------> ERROR
   40412 **               |              |                ^
   40413 **               |              V                |
   40414 **               |<------WRITER_CACHEMOD-------->|
   40415 **               |              |                |
   40416 **               |              V                |
   40417 **               |<-------WRITER_DBMOD---------->|
   40418 **               |              |                |
   40419 **               |              V                |
   40420 **               +<------WRITER_FINISHED-------->+
   40421 **
   40422 **
   40423 ** List of state transitions and the C [function] that performs each:
   40424 **
   40425 **   OPEN              -> READER              [sqlite3PagerSharedLock]
   40426 **   READER            -> OPEN                [pager_unlock]
   40427 **
   40428 **   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
   40429 **   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
   40430 **   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
   40431 **   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
   40432 **   WRITER_***        -> READER              [pager_end_transaction]
   40433 **
   40434 **   WRITER_***        -> ERROR               [pager_error]
   40435 **   ERROR             -> OPEN                [pager_unlock]
   40436 **
   40437 **
   40438 **  OPEN:
   40439 **
   40440 **    The pager starts up in this state. Nothing is guaranteed in this
   40441 **    state - the file may or may not be locked and the database size is
   40442 **    unknown. The database may not be read or written.
   40443 **
   40444 **    * No read or write transaction is active.
   40445 **    * Any lock, or no lock at all, may be held on the database file.
   40446 **    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
   40447 **
   40448 **  READER:
   40449 **
   40450 **    In this state all the requirements for reading the database in
   40451 **    rollback (non-WAL) mode are met. Unless the pager is (or recently
   40452 **    was) in exclusive-locking mode, a user-level read transaction is
   40453 **    open. The database size is known in this state.
   40454 **
   40455 **    A connection running with locking_mode=normal enters this state when
   40456 **    it opens a read-transaction on the database and returns to state
   40457 **    OPEN after the read-transaction is completed. However a connection
   40458 **    running in locking_mode=exclusive (including temp databases) remains in
   40459 **    this state even after the read-transaction is closed. The only way
   40460 **    a locking_mode=exclusive connection can transition from READER to OPEN
   40461 **    is via the ERROR state (see below).
   40462 **
   40463 **    * A read transaction may be active (but a write-transaction cannot).
   40464 **    * A SHARED or greater lock is held on the database file.
   40465 **    * The dbSize variable may be trusted (even if a user-level read
   40466 **      transaction is not active). The dbOrigSize and dbFileSize variables
   40467 **      may not be trusted at this point.
   40468 **    * If the database is a WAL database, then the WAL connection is open.
   40469 **    * Even if a read-transaction is not open, it is guaranteed that
   40470 **      there is no hot-journal in the file-system.
   40471 **
   40472 **  WRITER_LOCKED:
   40473 **
   40474 **    The pager moves to this state from READER when a write-transaction
   40475 **    is first opened on the database. In WRITER_LOCKED state, all locks
   40476 **    required to start a write-transaction are held, but no actual
   40477 **    modifications to the cache or database have taken place.
   40478 **
   40479 **    In rollback mode, a RESERVED or (if the transaction was opened with
   40480 **    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
   40481 **    moving to this state, but the journal file is not written to or opened
   40482 **    to in this state. If the transaction is committed or rolled back while
   40483 **    in WRITER_LOCKED state, all that is required is to unlock the database
   40484 **    file.
   40485 **
   40486 **    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
   40487 **    If the connection is running with locking_mode=exclusive, an attempt
   40488 **    is made to obtain an EXCLUSIVE lock on the database file.
   40489 **
   40490 **    * A write transaction is active.
   40491 **    * If the connection is open in rollback-mode, a RESERVED or greater
   40492 **      lock is held on the database file.
   40493 **    * If the connection is open in WAL-mode, a WAL write transaction
   40494 **      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
   40495 **      called).
   40496 **    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
   40497 **    * The contents of the pager cache have not been modified.
   40498 **    * The journal file may or may not be open.
   40499 **    * Nothing (not even the first header) has been written to the journal.
   40500 **
   40501 **  WRITER_CACHEMOD:
   40502 **
   40503 **    A pager moves from WRITER_LOCKED state to this state when a page is
   40504 **    first modified by the upper layer. In rollback mode the journal file
   40505 **    is opened (if it is not already open) and a header written to the
   40506 **    start of it. The database file on disk has not been modified.
   40507 **
   40508 **    * A write transaction is active.
   40509 **    * A RESERVED or greater lock is held on the database file.
   40510 **    * The journal file is open and the first header has been written
   40511 **      to it, but the header has not been synced to disk.
   40512 **    * The contents of the page cache have been modified.
   40513 **
   40514 **  WRITER_DBMOD:
   40515 **
   40516 **    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
   40517 **    when it modifies the contents of the database file. WAL connections
   40518 **    never enter this state (since they do not modify the database file,
   40519 **    just the log file).
   40520 **
   40521 **    * A write transaction is active.
   40522 **    * An EXCLUSIVE or greater lock is held on the database file.
   40523 **    * The journal file is open and the first header has been written
   40524 **      and synced to disk.
   40525 **    * The contents of the page cache have been modified (and possibly
   40526 **      written to disk).
   40527 **
   40528 **  WRITER_FINISHED:
   40529 **
   40530 **    It is not possible for a WAL connection to enter this state.
   40531 **
   40532 **    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
   40533 **    state after the entire transaction has been successfully written into the
   40534 **    database file. In this state the transaction may be committed simply
   40535 **    by finalizing the journal file. Once in WRITER_FINISHED state, it is
   40536 **    not possible to modify the database further. At this point, the upper
   40537 **    layer must either commit or rollback the transaction.
   40538 **
   40539 **    * A write transaction is active.
   40540 **    * An EXCLUSIVE or greater lock is held on the database file.
   40541 **    * All writing and syncing of journal and database data has finished.
   40542 **      If no error occurred, all that remains is to finalize the journal to
   40543 **      commit the transaction. If an error did occur, the caller will need
   40544 **      to rollback the transaction.
   40545 **
   40546 **  ERROR:
   40547 **
   40548 **    The ERROR state is entered when an IO or disk-full error (including
   40549 **    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
   40550 **    difficult to be sure that the in-memory pager state (cache contents,
   40551 **    db size etc.) are consistent with the contents of the file-system.
   40552 **
   40553 **    Temporary pager files may enter the ERROR state, but in-memory pagers
   40554 **    cannot.
   40555 **
   40556 **    For example, if an IO error occurs while performing a rollback,
   40557 **    the contents of the page-cache may be left in an inconsistent state.
   40558 **    At this point it would be dangerous to change back to READER state
   40559 **    (as usually happens after a rollback). Any subsequent readers might
   40560 **    report database corruption (due to the inconsistent cache), and if
   40561 **    they upgrade to writers, they may inadvertently corrupt the database
   40562 **    file. To avoid this hazard, the pager switches into the ERROR state
   40563 **    instead of READER following such an error.
   40564 **
   40565 **    Once it has entered the ERROR state, any attempt to use the pager
   40566 **    to read or write data returns an error. Eventually, once all
   40567 **    outstanding transactions have been abandoned, the pager is able to
   40568 **    transition back to OPEN state, discarding the contents of the
   40569 **    page-cache and any other in-memory state at the same time. Everything
   40570 **    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
   40571 **    when a read-transaction is next opened on the pager (transitioning
   40572 **    the pager into READER state). At that point the system has recovered
   40573 **    from the error.
   40574 **
   40575 **    Specifically, the pager jumps into the ERROR state if:
   40576 **
   40577 **      1. An error occurs while attempting a rollback. This happens in
   40578 **         function sqlite3PagerRollback().
   40579 **
   40580 **      2. An error occurs while attempting to finalize a journal file
   40581 **         following a commit in function sqlite3PagerCommitPhaseTwo().
   40582 **
   40583 **      3. An error occurs while attempting to write to the journal or
   40584 **         database file in function pagerStress() in order to free up
   40585 **         memory.
   40586 **
   40587 **    In other cases, the error is returned to the b-tree layer. The b-tree
   40588 **    layer then attempts a rollback operation. If the error condition
   40589 **    persists, the pager enters the ERROR state via condition (1) above.
   40590 **
   40591 **    Condition (3) is necessary because it can be triggered by a read-only
   40592 **    statement executed within a transaction. In this case, if the error
   40593 **    code were simply returned to the user, the b-tree layer would not
   40594 **    automatically attempt a rollback, as it assumes that an error in a
   40595 **    read-only statement cannot leave the pager in an internally inconsistent
   40596 **    state.
   40597 **
   40598 **    * The Pager.errCode variable is set to something other than SQLITE_OK.
   40599 **    * There are one or more outstanding references to pages (after the
   40600 **      last reference is dropped the pager should move back to OPEN state).
   40601 **    * The pager is not an in-memory pager.
   40602 **
   40603 **
   40604 ** Notes:
   40605 **
   40606 **   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
   40607 **     connection is open in WAL mode. A WAL connection is always in one
   40608 **     of the first four states.
   40609 **
   40610 **   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
   40611 **     state. There are two exceptions: immediately after exclusive-mode has
   40612 **     been turned on (and before any read or write transactions are
   40613 **     executed), and when the pager is leaving the "error state".
   40614 **
   40615 **   * See also: assert_pager_state().
   40616 */
   40617 #define PAGER_OPEN                  0
   40618 #define PAGER_READER                1
   40619 #define PAGER_WRITER_LOCKED         2
   40620 #define PAGER_WRITER_CACHEMOD       3
   40621 #define PAGER_WRITER_DBMOD          4
   40622 #define PAGER_WRITER_FINISHED       5
   40623 #define PAGER_ERROR                 6
   40624 
   40625 /*
   40626 ** The Pager.eLock variable is almost always set to one of the
   40627 ** following locking-states, according to the lock currently held on
   40628 ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
   40629 ** This variable is kept up to date as locks are taken and released by
   40630 ** the pagerLockDb() and pagerUnlockDb() wrappers.
   40631 **
   40632 ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
   40633 ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
   40634 ** the operation was successful. In these circumstances pagerLockDb() and
   40635 ** pagerUnlockDb() take a conservative approach - eLock is always updated
   40636 ** when unlocking the file, and only updated when locking the file if the
   40637 ** VFS call is successful. This way, the Pager.eLock variable may be set
   40638 ** to a less exclusive (lower) value than the lock that is actually held
   40639 ** at the system level, but it is never set to a more exclusive value.
   40640 **
   40641 ** This is usually safe. If an xUnlock fails or appears to fail, there may
   40642 ** be a few redundant xLock() calls or a lock may be held for longer than
   40643 ** required, but nothing really goes wrong.
   40644 **
   40645 ** The exception is when the database file is unlocked as the pager moves
   40646 ** from ERROR to OPEN state. At this point there may be a hot-journal file
   40647 ** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
   40648 ** transition, by the same pager or any other). If the call to xUnlock()
   40649 ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
   40650 ** can confuse the call to xCheckReservedLock() call made later as part
   40651 ** of hot-journal detection.
   40652 **
   40653 ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
   40654 ** lock held by this process or any others". So xCheckReservedLock may
   40655 ** return true because the caller itself is holding an EXCLUSIVE lock (but
   40656 ** doesn't know it because of a previous error in xUnlock). If this happens
   40657 ** a hot-journal may be mistaken for a journal being created by an active
   40658 ** transaction in another process, causing SQLite to read from the database
   40659 ** without rolling it back.
   40660 **
   40661 ** To work around this, if a call to xUnlock() fails when unlocking the
   40662 ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
   40663 ** is only changed back to a real locking state after a successful call
   40664 ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
   40665 ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
   40666 ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
   40667 ** lock on the database file before attempting to roll it back. See function
   40668 ** PagerSharedLock() for more detail.
   40669 **
   40670 ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
   40671 ** PAGER_OPEN state.
   40672 */
   40673 #define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
   40674 
   40675 /*
   40676 ** A macro used for invoking the codec if there is one
   40677 */
   40678 #ifdef SQLITE_HAS_CODEC
   40679 # define CODEC1(P,D,N,X,E) \
   40680     if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
   40681 # define CODEC2(P,D,N,X,E,O) \
   40682     if( P->xCodec==0 ){ O=(char*)D; }else \
   40683     if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
   40684 #else
   40685 # define CODEC1(P,D,N,X,E)   /* NO-OP */
   40686 # define CODEC2(P,D,N,X,E,O) O=(char*)D
   40687 #endif
   40688 
   40689 /*
   40690 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
   40691 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
   40692 ** This could conceivably cause corruption following a power failure on
   40693 ** such a system. This is currently an undocumented limit.
   40694 */
   40695 #define MAX_SECTOR_SIZE 0x10000
   40696 
   40697 /*
   40698 ** An instance of the following structure is allocated for each active
   40699 ** savepoint and statement transaction in the system. All such structures
   40700 ** are stored in the Pager.aSavepoint[] array, which is allocated and
   40701 ** resized using sqlite3Realloc().
   40702 **
   40703 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
   40704 ** set to 0. If a journal-header is written into the main journal while
   40705 ** the savepoint is active, then iHdrOffset is set to the byte offset
   40706 ** immediately following the last journal record written into the main
   40707 ** journal before the journal-header. This is required during savepoint
   40708 ** rollback (see pagerPlaybackSavepoint()).
   40709 */
   40710 typedef struct PagerSavepoint PagerSavepoint;
   40711 struct PagerSavepoint {
   40712   i64 iOffset;                 /* Starting offset in main journal */
   40713   i64 iHdrOffset;              /* See above */
   40714   Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
   40715   Pgno nOrig;                  /* Original number of pages in file */
   40716   Pgno iSubRec;                /* Index of first record in sub-journal */
   40717 #ifndef SQLITE_OMIT_WAL
   40718   u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
   40719 #endif
   40720 };
   40721 
   40722 /*
   40723 ** Bits of the Pager.doNotSpill flag.  See further description below.
   40724 */
   40725 #define SPILLFLAG_OFF         0x01      /* Never spill cache.  Set via pragma */
   40726 #define SPILLFLAG_ROLLBACK    0x02      /* Current rolling back, so do not spill */
   40727 #define SPILLFLAG_NOSYNC      0x04      /* Spill is ok, but do not sync */
   40728 
   40729 /*
   40730 ** A open page cache is an instance of struct Pager. A description of
   40731 ** some of the more important member variables follows:
   40732 **
   40733 ** eState
   40734 **
   40735 **   The current 'state' of the pager object. See the comment and state
   40736 **   diagram above for a description of the pager state.
   40737 **
   40738 ** eLock
   40739 **
   40740 **   For a real on-disk database, the current lock held on the database file -
   40741 **   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
   40742 **
   40743 **   For a temporary or in-memory database (neither of which require any
   40744 **   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
   40745 **   databases always have Pager.exclusiveMode==1, this tricks the pager
   40746 **   logic into thinking that it already has all the locks it will ever
   40747 **   need (and no reason to release them).
   40748 **
   40749 **   In some (obscure) circumstances, this variable may also be set to
   40750 **   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
   40751 **   details.
   40752 **
   40753 ** changeCountDone
   40754 **
   40755 **   This boolean variable is used to make sure that the change-counter
   40756 **   (the 4-byte header field at byte offset 24 of the database file) is
   40757 **   not updated more often than necessary.
   40758 **
   40759 **   It is set to true when the change-counter field is updated, which
   40760 **   can only happen if an exclusive lock is held on the database file.
   40761 **   It is cleared (set to false) whenever an exclusive lock is
   40762 **   relinquished on the database file. Each time a transaction is committed,
   40763 **   The changeCountDone flag is inspected. If it is true, the work of
   40764 **   updating the change-counter is omitted for the current transaction.
   40765 **
   40766 **   This mechanism means that when running in exclusive mode, a connection
   40767 **   need only update the change-counter once, for the first transaction
   40768 **   committed.
   40769 **
   40770 ** setMaster
   40771 **
   40772 **   When PagerCommitPhaseOne() is called to commit a transaction, it may
   40773 **   (or may not) specify a master-journal name to be written into the
   40774 **   journal file before it is synced to disk.
   40775 **
   40776 **   Whether or not a journal file contains a master-journal pointer affects
   40777 **   the way in which the journal file is finalized after the transaction is
   40778 **   committed or rolled back when running in "journal_mode=PERSIST" mode.
   40779 **   If a journal file does not contain a master-journal pointer, it is
   40780 **   finalized by overwriting the first journal header with zeroes. If
   40781 **   it does contain a master-journal pointer the journal file is finalized
   40782 **   by truncating it to zero bytes, just as if the connection were
   40783 **   running in "journal_mode=truncate" mode.
   40784 **
   40785 **   Journal files that contain master journal pointers cannot be finalized
   40786 **   simply by overwriting the first journal-header with zeroes, as the
   40787 **   master journal pointer could interfere with hot-journal rollback of any
   40788 **   subsequently interrupted transaction that reuses the journal file.
   40789 **
   40790 **   The flag is cleared as soon as the journal file is finalized (either
   40791 **   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
   40792 **   journal file from being successfully finalized, the setMaster flag
   40793 **   is cleared anyway (and the pager will move to ERROR state).
   40794 **
   40795 ** doNotSpill
   40796 **
   40797 **   This variables control the behavior of cache-spills  (calls made by
   40798 **   the pcache module to the pagerStress() routine to write cached data
   40799 **   to the file-system in order to free up memory).
   40800 **
   40801 **   When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
   40802 **   writing to the database from pagerStress() is disabled altogether.
   40803 **   The SPILLFLAG_ROLLBACK case is done in a very obscure case that
   40804 **   comes up during savepoint rollback that requires the pcache module
   40805 **   to allocate a new page to prevent the journal file from being written
   40806 **   while it is being traversed by code in pager_playback().  The SPILLFLAG_OFF
   40807 **   case is a user preference.
   40808 **
   40809 **   If the SPILLFLAG_NOSYNC bit is set, writing to the database from pagerStress()
   40810 **   is permitted, but syncing the journal file is not. This flag is set
   40811 **   by sqlite3PagerWrite() when the file-system sector-size is larger than
   40812 **   the database page-size in order to prevent a journal sync from happening
   40813 **   in between the journalling of two pages on the same sector.
   40814 **
   40815 ** subjInMemory
   40816 **
   40817 **   This is a boolean variable. If true, then any required sub-journal
   40818 **   is opened as an in-memory journal file. If false, then in-memory
   40819 **   sub-journals are only used for in-memory pager files.
   40820 **
   40821 **   This variable is updated by the upper layer each time a new
   40822 **   write-transaction is opened.
   40823 **
   40824 ** dbSize, dbOrigSize, dbFileSize
   40825 **
   40826 **   Variable dbSize is set to the number of pages in the database file.
   40827 **   It is valid in PAGER_READER and higher states (all states except for
   40828 **   OPEN and ERROR).
   40829 **
   40830 **   dbSize is set based on the size of the database file, which may be
   40831 **   larger than the size of the database (the value stored at offset
   40832 **   28 of the database header by the btree). If the size of the file
   40833 **   is not an integer multiple of the page-size, the value stored in
   40834 **   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
   40835 **   Except, any file that is greater than 0 bytes in size is considered
   40836 **   to have at least one page. (i.e. a 1KB file with 2K page-size leads
   40837 **   to dbSize==1).
   40838 **
   40839 **   During a write-transaction, if pages with page-numbers greater than
   40840 **   dbSize are modified in the cache, dbSize is updated accordingly.
   40841 **   Similarly, if the database is truncated using PagerTruncateImage(),
   40842 **   dbSize is updated.
   40843 **
   40844 **   Variables dbOrigSize and dbFileSize are valid in states
   40845 **   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
   40846 **   variable at the start of the transaction. It is used during rollback,
   40847 **   and to determine whether or not pages need to be journalled before
   40848 **   being modified.
   40849 **
   40850 **   Throughout a write-transaction, dbFileSize contains the size of
   40851 **   the file on disk in pages. It is set to a copy of dbSize when the
   40852 **   write-transaction is first opened, and updated when VFS calls are made
   40853 **   to write or truncate the database file on disk.
   40854 **
   40855 **   The only reason the dbFileSize variable is required is to suppress
   40856 **   unnecessary calls to xTruncate() after committing a transaction. If,
   40857 **   when a transaction is committed, the dbFileSize variable indicates
   40858 **   that the database file is larger than the database image (Pager.dbSize),
   40859 **   pager_truncate() is called. The pager_truncate() call uses xFilesize()
   40860 **   to measure the database file on disk, and then truncates it if required.
   40861 **   dbFileSize is not used when rolling back a transaction. In this case
   40862 **   pager_truncate() is called unconditionally (which means there may be
   40863 **   a call to xFilesize() that is not strictly required). In either case,
   40864 **   pager_truncate() may cause the file to become smaller or larger.
   40865 **
   40866 ** dbHintSize
   40867 **
   40868 **   The dbHintSize variable is used to limit the number of calls made to
   40869 **   the VFS xFileControl(FCNTL_SIZE_HINT) method.
   40870 **
   40871 **   dbHintSize is set to a copy of the dbSize variable when a
   40872 **   write-transaction is opened (at the same time as dbFileSize and
   40873 **   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
   40874 **   dbHintSize is increased to the number of pages that correspond to the
   40875 **   size-hint passed to the method call. See pager_write_pagelist() for
   40876 **   details.
   40877 **
   40878 ** errCode
   40879 **
   40880 **   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
   40881 **   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
   40882 **   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
   40883 **   sub-codes.
   40884 */
   40885 struct Pager {
   40886   sqlite3_vfs *pVfs;          /* OS functions to use for IO */
   40887   u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
   40888   u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
   40889   u8 useJournal;              /* Use a rollback journal on this file */
   40890   u8 noSync;                  /* Do not sync the journal if true */
   40891   u8 fullSync;                /* Do extra syncs of the journal for robustness */
   40892   u8 ckptSyncFlags;           /* SYNC_NORMAL or SYNC_FULL for checkpoint */
   40893   u8 walSyncFlags;            /* SYNC_NORMAL or SYNC_FULL for wal writes */
   40894   u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */
   40895   u8 tempFile;                /* zFilename is a temporary or immutable file */
   40896   u8 noLock;                  /* Do not lock (except in WAL mode) */
   40897   u8 readOnly;                /* True for a read-only database */
   40898   u8 memDb;                   /* True to inhibit all file I/O */
   40899 
   40900   /**************************************************************************
   40901   ** The following block contains those class members that change during
   40902   ** routine opertion.  Class members not in this block are either fixed
   40903   ** when the pager is first created or else only change when there is a
   40904   ** significant mode change (such as changing the page_size, locking_mode,
   40905   ** or the journal_mode).  From another view, these class members describe
   40906   ** the "state" of the pager, while other class members describe the
   40907   ** "configuration" of the pager.
   40908   */
   40909   u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
   40910   u8 eLock;                   /* Current lock held on database file */
   40911   u8 changeCountDone;         /* Set after incrementing the change-counter */
   40912   u8 setMaster;               /* True if a m-j name has been written to jrnl */
   40913   u8 doNotSpill;              /* Do not spill the cache when non-zero */
   40914   u8 subjInMemory;            /* True to use in-memory sub-journals */
   40915   Pgno dbSize;                /* Number of pages in the database */
   40916   Pgno dbOrigSize;            /* dbSize before the current transaction */
   40917   Pgno dbFileSize;            /* Number of pages in the database file */
   40918   Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
   40919   int errCode;                /* One of several kinds of errors */
   40920   int nRec;                   /* Pages journalled since last j-header written */
   40921   u32 cksumInit;              /* Quasi-random value added to every checksum */
   40922   u32 nSubRec;                /* Number of records written to sub-journal */
   40923   Bitvec *pInJournal;         /* One bit for each page in the database file */
   40924   sqlite3_file *fd;           /* File descriptor for database */
   40925   sqlite3_file *jfd;          /* File descriptor for main journal */
   40926   sqlite3_file *sjfd;         /* File descriptor for sub-journal */
   40927   i64 journalOff;             /* Current write offset in the journal file */
   40928   i64 journalHdr;             /* Byte offset to previous journal header */
   40929   sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
   40930   PagerSavepoint *aSavepoint; /* Array of active savepoints */
   40931   int nSavepoint;             /* Number of elements in aSavepoint[] */
   40932   char dbFileVers[16];        /* Changes whenever database file changes */
   40933 
   40934   u8 bUseFetch;               /* True to use xFetch() */
   40935   int nMmapOut;               /* Number of mmap pages currently outstanding */
   40936   sqlite3_int64 szMmap;       /* Desired maximum mmap size */
   40937   PgHdr *pMmapFreelist;       /* List of free mmap page headers (pDirty) */
   40938   /*
   40939   ** End of the routinely-changing class members
   40940   ***************************************************************************/
   40941 
   40942   u16 nExtra;                 /* Add this many bytes to each in-memory page */
   40943   i16 nReserve;               /* Number of unused bytes at end of each page */
   40944   u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
   40945   u32 sectorSize;             /* Assumed sector size during rollback */
   40946   int pageSize;               /* Number of bytes in a page */
   40947   Pgno mxPgno;                /* Maximum allowed size of the database */
   40948   i64 journalSizeLimit;       /* Size limit for persistent journal files */
   40949   char *zFilename;            /* Name of the database file */
   40950   char *zJournal;             /* Name of the journal file */
   40951   int (*xBusyHandler)(void*); /* Function to call when busy */
   40952   void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
   40953   int aStat[3];               /* Total cache hits, misses and writes */
   40954 #ifdef SQLITE_TEST
   40955   int nRead;                  /* Database pages read */
   40956 #endif
   40957   void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
   40958 #ifdef SQLITE_HAS_CODEC
   40959   void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
   40960   void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
   40961   void (*xCodecFree)(void*);             /* Destructor for the codec */
   40962   void *pCodec;               /* First argument to xCodec... methods */
   40963 #endif
   40964   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
   40965   PCache *pPCache;            /* Pointer to page cache object */
   40966 #ifndef SQLITE_OMIT_WAL
   40967   Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
   40968   char *zWal;                 /* File name for write-ahead log */
   40969 #endif
   40970 };
   40971 
   40972 /*
   40973 ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
   40974 ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
   40975 ** or CACHE_WRITE to sqlite3_db_status().
   40976 */
   40977 #define PAGER_STAT_HIT   0
   40978 #define PAGER_STAT_MISS  1
   40979 #define PAGER_STAT_WRITE 2
   40980 
   40981 /*
   40982 ** The following global variables hold counters used for
   40983 ** testing purposes only.  These variables do not exist in
   40984 ** a non-testing build.  These variables are not thread-safe.
   40985 */
   40986 #ifdef SQLITE_TEST
   40987 SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
   40988 SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
   40989 SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
   40990 # define PAGER_INCR(v)  v++
   40991 #else
   40992 # define PAGER_INCR(v)
   40993 #endif
   40994 
   40995 
   40996 
   40997 /*
   40998 ** Journal files begin with the following magic string.  The data
   40999 ** was obtained from /dev/random.  It is used only as a sanity check.
   41000 **
   41001 ** Since version 2.8.0, the journal format contains additional sanity
   41002 ** checking information.  If the power fails while the journal is being
   41003 ** written, semi-random garbage data might appear in the journal
   41004 ** file after power is restored.  If an attempt is then made
   41005 ** to roll the journal back, the database could be corrupted.  The additional
   41006 ** sanity checking data is an attempt to discover the garbage in the
   41007 ** journal and ignore it.
   41008 **
   41009 ** The sanity checking information for the new journal format consists
   41010 ** of a 32-bit checksum on each page of data.  The checksum covers both
   41011 ** the page number and the pPager->pageSize bytes of data for the page.
   41012 ** This cksum is initialized to a 32-bit random value that appears in the
   41013 ** journal file right after the header.  The random initializer is important,
   41014 ** because garbage data that appears at the end of a journal is likely
   41015 ** data that was once in other files that have now been deleted.  If the
   41016 ** garbage data came from an obsolete journal file, the checksums might
   41017 ** be correct.  But by initializing the checksum to random value which
   41018 ** is different for every journal, we minimize that risk.
   41019 */
   41020 static const unsigned char aJournalMagic[] = {
   41021   0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
   41022 };
   41023 
   41024 /*
   41025 ** The size of the of each page record in the journal is given by
   41026 ** the following macro.
   41027 */
   41028 #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
   41029 
   41030 /*
   41031 ** The journal header size for this pager. This is usually the same
   41032 ** size as a single disk sector. See also setSectorSize().
   41033 */
   41034 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
   41035 
   41036 /*
   41037 ** The macro MEMDB is true if we are dealing with an in-memory database.
   41038 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
   41039 ** the value of MEMDB will be a constant and the compiler will optimize
   41040 ** out code that would never execute.
   41041 */
   41042 #ifdef SQLITE_OMIT_MEMORYDB
   41043 # define MEMDB 0
   41044 #else
   41045 # define MEMDB pPager->memDb
   41046 #endif
   41047 
   41048 /*
   41049 ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
   41050 ** interfaces to access the database using memory-mapped I/O.
   41051 */
   41052 #if SQLITE_MAX_MMAP_SIZE>0
   41053 # define USEFETCH(x) ((x)->bUseFetch)
   41054 #else
   41055 # define USEFETCH(x) 0
   41056 #endif
   41057 
   41058 /*
   41059 ** The maximum legal page number is (2^31 - 1).
   41060 */
   41061 #define PAGER_MAX_PGNO 2147483647
   41062 
   41063 /*
   41064 ** The argument to this macro is a file descriptor (type sqlite3_file*).
   41065 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
   41066 **
   41067 ** This is so that expressions can be written as:
   41068 **
   41069 **   if( isOpen(pPager->jfd) ){ ...
   41070 **
   41071 ** instead of
   41072 **
   41073 **   if( pPager->jfd->pMethods ){ ...
   41074 */
   41075 #define isOpen(pFd) ((pFd)->pMethods)
   41076 
   41077 /*
   41078 ** Return true if this pager uses a write-ahead log instead of the usual
   41079 ** rollback journal. Otherwise false.
   41080 */
   41081 #ifndef SQLITE_OMIT_WAL
   41082 static int pagerUseWal(Pager *pPager){
   41083   return (pPager->pWal!=0);
   41084 }
   41085 #else
   41086 # define pagerUseWal(x) 0
   41087 # define pagerRollbackWal(x) 0
   41088 # define pagerWalFrames(v,w,x,y) 0
   41089 # define pagerOpenWalIfPresent(z) SQLITE_OK
   41090 # define pagerBeginReadTransaction(z) SQLITE_OK
   41091 #endif
   41092 
   41093 #ifndef NDEBUG
   41094 /*
   41095 ** Usage:
   41096 **
   41097 **   assert( assert_pager_state(pPager) );
   41098 **
   41099 ** This function runs many asserts to try to find inconsistencies in
   41100 ** the internal state of the Pager object.
   41101 */
   41102 static int assert_pager_state(Pager *p){
   41103   Pager *pPager = p;
   41104 
   41105   /* State must be valid. */
   41106   assert( p->eState==PAGER_OPEN
   41107        || p->eState==PAGER_READER
   41108        || p->eState==PAGER_WRITER_LOCKED
   41109        || p->eState==PAGER_WRITER_CACHEMOD
   41110        || p->eState==PAGER_WRITER_DBMOD
   41111        || p->eState==PAGER_WRITER_FINISHED
   41112        || p->eState==PAGER_ERROR
   41113   );
   41114 
   41115   /* Regardless of the current state, a temp-file connection always behaves
   41116   ** as if it has an exclusive lock on the database file. It never updates
   41117   ** the change-counter field, so the changeCountDone flag is always set.
   41118   */
   41119   assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
   41120   assert( p->tempFile==0 || pPager->changeCountDone );
   41121 
   41122   /* If the useJournal flag is clear, the journal-mode must be "OFF".
   41123   ** And if the journal-mode is "OFF", the journal file must not be open.
   41124   */
   41125   assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
   41126   assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
   41127 
   41128   /* Check that MEMDB implies noSync. And an in-memory journal. Since
   41129   ** this means an in-memory pager performs no IO at all, it cannot encounter
   41130   ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
   41131   ** a journal file. (although the in-memory journal implementation may
   41132   ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
   41133   ** is therefore not possible for an in-memory pager to enter the ERROR
   41134   ** state.
   41135   */
   41136   if( MEMDB ){
   41137     assert( p->noSync );
   41138     assert( p->journalMode==PAGER_JOURNALMODE_OFF
   41139          || p->journalMode==PAGER_JOURNALMODE_MEMORY
   41140     );
   41141     assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
   41142     assert( pagerUseWal(p)==0 );
   41143   }
   41144 
   41145   /* If changeCountDone is set, a RESERVED lock or greater must be held
   41146   ** on the file.
   41147   */
   41148   assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
   41149   assert( p->eLock!=PENDING_LOCK );
   41150 
   41151   switch( p->eState ){
   41152     case PAGER_OPEN:
   41153       assert( !MEMDB );
   41154       assert( pPager->errCode==SQLITE_OK );
   41155       assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
   41156       break;
   41157 
   41158     case PAGER_READER:
   41159       assert( pPager->errCode==SQLITE_OK );
   41160       assert( p->eLock!=UNKNOWN_LOCK );
   41161       assert( p->eLock>=SHARED_LOCK );
   41162       break;
   41163 
   41164     case PAGER_WRITER_LOCKED:
   41165       assert( p->eLock!=UNKNOWN_LOCK );
   41166       assert( pPager->errCode==SQLITE_OK );
   41167       if( !pagerUseWal(pPager) ){
   41168         assert( p->eLock>=RESERVED_LOCK );
   41169       }
   41170       assert( pPager->dbSize==pPager->dbOrigSize );
   41171       assert( pPager->dbOrigSize==pPager->dbFileSize );
   41172       assert( pPager->dbOrigSize==pPager->dbHintSize );
   41173       assert( pPager->setMaster==0 );
   41174       break;
   41175 
   41176     case PAGER_WRITER_CACHEMOD:
   41177       assert( p->eLock!=UNKNOWN_LOCK );
   41178       assert( pPager->errCode==SQLITE_OK );
   41179       if( !pagerUseWal(pPager) ){
   41180         /* It is possible that if journal_mode=wal here that neither the
   41181         ** journal file nor the WAL file are open. This happens during
   41182         ** a rollback transaction that switches from journal_mode=off
   41183         ** to journal_mode=wal.
   41184         */
   41185         assert( p->eLock>=RESERVED_LOCK );
   41186         assert( isOpen(p->jfd)
   41187              || p->journalMode==PAGER_JOURNALMODE_OFF
   41188              || p->journalMode==PAGER_JOURNALMODE_WAL
   41189         );
   41190       }
   41191       assert( pPager->dbOrigSize==pPager->dbFileSize );
   41192       assert( pPager->dbOrigSize==pPager->dbHintSize );
   41193       break;
   41194 
   41195     case PAGER_WRITER_DBMOD:
   41196       assert( p->eLock==EXCLUSIVE_LOCK );
   41197       assert( pPager->errCode==SQLITE_OK );
   41198       assert( !pagerUseWal(pPager) );
   41199       assert( p->eLock>=EXCLUSIVE_LOCK );
   41200       assert( isOpen(p->jfd)
   41201            || p->journalMode==PAGER_JOURNALMODE_OFF
   41202            || p->journalMode==PAGER_JOURNALMODE_WAL
   41203       );
   41204       assert( pPager->dbOrigSize<=pPager->dbHintSize );
   41205       break;
   41206 
   41207     case PAGER_WRITER_FINISHED:
   41208       assert( p->eLock==EXCLUSIVE_LOCK );
   41209       assert( pPager->errCode==SQLITE_OK );
   41210       assert( !pagerUseWal(pPager) );
   41211       assert( isOpen(p->jfd)
   41212            || p->journalMode==PAGER_JOURNALMODE_OFF
   41213            || p->journalMode==PAGER_JOURNALMODE_WAL
   41214       );
   41215       break;
   41216 
   41217     case PAGER_ERROR:
   41218       /* There must be at least one outstanding reference to the pager if
   41219       ** in ERROR state. Otherwise the pager should have already dropped
   41220       ** back to OPEN state.
   41221       */
   41222       assert( pPager->errCode!=SQLITE_OK );
   41223       assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
   41224       break;
   41225   }
   41226 
   41227   return 1;
   41228 }
   41229 #endif /* ifndef NDEBUG */
   41230 
   41231 #ifdef SQLITE_DEBUG
   41232 /*
   41233 ** Return a pointer to a human readable string in a static buffer
   41234 ** containing the state of the Pager object passed as an argument. This
   41235 ** is intended to be used within debuggers. For example, as an alternative
   41236 ** to "print *pPager" in gdb:
   41237 **
   41238 ** (gdb) printf "%s", print_pager_state(pPager)
   41239 */
   41240 static char *print_pager_state(Pager *p){
   41241   static char zRet[1024];
   41242 
   41243   sqlite3_snprintf(1024, zRet,
   41244       "Filename:      %s\n"
   41245       "State:         %s errCode=%d\n"
   41246       "Lock:          %s\n"
   41247       "Locking mode:  locking_mode=%s\n"
   41248       "Journal mode:  journal_mode=%s\n"
   41249       "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
   41250       "Journal:       journalOff=%lld journalHdr=%lld\n"
   41251       "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
   41252       , p->zFilename
   41253       , p->eState==PAGER_OPEN            ? "OPEN" :
   41254         p->eState==PAGER_READER          ? "READER" :
   41255         p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
   41256         p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
   41257         p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
   41258         p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
   41259         p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
   41260       , (int)p->errCode
   41261       , p->eLock==NO_LOCK         ? "NO_LOCK" :
   41262         p->eLock==RESERVED_LOCK   ? "RESERVED" :
   41263         p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
   41264         p->eLock==SHARED_LOCK     ? "SHARED" :
   41265         p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
   41266       , p->exclusiveMode ? "exclusive" : "normal"
   41267       , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
   41268         p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
   41269         p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
   41270         p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
   41271         p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
   41272         p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
   41273       , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
   41274       , p->journalOff, p->journalHdr
   41275       , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
   41276   );
   41277 
   41278   return zRet;
   41279 }
   41280 #endif
   41281 
   41282 /*
   41283 ** Return true if it is necessary to write page *pPg into the sub-journal.
   41284 ** A page needs to be written into the sub-journal if there exists one
   41285 ** or more open savepoints for which:
   41286 **
   41287 **   * The page-number is less than or equal to PagerSavepoint.nOrig, and
   41288 **   * The bit corresponding to the page-number is not set in
   41289 **     PagerSavepoint.pInSavepoint.
   41290 */
   41291 static int subjRequiresPage(PgHdr *pPg){
   41292   Pager *pPager = pPg->pPager;
   41293   PagerSavepoint *p;
   41294   Pgno pgno = pPg->pgno;
   41295   int i;
   41296   for(i=0; i<pPager->nSavepoint; i++){
   41297     p = &pPager->aSavepoint[i];
   41298     if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
   41299       return 1;
   41300     }
   41301   }
   41302   return 0;
   41303 }
   41304 
   41305 /*
   41306 ** Return true if the page is already in the journal file.
   41307 */
   41308 static int pageInJournal(Pager *pPager, PgHdr *pPg){
   41309   return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
   41310 }
   41311 
   41312 /*
   41313 ** Read a 32-bit integer from the given file descriptor.  Store the integer
   41314 ** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
   41315 ** error code is something goes wrong.
   41316 **
   41317 ** All values are stored on disk as big-endian.
   41318 */
   41319 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
   41320   unsigned char ac[4];
   41321   int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
   41322   if( rc==SQLITE_OK ){
   41323     *pRes = sqlite3Get4byte(ac);
   41324   }
   41325   return rc;
   41326 }
   41327 
   41328 /*
   41329 ** Write a 32-bit integer into a string buffer in big-endian byte order.
   41330 */
   41331 #define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
   41332 
   41333 
   41334 /*
   41335 ** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
   41336 ** on success or an error code is something goes wrong.
   41337 */
   41338 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
   41339   char ac[4];
   41340   put32bits(ac, val);
   41341   return sqlite3OsWrite(fd, ac, 4, offset);
   41342 }
   41343 
   41344 /*
   41345 ** Unlock the database file to level eLock, which must be either NO_LOCK
   41346 ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
   41347 ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
   41348 **
   41349 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
   41350 ** called, do not modify it. See the comment above the #define of
   41351 ** UNKNOWN_LOCK for an explanation of this.
   41352 */
   41353 static int pagerUnlockDb(Pager *pPager, int eLock){
   41354   int rc = SQLITE_OK;
   41355 
   41356   assert( !pPager->exclusiveMode || pPager->eLock==eLock );
   41357   assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
   41358   assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
   41359   if( isOpen(pPager->fd) ){
   41360     assert( pPager->eLock>=eLock );
   41361     rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);
   41362     if( pPager->eLock!=UNKNOWN_LOCK ){
   41363       pPager->eLock = (u8)eLock;
   41364     }
   41365     IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
   41366   }
   41367   return rc;
   41368 }
   41369 
   41370 /*
   41371 ** Lock the database file to level eLock, which must be either SHARED_LOCK,
   41372 ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
   41373 ** Pager.eLock variable to the new locking state.
   41374 **
   41375 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
   41376 ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
   41377 ** See the comment above the #define of UNKNOWN_LOCK for an explanation
   41378 ** of this.
   41379 */
   41380 static int pagerLockDb(Pager *pPager, int eLock){
   41381   int rc = SQLITE_OK;
   41382 
   41383   assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
   41384   if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
   41385     rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);
   41386     if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
   41387       pPager->eLock = (u8)eLock;
   41388       IOTRACE(("LOCK %p %d\n", pPager, eLock))
   41389     }
   41390   }
   41391   return rc;
   41392 }
   41393 
   41394 /*
   41395 ** This function determines whether or not the atomic-write optimization
   41396 ** can be used with this pager. The optimization can be used if:
   41397 **
   41398 **  (a) the value returned by OsDeviceCharacteristics() indicates that
   41399 **      a database page may be written atomically, and
   41400 **  (b) the value returned by OsSectorSize() is less than or equal
   41401 **      to the page size.
   41402 **
   41403 ** The optimization is also always enabled for temporary files. It is
   41404 ** an error to call this function if pPager is opened on an in-memory
   41405 ** database.
   41406 **
   41407 ** If the optimization cannot be used, 0 is returned. If it can be used,
   41408 ** then the value returned is the size of the journal file when it
   41409 ** contains rollback data for exactly one page.
   41410 */
   41411 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
   41412 static int jrnlBufferSize(Pager *pPager){
   41413   assert( !MEMDB );
   41414   if( !pPager->tempFile ){
   41415     int dc;                           /* Device characteristics */
   41416     int nSector;                      /* Sector size */
   41417     int szPage;                       /* Page size */
   41418 
   41419     assert( isOpen(pPager->fd) );
   41420     dc = sqlite3OsDeviceCharacteristics(pPager->fd);
   41421     nSector = pPager->sectorSize;
   41422     szPage = pPager->pageSize;
   41423 
   41424     assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
   41425     assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
   41426     if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
   41427       return 0;
   41428     }
   41429   }
   41430 
   41431   return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
   41432 }
   41433 #endif
   41434 
   41435 /*
   41436 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
   41437 ** on the cache using a hash function.  This is used for testing
   41438 ** and debugging only.
   41439 */
   41440 #ifdef SQLITE_CHECK_PAGES
   41441 /*
   41442 ** Return a 32-bit hash of the page data for pPage.
   41443 */
   41444 static u32 pager_datahash(int nByte, unsigned char *pData){
   41445   u32 hash = 0;
   41446   int i;
   41447   for(i=0; i<nByte; i++){
   41448     hash = (hash*1039) + pData[i];
   41449   }
   41450   return hash;
   41451 }
   41452 static u32 pager_pagehash(PgHdr *pPage){
   41453   return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
   41454 }
   41455 static void pager_set_pagehash(PgHdr *pPage){
   41456   pPage->pageHash = pager_pagehash(pPage);
   41457 }
   41458 
   41459 /*
   41460 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
   41461 ** is defined, and NDEBUG is not defined, an assert() statement checks
   41462 ** that the page is either dirty or still matches the calculated page-hash.
   41463 */
   41464 #define CHECK_PAGE(x) checkPage(x)
   41465 static void checkPage(PgHdr *pPg){
   41466   Pager *pPager = pPg->pPager;
   41467   assert( pPager->eState!=PAGER_ERROR );
   41468   assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
   41469 }
   41470 
   41471 #else
   41472 #define pager_datahash(X,Y)  0
   41473 #define pager_pagehash(X)  0
   41474 #define pager_set_pagehash(X)
   41475 #define CHECK_PAGE(x)
   41476 #endif  /* SQLITE_CHECK_PAGES */
   41477 
   41478 /*
   41479 ** When this is called the journal file for pager pPager must be open.
   41480 ** This function attempts to read a master journal file name from the
   41481 ** end of the file and, if successful, copies it into memory supplied
   41482 ** by the caller. See comments above writeMasterJournal() for the format
   41483 ** used to store a master journal file name at the end of a journal file.
   41484 **
   41485 ** zMaster must point to a buffer of at least nMaster bytes allocated by
   41486 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
   41487 ** enough space to write the master journal name). If the master journal
   41488 ** name in the journal is longer than nMaster bytes (including a
   41489 ** nul-terminator), then this is handled as if no master journal name
   41490 ** were present in the journal.
   41491 **
   41492 ** If a master journal file name is present at the end of the journal
   41493 ** file, then it is copied into the buffer pointed to by zMaster. A
   41494 ** nul-terminator byte is appended to the buffer following the master
   41495 ** journal file name.
   41496 **
   41497 ** If it is determined that no master journal file name is present
   41498 ** zMaster[0] is set to 0 and SQLITE_OK returned.
   41499 **
   41500 ** If an error occurs while reading from the journal file, an SQLite
   41501 ** error code is returned.
   41502 */
   41503 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
   41504   int rc;                    /* Return code */
   41505   u32 len;                   /* Length in bytes of master journal name */
   41506   i64 szJ;                   /* Total size in bytes of journal file pJrnl */
   41507   u32 cksum;                 /* MJ checksum value read from journal */
   41508   u32 u;                     /* Unsigned loop counter */
   41509   unsigned char aMagic[8];   /* A buffer to hold the magic header */
   41510   zMaster[0] = '\0';
   41511 
   41512   if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
   41513    || szJ<16
   41514    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
   41515    || len>=nMaster
   41516    || len==0
   41517    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
   41518    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
   41519    || memcmp(aMagic, aJournalMagic, 8)
   41520    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
   41521   ){
   41522     return rc;
   41523   }
   41524 
   41525   /* See if the checksum matches the master journal name */
   41526   for(u=0; u<len; u++){
   41527     cksum -= zMaster[u];
   41528   }
   41529   if( cksum ){
   41530     /* If the checksum doesn't add up, then one or more of the disk sectors
   41531     ** containing the master journal filename is corrupted. This means
   41532     ** definitely roll back, so just return SQLITE_OK and report a (nul)
   41533     ** master-journal filename.
   41534     */
   41535     len = 0;
   41536   }
   41537   zMaster[len] = '\0';
   41538 
   41539   return SQLITE_OK;
   41540 }
   41541 
   41542 /*
   41543 ** Return the offset of the sector boundary at or immediately
   41544 ** following the value in pPager->journalOff, assuming a sector
   41545 ** size of pPager->sectorSize bytes.
   41546 **
   41547 ** i.e for a sector size of 512:
   41548 **
   41549 **   Pager.journalOff          Return value
   41550 **   ---------------------------------------
   41551 **   0                         0
   41552 **   512                       512
   41553 **   100                       512
   41554 **   2000                      2048
   41555 **
   41556 */
   41557 static i64 journalHdrOffset(Pager *pPager){
   41558   i64 offset = 0;
   41559   i64 c = pPager->journalOff;
   41560   if( c ){
   41561     offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
   41562   }
   41563   assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
   41564   assert( offset>=c );
   41565   assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
   41566   return offset;
   41567 }
   41568 
   41569 /*
   41570 ** The journal file must be open when this function is called.
   41571 **
   41572 ** This function is a no-op if the journal file has not been written to
   41573 ** within the current transaction (i.e. if Pager.journalOff==0).
   41574 **
   41575 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
   41576 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
   41577 ** zero the 28-byte header at the start of the journal file. In either case,
   41578 ** if the pager is not in no-sync mode, sync the journal file immediately
   41579 ** after writing or truncating it.
   41580 **
   41581 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
   41582 ** following the truncation or zeroing described above the size of the
   41583 ** journal file in bytes is larger than this value, then truncate the
   41584 ** journal file to Pager.journalSizeLimit bytes. The journal file does
   41585 ** not need to be synced following this operation.
   41586 **
   41587 ** If an IO error occurs, abandon processing and return the IO error code.
   41588 ** Otherwise, return SQLITE_OK.
   41589 */
   41590 static int zeroJournalHdr(Pager *pPager, int doTruncate){
   41591   int rc = SQLITE_OK;                               /* Return code */
   41592   assert( isOpen(pPager->jfd) );
   41593   if( pPager->journalOff ){
   41594     const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
   41595 
   41596     IOTRACE(("JZEROHDR %p\n", pPager))
   41597     if( doTruncate || iLimit==0 ){
   41598       rc = sqlite3OsTruncate(pPager->jfd, 0);
   41599     }else{
   41600       static const char zeroHdr[28] = {0};
   41601       rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
   41602     }
   41603     if( rc==SQLITE_OK && !pPager->noSync ){
   41604       rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
   41605     }
   41606 
   41607     /* At this point the transaction is committed but the write lock
   41608     ** is still held on the file. If there is a size limit configured for
   41609     ** the persistent journal and the journal file currently consumes more
   41610     ** space than that limit allows for, truncate it now. There is no need
   41611     ** to sync the file following this operation.
   41612     */
   41613     if( rc==SQLITE_OK && iLimit>0 ){
   41614       i64 sz;
   41615       rc = sqlite3OsFileSize(pPager->jfd, &sz);
   41616       if( rc==SQLITE_OK && sz>iLimit ){
   41617         rc = sqlite3OsTruncate(pPager->jfd, iLimit);
   41618       }
   41619     }
   41620   }
   41621   return rc;
   41622 }
   41623 
   41624 /*
   41625 ** The journal file must be open when this routine is called. A journal
   41626 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
   41627 ** current location.
   41628 **
   41629 ** The format for the journal header is as follows:
   41630 ** - 8 bytes: Magic identifying journal format.
   41631 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
   41632 ** - 4 bytes: Random number used for page hash.
   41633 ** - 4 bytes: Initial database page count.
   41634 ** - 4 bytes: Sector size used by the process that wrote this journal.
   41635 ** - 4 bytes: Database page size.
   41636 **
   41637 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
   41638 */
   41639 static int writeJournalHdr(Pager *pPager){
   41640   int rc = SQLITE_OK;                 /* Return code */
   41641   char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
   41642   u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
   41643   u32 nWrite;                         /* Bytes of header sector written */
   41644   int ii;                             /* Loop counter */
   41645 
   41646   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
   41647 
   41648   if( nHeader>JOURNAL_HDR_SZ(pPager) ){
   41649     nHeader = JOURNAL_HDR_SZ(pPager);
   41650   }
   41651 
   41652   /* If there are active savepoints and any of them were created
   41653   ** since the most recent journal header was written, update the
   41654   ** PagerSavepoint.iHdrOffset fields now.
   41655   */
   41656   for(ii=0; ii<pPager->nSavepoint; ii++){
   41657     if( pPager->aSavepoint[ii].iHdrOffset==0 ){
   41658       pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
   41659     }
   41660   }
   41661 
   41662   pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
   41663 
   41664   /*
   41665   ** Write the nRec Field - the number of page records that follow this
   41666   ** journal header. Normally, zero is written to this value at this time.
   41667   ** After the records are added to the journal (and the journal synced,
   41668   ** if in full-sync mode), the zero is overwritten with the true number
   41669   ** of records (see syncJournal()).
   41670   **
   41671   ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
   41672   ** reading the journal this value tells SQLite to assume that the
   41673   ** rest of the journal file contains valid page records. This assumption
   41674   ** is dangerous, as if a failure occurred whilst writing to the journal
   41675   ** file it may contain some garbage data. There are two scenarios
   41676   ** where this risk can be ignored:
   41677   **
   41678   **   * When the pager is in no-sync mode. Corruption can follow a
   41679   **     power failure in this case anyway.
   41680   **
   41681   **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
   41682   **     that garbage data is never appended to the journal file.
   41683   */
   41684   assert( isOpen(pPager->fd) || pPager->noSync );
   41685   if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
   41686    || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
   41687   ){
   41688     memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
   41689     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
   41690   }else{
   41691     memset(zHeader, 0, sizeof(aJournalMagic)+4);
   41692   }
   41693 
   41694   /* The random check-hash initializer */
   41695   sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
   41696   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
   41697   /* The initial database size */
   41698   put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
   41699   /* The assumed sector size for this process */
   41700   put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
   41701 
   41702   /* The page size */
   41703   put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
   41704 
   41705   /* Initializing the tail of the buffer is not necessary.  Everything
   41706   ** works find if the following memset() is omitted.  But initializing
   41707   ** the memory prevents valgrind from complaining, so we are willing to
   41708   ** take the performance hit.
   41709   */
   41710   memset(&zHeader[sizeof(aJournalMagic)+20], 0,
   41711          nHeader-(sizeof(aJournalMagic)+20));
   41712 
   41713   /* In theory, it is only necessary to write the 28 bytes that the
   41714   ** journal header consumes to the journal file here. Then increment the
   41715   ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
   41716   ** record is written to the following sector (leaving a gap in the file
   41717   ** that will be implicitly filled in by the OS).
   41718   **
   41719   ** However it has been discovered that on some systems this pattern can
   41720   ** be significantly slower than contiguously writing data to the file,
   41721   ** even if that means explicitly writing data to the block of
   41722   ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
   41723   ** is done.
   41724   **
   41725   ** The loop is required here in case the sector-size is larger than the
   41726   ** database page size. Since the zHeader buffer is only Pager.pageSize
   41727   ** bytes in size, more than one call to sqlite3OsWrite() may be required
   41728   ** to populate the entire journal header sector.
   41729   */
   41730   for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
   41731     IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
   41732     rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
   41733     assert( pPager->journalHdr <= pPager->journalOff );
   41734     pPager->journalOff += nHeader;
   41735   }
   41736 
   41737   return rc;
   41738 }
   41739 
   41740 /*
   41741 ** The journal file must be open when this is called. A journal header file
   41742 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
   41743 ** file. The current location in the journal file is given by
   41744 ** pPager->journalOff. See comments above function writeJournalHdr() for
   41745 ** a description of the journal header format.
   41746 **
   41747 ** If the header is read successfully, *pNRec is set to the number of
   41748 ** page records following this header and *pDbSize is set to the size of the
   41749 ** database before the transaction began, in pages. Also, pPager->cksumInit
   41750 ** is set to the value read from the journal header. SQLITE_OK is returned
   41751 ** in this case.
   41752 **
   41753 ** If the journal header file appears to be corrupted, SQLITE_DONE is
   41754 ** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
   41755 ** cannot be read from the journal file an error code is returned.
   41756 */
   41757 static int readJournalHdr(
   41758   Pager *pPager,               /* Pager object */
   41759   int isHot,
   41760   i64 journalSize,             /* Size of the open journal file in bytes */
   41761   u32 *pNRec,                  /* OUT: Value read from the nRec field */
   41762   u32 *pDbSize                 /* OUT: Value of original database size field */
   41763 ){
   41764   int rc;                      /* Return code */
   41765   unsigned char aMagic[8];     /* A buffer to hold the magic header */
   41766   i64 iHdrOff;                 /* Offset of journal header being read */
   41767 
   41768   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
   41769 
   41770   /* Advance Pager.journalOff to the start of the next sector. If the
   41771   ** journal file is too small for there to be a header stored at this
   41772   ** point, return SQLITE_DONE.
   41773   */
   41774   pPager->journalOff = journalHdrOffset(pPager);
   41775   if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
   41776     return SQLITE_DONE;
   41777   }
   41778   iHdrOff = pPager->journalOff;
   41779 
   41780   /* Read in the first 8 bytes of the journal header. If they do not match
   41781   ** the  magic string found at the start of each journal header, return
   41782   ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
   41783   ** proceed.
   41784   */
   41785   if( isHot || iHdrOff!=pPager->journalHdr ){
   41786     rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
   41787     if( rc ){
   41788       return rc;
   41789     }
   41790     if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
   41791       return SQLITE_DONE;
   41792     }
   41793   }
   41794 
   41795   /* Read the first three 32-bit fields of the journal header: The nRec
   41796   ** field, the checksum-initializer and the database size at the start
   41797   ** of the transaction. Return an error code if anything goes wrong.
   41798   */
   41799   if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
   41800    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
   41801    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
   41802   ){
   41803     return rc;
   41804   }
   41805 
   41806   if( pPager->journalOff==0 ){
   41807     u32 iPageSize;               /* Page-size field of journal header */
   41808     u32 iSectorSize;             /* Sector-size field of journal header */
   41809 
   41810     /* Read the page-size and sector-size journal header fields. */
   41811     if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
   41812      || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
   41813     ){
   41814       return rc;
   41815     }
   41816 
   41817     /* Versions of SQLite prior to 3.5.8 set the page-size field of the
   41818     ** journal header to zero. In this case, assume that the Pager.pageSize
   41819     ** variable is already set to the correct page size.
   41820     */
   41821     if( iPageSize==0 ){
   41822       iPageSize = pPager->pageSize;
   41823     }
   41824 
   41825     /* Check that the values read from the page-size and sector-size fields
   41826     ** are within range. To be 'in range', both values need to be a power
   41827     ** of two greater than or equal to 512 or 32, and not greater than their
   41828     ** respective compile time maximum limits.
   41829     */
   41830     if( iPageSize<512                  || iSectorSize<32
   41831      || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
   41832      || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0
   41833     ){
   41834       /* If the either the page-size or sector-size in the journal-header is
   41835       ** invalid, then the process that wrote the journal-header must have
   41836       ** crashed before the header was synced. In this case stop reading
   41837       ** the journal file here.
   41838       */
   41839       return SQLITE_DONE;
   41840     }
   41841 
   41842     /* Update the page-size to match the value read from the journal.
   41843     ** Use a testcase() macro to make sure that malloc failure within
   41844     ** PagerSetPagesize() is tested.
   41845     */
   41846     rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
   41847     testcase( rc!=SQLITE_OK );
   41848 
   41849     /* Update the assumed sector-size to match the value used by
   41850     ** the process that created this journal. If this journal was
   41851     ** created by a process other than this one, then this routine
   41852     ** is being called from within pager_playback(). The local value
   41853     ** of Pager.sectorSize is restored at the end of that routine.
   41854     */
   41855     pPager->sectorSize = iSectorSize;
   41856   }
   41857 
   41858   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
   41859   return rc;
   41860 }
   41861 
   41862 
   41863 /*
   41864 ** Write the supplied master journal name into the journal file for pager
   41865 ** pPager at the current location. The master journal name must be the last
   41866 ** thing written to a journal file. If the pager is in full-sync mode, the
   41867 ** journal file descriptor is advanced to the next sector boundary before
   41868 ** anything is written. The format is:
   41869 **
   41870 **   + 4 bytes: PAGER_MJ_PGNO.
   41871 **   + N bytes: Master journal filename in utf-8.
   41872 **   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
   41873 **   + 4 bytes: Master journal name checksum.
   41874 **   + 8 bytes: aJournalMagic[].
   41875 **
   41876 ** The master journal page checksum is the sum of the bytes in the master
   41877 ** journal name, where each byte is interpreted as a signed 8-bit integer.
   41878 **
   41879 ** If zMaster is a NULL pointer (occurs for a single database transaction),
   41880 ** this call is a no-op.
   41881 */
   41882 static int writeMasterJournal(Pager *pPager, const char *zMaster){
   41883   int rc;                          /* Return code */
   41884   int nMaster;                     /* Length of string zMaster */
   41885   i64 iHdrOff;                     /* Offset of header in journal file */
   41886   i64 jrnlSize;                    /* Size of journal file on disk */
   41887   u32 cksum = 0;                   /* Checksum of string zMaster */
   41888 
   41889   assert( pPager->setMaster==0 );
   41890   assert( !pagerUseWal(pPager) );
   41891 
   41892   if( !zMaster
   41893    || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
   41894    || !isOpen(pPager->jfd)
   41895   ){
   41896     return SQLITE_OK;
   41897   }
   41898   pPager->setMaster = 1;
   41899   assert( pPager->journalHdr <= pPager->journalOff );
   41900 
   41901   /* Calculate the length in bytes and the checksum of zMaster */
   41902   for(nMaster=0; zMaster[nMaster]; nMaster++){
   41903     cksum += zMaster[nMaster];
   41904   }
   41905 
   41906   /* If in full-sync mode, advance to the next disk sector before writing
   41907   ** the master journal name. This is in case the previous page written to
   41908   ** the journal has already been synced.
   41909   */
   41910   if( pPager->fullSync ){
   41911     pPager->journalOff = journalHdrOffset(pPager);
   41912   }
   41913   iHdrOff = pPager->journalOff;
   41914 
   41915   /* Write the master journal data to the end of the journal file. If
   41916   ** an error occurs, return the error code to the caller.
   41917   */
   41918   if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
   41919    || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
   41920    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
   41921    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
   41922    || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
   41923   ){
   41924     return rc;
   41925   }
   41926   pPager->journalOff += (nMaster+20);
   41927 
   41928   /* If the pager is in peristent-journal mode, then the physical
   41929   ** journal-file may extend past the end of the master-journal name
   41930   ** and 8 bytes of magic data just written to the file. This is
   41931   ** dangerous because the code to rollback a hot-journal file
   41932   ** will not be able to find the master-journal name to determine
   41933   ** whether or not the journal is hot.
   41934   **
   41935   ** Easiest thing to do in this scenario is to truncate the journal
   41936   ** file to the required size.
   41937   */
   41938   if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
   41939    && jrnlSize>pPager->journalOff
   41940   ){
   41941     rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
   41942   }
   41943   return rc;
   41944 }
   41945 
   41946 /*
   41947 ** Find a page in the hash table given its page number. Return
   41948 ** a pointer to the page or NULL if the requested page is not
   41949 ** already in memory.
   41950 */
   41951 static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
   41952   PgHdr *p = 0;                     /* Return value */
   41953 
   41954   /* It is not possible for a call to PcacheFetch() with createFlag==0 to
   41955   ** fail, since no attempt to allocate dynamic memory will be made.
   41956   */
   41957   (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
   41958   return p;
   41959 }
   41960 
   41961 /*
   41962 ** Discard the entire contents of the in-memory page-cache.
   41963 */
   41964 static void pager_reset(Pager *pPager){
   41965   sqlite3BackupRestart(pPager->pBackup);
   41966   sqlite3PcacheClear(pPager->pPCache);
   41967 }
   41968 
   41969 /*
   41970 ** Free all structures in the Pager.aSavepoint[] array and set both
   41971 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
   41972 ** if it is open and the pager is not in exclusive mode.
   41973 */
   41974 static void releaseAllSavepoints(Pager *pPager){
   41975   int ii;               /* Iterator for looping through Pager.aSavepoint */
   41976   for(ii=0; ii<pPager->nSavepoint; ii++){
   41977     sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
   41978   }
   41979   if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
   41980     sqlite3OsClose(pPager->sjfd);
   41981   }
   41982   sqlite3_free(pPager->aSavepoint);
   41983   pPager->aSavepoint = 0;
   41984   pPager->nSavepoint = 0;
   41985   pPager->nSubRec = 0;
   41986 }
   41987 
   41988 /*
   41989 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
   41990 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
   41991 ** or SQLITE_NOMEM if a malloc failure occurs.
   41992 */
   41993 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
   41994   int ii;                   /* Loop counter */
   41995   int rc = SQLITE_OK;       /* Result code */
   41996 
   41997   for(ii=0; ii<pPager->nSavepoint; ii++){
   41998     PagerSavepoint *p = &pPager->aSavepoint[ii];
   41999     if( pgno<=p->nOrig ){
   42000       rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
   42001       testcase( rc==SQLITE_NOMEM );
   42002       assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
   42003     }
   42004   }
   42005   return rc;
   42006 }
   42007 
   42008 /*
   42009 ** This function is a no-op if the pager is in exclusive mode and not
   42010 ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
   42011 ** state.
   42012 **
   42013 ** If the pager is not in exclusive-access mode, the database file is
   42014 ** completely unlocked. If the file is unlocked and the file-system does
   42015 ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
   42016 ** closed (if it is open).
   42017 **
   42018 ** If the pager is in ERROR state when this function is called, the
   42019 ** contents of the pager cache are discarded before switching back to
   42020 ** the OPEN state. Regardless of whether the pager is in exclusive-mode
   42021 ** or not, any journal file left in the file-system will be treated
   42022 ** as a hot-journal and rolled back the next time a read-transaction
   42023 ** is opened (by this or by any other connection).
   42024 */
   42025 static void pager_unlock(Pager *pPager){
   42026 
   42027   assert( pPager->eState==PAGER_READER
   42028        || pPager->eState==PAGER_OPEN
   42029        || pPager->eState==PAGER_ERROR
   42030   );
   42031 
   42032   sqlite3BitvecDestroy(pPager->pInJournal);
   42033   pPager->pInJournal = 0;
   42034   releaseAllSavepoints(pPager);
   42035 
   42036   if( pagerUseWal(pPager) ){
   42037     assert( !isOpen(pPager->jfd) );
   42038     sqlite3WalEndReadTransaction(pPager->pWal);
   42039     pPager->eState = PAGER_OPEN;
   42040   }else if( !pPager->exclusiveMode ){
   42041     int rc;                       /* Error code returned by pagerUnlockDb() */
   42042     int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
   42043 
   42044     /* If the operating system support deletion of open files, then
   42045     ** close the journal file when dropping the database lock.  Otherwise
   42046     ** another connection with journal_mode=delete might delete the file
   42047     ** out from under us.
   42048     */
   42049     assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
   42050     assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
   42051     assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
   42052     assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
   42053     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
   42054     assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
   42055     if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
   42056      || 1!=(pPager->journalMode & 5)
   42057     ){
   42058       sqlite3OsClose(pPager->jfd);
   42059     }
   42060 
   42061     /* If the pager is in the ERROR state and the call to unlock the database
   42062     ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
   42063     ** above the #define for UNKNOWN_LOCK for an explanation of why this
   42064     ** is necessary.
   42065     */
   42066     rc = pagerUnlockDb(pPager, NO_LOCK);
   42067     if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
   42068       pPager->eLock = UNKNOWN_LOCK;
   42069     }
   42070 
   42071     /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
   42072     ** without clearing the error code. This is intentional - the error
   42073     ** code is cleared and the cache reset in the block below.
   42074     */
   42075     assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
   42076     pPager->changeCountDone = 0;
   42077     pPager->eState = PAGER_OPEN;
   42078   }
   42079 
   42080   /* If Pager.errCode is set, the contents of the pager cache cannot be
   42081   ** trusted. Now that there are no outstanding references to the pager,
   42082   ** it can safely move back to PAGER_OPEN state. This happens in both
   42083   ** normal and exclusive-locking mode.
   42084   */
   42085   if( pPager->errCode ){
   42086     assert( !MEMDB );
   42087     pager_reset(pPager);
   42088     pPager->changeCountDone = pPager->tempFile;
   42089     pPager->eState = PAGER_OPEN;
   42090     pPager->errCode = SQLITE_OK;
   42091     if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
   42092   }
   42093 
   42094   pPager->journalOff = 0;
   42095   pPager->journalHdr = 0;
   42096   pPager->setMaster = 0;
   42097 }
   42098 
   42099 /*
   42100 ** This function is called whenever an IOERR or FULL error that requires
   42101 ** the pager to transition into the ERROR state may ahve occurred.
   42102 ** The first argument is a pointer to the pager structure, the second
   42103 ** the error-code about to be returned by a pager API function. The
   42104 ** value returned is a copy of the second argument to this function.
   42105 **
   42106 ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
   42107 ** IOERR sub-codes, the pager enters the ERROR state and the error code
   42108 ** is stored in Pager.errCode. While the pager remains in the ERROR state,
   42109 ** all major API calls on the Pager will immediately return Pager.errCode.
   42110 **
   42111 ** The ERROR state indicates that the contents of the pager-cache
   42112 ** cannot be trusted. This state can be cleared by completely discarding
   42113 ** the contents of the pager-cache. If a transaction was active when
   42114 ** the persistent error occurred, then the rollback journal may need
   42115 ** to be replayed to restore the contents of the database file (as if
   42116 ** it were a hot-journal).
   42117 */
   42118 static int pager_error(Pager *pPager, int rc){
   42119   int rc2 = rc & 0xff;
   42120   assert( rc==SQLITE_OK || !MEMDB );
   42121   assert(
   42122        pPager->errCode==SQLITE_FULL ||
   42123        pPager->errCode==SQLITE_OK ||
   42124        (pPager->errCode & 0xff)==SQLITE_IOERR
   42125   );
   42126   if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
   42127     pPager->errCode = rc;
   42128     pPager->eState = PAGER_ERROR;
   42129   }
   42130   return rc;
   42131 }
   42132 
   42133 static int pager_truncate(Pager *pPager, Pgno nPage);
   42134 
   42135 /*
   42136 ** This routine ends a transaction. A transaction is usually ended by
   42137 ** either a COMMIT or a ROLLBACK operation. This routine may be called
   42138 ** after rollback of a hot-journal, or if an error occurs while opening
   42139 ** the journal file or writing the very first journal-header of a
   42140 ** database transaction.
   42141 **
   42142 ** This routine is never called in PAGER_ERROR state. If it is called
   42143 ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
   42144 ** exclusive than a RESERVED lock, it is a no-op.
   42145 **
   42146 ** Otherwise, any active savepoints are released.
   42147 **
   42148 ** If the journal file is open, then it is "finalized". Once a journal
   42149 ** file has been finalized it is not possible to use it to roll back a
   42150 ** transaction. Nor will it be considered to be a hot-journal by this
   42151 ** or any other database connection. Exactly how a journal is finalized
   42152 ** depends on whether or not the pager is running in exclusive mode and
   42153 ** the current journal-mode (Pager.journalMode value), as follows:
   42154 **
   42155 **   journalMode==MEMORY
   42156 **     Journal file descriptor is simply closed. This destroys an
   42157 **     in-memory journal.
   42158 **
   42159 **   journalMode==TRUNCATE
   42160 **     Journal file is truncated to zero bytes in size.
   42161 **
   42162 **   journalMode==PERSIST
   42163 **     The first 28 bytes of the journal file are zeroed. This invalidates
   42164 **     the first journal header in the file, and hence the entire journal
   42165 **     file. An invalid journal file cannot be rolled back.
   42166 **
   42167 **   journalMode==DELETE
   42168 **     The journal file is closed and deleted using sqlite3OsDelete().
   42169 **
   42170 **     If the pager is running in exclusive mode, this method of finalizing
   42171 **     the journal file is never used. Instead, if the journalMode is
   42172 **     DELETE and the pager is in exclusive mode, the method described under
   42173 **     journalMode==PERSIST is used instead.
   42174 **
   42175 ** After the journal is finalized, the pager moves to PAGER_READER state.
   42176 ** If running in non-exclusive rollback mode, the lock on the file is
   42177 ** downgraded to a SHARED_LOCK.
   42178 **
   42179 ** SQLITE_OK is returned if no error occurs. If an error occurs during
   42180 ** any of the IO operations to finalize the journal file or unlock the
   42181 ** database then the IO error code is returned to the user. If the
   42182 ** operation to finalize the journal file fails, then the code still
   42183 ** tries to unlock the database file if not in exclusive mode. If the
   42184 ** unlock operation fails as well, then the first error code related
   42185 ** to the first error encountered (the journal finalization one) is
   42186 ** returned.
   42187 */
   42188 static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
   42189   int rc = SQLITE_OK;      /* Error code from journal finalization operation */
   42190   int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
   42191 
   42192   /* Do nothing if the pager does not have an open write transaction
   42193   ** or at least a RESERVED lock. This function may be called when there
   42194   ** is no write-transaction active but a RESERVED or greater lock is
   42195   ** held under two circumstances:
   42196   **
   42197   **   1. After a successful hot-journal rollback, it is called with
   42198   **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
   42199   **
   42200   **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
   42201   **      lock switches back to locking_mode=normal and then executes a
   42202   **      read-transaction, this function is called with eState==PAGER_READER
   42203   **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
   42204   */
   42205   assert( assert_pager_state(pPager) );
   42206   assert( pPager->eState!=PAGER_ERROR );
   42207   if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
   42208     return SQLITE_OK;
   42209   }
   42210 
   42211   releaseAllSavepoints(pPager);
   42212   assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
   42213   if( isOpen(pPager->jfd) ){
   42214     assert( !pagerUseWal(pPager) );
   42215 
   42216     /* Finalize the journal file. */
   42217     if( sqlite3IsMemJournal(pPager->jfd) ){
   42218       assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
   42219       sqlite3OsClose(pPager->jfd);
   42220     }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
   42221       if( pPager->journalOff==0 ){
   42222         rc = SQLITE_OK;
   42223       }else{
   42224         rc = sqlite3OsTruncate(pPager->jfd, 0);
   42225       }
   42226       pPager->journalOff = 0;
   42227     }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
   42228       || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
   42229     ){
   42230       rc = zeroJournalHdr(pPager, hasMaster);
   42231       pPager->journalOff = 0;
   42232     }else{
   42233       /* This branch may be executed with Pager.journalMode==MEMORY if
   42234       ** a hot-journal was just rolled back. In this case the journal
   42235       ** file should be closed and deleted. If this connection writes to
   42236       ** the database file, it will do so using an in-memory journal.
   42237       */
   42238       int bDelete = (!pPager->tempFile && sqlite3JournalExists(pPager->jfd));
   42239       assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
   42240            || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
   42241            || pPager->journalMode==PAGER_JOURNALMODE_WAL
   42242       );
   42243       sqlite3OsClose(pPager->jfd);
   42244       if( bDelete ){
   42245         rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
   42246       }
   42247     }
   42248   }
   42249 
   42250 #ifdef SQLITE_CHECK_PAGES
   42251   sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
   42252   if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
   42253     PgHdr *p = pager_lookup(pPager, 1);
   42254     if( p ){
   42255       p->pageHash = 0;
   42256       sqlite3PagerUnrefNotNull(p);
   42257     }
   42258   }
   42259 #endif
   42260 
   42261   sqlite3BitvecDestroy(pPager->pInJournal);
   42262   pPager->pInJournal = 0;
   42263   pPager->nRec = 0;
   42264   sqlite3PcacheCleanAll(pPager->pPCache);
   42265   sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
   42266 
   42267   if( pagerUseWal(pPager) ){
   42268     /* Drop the WAL write-lock, if any. Also, if the connection was in
   42269     ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
   42270     ** lock held on the database file.
   42271     */
   42272     rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
   42273     assert( rc2==SQLITE_OK );
   42274   }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
   42275     /* This branch is taken when committing a transaction in rollback-journal
   42276     ** mode if the database file on disk is larger than the database image.
   42277     ** At this point the journal has been finalized and the transaction
   42278     ** successfully committed, but the EXCLUSIVE lock is still held on the
   42279     ** file. So it is safe to truncate the database file to its minimum
   42280     ** required size.  */
   42281     assert( pPager->eLock==EXCLUSIVE_LOCK );
   42282     rc = pager_truncate(pPager, pPager->dbSize);
   42283   }
   42284 
   42285   if( rc==SQLITE_OK && bCommit && isOpen(pPager->fd) ){
   42286     rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);
   42287     if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
   42288   }
   42289 
   42290   if( !pPager->exclusiveMode
   42291    && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
   42292   ){
   42293     rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
   42294     pPager->changeCountDone = 0;
   42295   }
   42296   pPager->eState = PAGER_READER;
   42297   pPager->setMaster = 0;
   42298 
   42299   return (rc==SQLITE_OK?rc2:rc);
   42300 }
   42301 
   42302 /*
   42303 ** Execute a rollback if a transaction is active and unlock the
   42304 ** database file.
   42305 **
   42306 ** If the pager has already entered the ERROR state, do not attempt
   42307 ** the rollback at this time. Instead, pager_unlock() is called. The
   42308 ** call to pager_unlock() will discard all in-memory pages, unlock
   42309 ** the database file and move the pager back to OPEN state. If this
   42310 ** means that there is a hot-journal left in the file-system, the next
   42311 ** connection to obtain a shared lock on the pager (which may be this one)
   42312 ** will roll it back.
   42313 **
   42314 ** If the pager has not already entered the ERROR state, but an IO or
   42315 ** malloc error occurs during a rollback, then this will itself cause
   42316 ** the pager to enter the ERROR state. Which will be cleared by the
   42317 ** call to pager_unlock(), as described above.
   42318 */
   42319 static void pagerUnlockAndRollback(Pager *pPager){
   42320   if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
   42321     assert( assert_pager_state(pPager) );
   42322     if( pPager->eState>=PAGER_WRITER_LOCKED ){
   42323       sqlite3BeginBenignMalloc();
   42324       sqlite3PagerRollback(pPager);
   42325       sqlite3EndBenignMalloc();
   42326     }else if( !pPager->exclusiveMode ){
   42327       assert( pPager->eState==PAGER_READER );
   42328       pager_end_transaction(pPager, 0, 0);
   42329     }
   42330   }
   42331   pager_unlock(pPager);
   42332 }
   42333 
   42334 /*
   42335 ** Parameter aData must point to a buffer of pPager->pageSize bytes
   42336 ** of data. Compute and return a checksum based ont the contents of the
   42337 ** page of data and the current value of pPager->cksumInit.
   42338 **
   42339 ** This is not a real checksum. It is really just the sum of the
   42340 ** random initial value (pPager->cksumInit) and every 200th byte
   42341 ** of the page data, starting with byte offset (pPager->pageSize%200).
   42342 ** Each byte is interpreted as an 8-bit unsigned integer.
   42343 **
   42344 ** Changing the formula used to compute this checksum results in an
   42345 ** incompatible journal file format.
   42346 **
   42347 ** If journal corruption occurs due to a power failure, the most likely
   42348 ** scenario is that one end or the other of the record will be changed.
   42349 ** It is much less likely that the two ends of the journal record will be
   42350 ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
   42351 ** though fast and simple, catches the mostly likely kind of corruption.
   42352 */
   42353 static u32 pager_cksum(Pager *pPager, const u8 *aData){
   42354   u32 cksum = pPager->cksumInit;         /* Checksum value to return */
   42355   int i = pPager->pageSize-200;          /* Loop counter */
   42356   while( i>0 ){
   42357     cksum += aData[i];
   42358     i -= 200;
   42359   }
   42360   return cksum;
   42361 }
   42362 
   42363 /*
   42364 ** Report the current page size and number of reserved bytes back
   42365 ** to the codec.
   42366 */
   42367 #ifdef SQLITE_HAS_CODEC
   42368 static void pagerReportSize(Pager *pPager){
   42369   if( pPager->xCodecSizeChng ){
   42370     pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
   42371                            (int)pPager->nReserve);
   42372   }
   42373 }
   42374 #else
   42375 # define pagerReportSize(X)     /* No-op if we do not support a codec */
   42376 #endif
   42377 
   42378 /*
   42379 ** Read a single page from either the journal file (if isMainJrnl==1) or
   42380 ** from the sub-journal (if isMainJrnl==0) and playback that page.
   42381 ** The page begins at offset *pOffset into the file. The *pOffset
   42382 ** value is increased to the start of the next page in the journal.
   42383 **
   42384 ** The main rollback journal uses checksums - the statement journal does
   42385 ** not.
   42386 **
   42387 ** If the page number of the page record read from the (sub-)journal file
   42388 ** is greater than the current value of Pager.dbSize, then playback is
   42389 ** skipped and SQLITE_OK is returned.
   42390 **
   42391 ** If pDone is not NULL, then it is a record of pages that have already
   42392 ** been played back.  If the page at *pOffset has already been played back
   42393 ** (if the corresponding pDone bit is set) then skip the playback.
   42394 ** Make sure the pDone bit corresponding to the *pOffset page is set
   42395 ** prior to returning.
   42396 **
   42397 ** If the page record is successfully read from the (sub-)journal file
   42398 ** and played back, then SQLITE_OK is returned. If an IO error occurs
   42399 ** while reading the record from the (sub-)journal file or while writing
   42400 ** to the database file, then the IO error code is returned. If data
   42401 ** is successfully read from the (sub-)journal file but appears to be
   42402 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
   42403 ** two circumstances:
   42404 **
   42405 **   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
   42406 **   * If the record is being rolled back from the main journal file
   42407 **     and the checksum field does not match the record content.
   42408 **
   42409 ** Neither of these two scenarios are possible during a savepoint rollback.
   42410 **
   42411 ** If this is a savepoint rollback, then memory may have to be dynamically
   42412 ** allocated by this function. If this is the case and an allocation fails,
   42413 ** SQLITE_NOMEM is returned.
   42414 */
   42415 static int pager_playback_one_page(
   42416   Pager *pPager,                /* The pager being played back */
   42417   i64 *pOffset,                 /* Offset of record to playback */
   42418   Bitvec *pDone,                /* Bitvec of pages already played back */
   42419   int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
   42420   int isSavepnt                 /* True for a savepoint rollback */
   42421 ){
   42422   int rc;
   42423   PgHdr *pPg;                   /* An existing page in the cache */
   42424   Pgno pgno;                    /* The page number of a page in journal */
   42425   u32 cksum;                    /* Checksum used for sanity checking */
   42426   char *aData;                  /* Temporary storage for the page */
   42427   sqlite3_file *jfd;            /* The file descriptor for the journal file */
   42428   int isSynced;                 /* True if journal page is synced */
   42429 
   42430   assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
   42431   assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
   42432   assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
   42433   assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
   42434 
   42435   aData = pPager->pTmpSpace;
   42436   assert( aData );         /* Temp storage must have already been allocated */
   42437   assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
   42438 
   42439   /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
   42440   ** or savepoint rollback done at the request of the caller) or this is
   42441   ** a hot-journal rollback. If it is a hot-journal rollback, the pager
   42442   ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
   42443   ** only reads from the main journal, not the sub-journal.
   42444   */
   42445   assert( pPager->eState>=PAGER_WRITER_CACHEMOD
   42446        || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
   42447   );
   42448   assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
   42449 
   42450   /* Read the page number and page data from the journal or sub-journal
   42451   ** file. Return an error code to the caller if an IO error occurs.
   42452   */
   42453   jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
   42454   rc = read32bits(jfd, *pOffset, &pgno);
   42455   if( rc!=SQLITE_OK ) return rc;
   42456   rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
   42457   if( rc!=SQLITE_OK ) return rc;
   42458   *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
   42459 
   42460   /* Sanity checking on the page.  This is more important that I originally
   42461   ** thought.  If a power failure occurs while the journal is being written,
   42462   ** it could cause invalid data to be written into the journal.  We need to
   42463   ** detect this invalid data (with high probability) and ignore it.
   42464   */
   42465   if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
   42466     assert( !isSavepnt );
   42467     return SQLITE_DONE;
   42468   }
   42469   if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
   42470     return SQLITE_OK;
   42471   }
   42472   if( isMainJrnl ){
   42473     rc = read32bits(jfd, (*pOffset)-4, &cksum);
   42474     if( rc ) return rc;
   42475     if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
   42476       return SQLITE_DONE;
   42477     }
   42478   }
   42479 
   42480   /* If this page has already been played by before during the current
   42481   ** rollback, then don't bother to play it back again.
   42482   */
   42483   if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
   42484     return rc;
   42485   }
   42486 
   42487   /* When playing back page 1, restore the nReserve setting
   42488   */
   42489   if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
   42490     pPager->nReserve = ((u8*)aData)[20];
   42491     pagerReportSize(pPager);
   42492   }
   42493 
   42494   /* If the pager is in CACHEMOD state, then there must be a copy of this
   42495   ** page in the pager cache. In this case just update the pager cache,
   42496   ** not the database file. The page is left marked dirty in this case.
   42497   **
   42498   ** An exception to the above rule: If the database is in no-sync mode
   42499   ** and a page is moved during an incremental vacuum then the page may
   42500   ** not be in the pager cache. Later: if a malloc() or IO error occurs
   42501   ** during a Movepage() call, then the page may not be in the cache
   42502   ** either. So the condition described in the above paragraph is not
   42503   ** assert()able.
   42504   **
   42505   ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
   42506   ** pager cache if it exists and the main file. The page is then marked
   42507   ** not dirty. Since this code is only executed in PAGER_OPEN state for
   42508   ** a hot-journal rollback, it is guaranteed that the page-cache is empty
   42509   ** if the pager is in OPEN state.
   42510   **
   42511   ** Ticket #1171:  The statement journal might contain page content that is
   42512   ** different from the page content at the start of the transaction.
   42513   ** This occurs when a page is changed prior to the start of a statement
   42514   ** then changed again within the statement.  When rolling back such a
   42515   ** statement we must not write to the original database unless we know
   42516   ** for certain that original page contents are synced into the main rollback
   42517   ** journal.  Otherwise, a power loss might leave modified data in the
   42518   ** database file without an entry in the rollback journal that can
   42519   ** restore the database to its original form.  Two conditions must be
   42520   ** met before writing to the database files. (1) the database must be
   42521   ** locked.  (2) we know that the original page content is fully synced
   42522   ** in the main journal either because the page is not in cache or else
   42523   ** the page is marked as needSync==0.
   42524   **
   42525   ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
   42526   ** is possible to fail a statement on a database that does not yet exist.
   42527   ** Do not attempt to write if database file has never been opened.
   42528   */
   42529   if( pagerUseWal(pPager) ){
   42530     pPg = 0;
   42531   }else{
   42532     pPg = pager_lookup(pPager, pgno);
   42533   }
   42534   assert( pPg || !MEMDB );
   42535   assert( pPager->eState!=PAGER_OPEN || pPg==0 );
   42536   PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
   42537            PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
   42538            (isMainJrnl?"main-journal":"sub-journal")
   42539   ));
   42540   if( isMainJrnl ){
   42541     isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
   42542   }else{
   42543     isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
   42544   }
   42545   if( isOpen(pPager->fd)
   42546    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
   42547    && isSynced
   42548   ){
   42549     i64 ofst = (pgno-1)*(i64)pPager->pageSize;
   42550     testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
   42551     assert( !pagerUseWal(pPager) );
   42552     rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
   42553     if( pgno>pPager->dbFileSize ){
   42554       pPager->dbFileSize = pgno;
   42555     }
   42556     if( pPager->pBackup ){
   42557       CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
   42558       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
   42559       CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
   42560     }
   42561   }else if( !isMainJrnl && pPg==0 ){
   42562     /* If this is a rollback of a savepoint and data was not written to
   42563     ** the database and the page is not in-memory, there is a potential
   42564     ** problem. When the page is next fetched by the b-tree layer, it
   42565     ** will be read from the database file, which may or may not be
   42566     ** current.
   42567     **
   42568     ** There are a couple of different ways this can happen. All are quite
   42569     ** obscure. When running in synchronous mode, this can only happen
   42570     ** if the page is on the free-list at the start of the transaction, then
   42571     ** populated, then moved using sqlite3PagerMovepage().
   42572     **
   42573     ** The solution is to add an in-memory page to the cache containing
   42574     ** the data just read from the sub-journal. Mark the page as dirty
   42575     ** and if the pager requires a journal-sync, then mark the page as
   42576     ** requiring a journal-sync before it is written.
   42577     */
   42578     assert( isSavepnt );
   42579     assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
   42580     pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
   42581     rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
   42582     assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
   42583     pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
   42584     if( rc!=SQLITE_OK ) return rc;
   42585     pPg->flags &= ~PGHDR_NEED_READ;
   42586     sqlite3PcacheMakeDirty(pPg);
   42587   }
   42588   if( pPg ){
   42589     /* No page should ever be explicitly rolled back that is in use, except
   42590     ** for page 1 which is held in use in order to keep the lock on the
   42591     ** database active. However such a page may be rolled back as a result
   42592     ** of an internal error resulting in an automatic call to
   42593     ** sqlite3PagerRollback().
   42594     */
   42595     void *pData;
   42596     pData = pPg->pData;
   42597     memcpy(pData, (u8*)aData, pPager->pageSize);
   42598     pPager->xReiniter(pPg);
   42599     if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
   42600       /* If the contents of this page were just restored from the main
   42601       ** journal file, then its content must be as they were when the
   42602       ** transaction was first opened. In this case we can mark the page
   42603       ** as clean, since there will be no need to write it out to the
   42604       ** database.
   42605       **
   42606       ** There is one exception to this rule. If the page is being rolled
   42607       ** back as part of a savepoint (or statement) rollback from an
   42608       ** unsynced portion of the main journal file, then it is not safe
   42609       ** to mark the page as clean. This is because marking the page as
   42610       ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
   42611       ** already in the journal file (recorded in Pager.pInJournal) and
   42612       ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
   42613       ** again within this transaction, it will be marked as dirty but
   42614       ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
   42615       ** be written out into the database file before its journal file
   42616       ** segment is synced. If a crash occurs during or following this,
   42617       ** database corruption may ensue.
   42618       */
   42619       assert( !pagerUseWal(pPager) );
   42620       sqlite3PcacheMakeClean(pPg);
   42621     }
   42622     pager_set_pagehash(pPg);
   42623 
   42624     /* If this was page 1, then restore the value of Pager.dbFileVers.
   42625     ** Do this before any decoding. */
   42626     if( pgno==1 ){
   42627       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
   42628     }
   42629 
   42630     /* Decode the page just read from disk */
   42631     CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
   42632     sqlite3PcacheRelease(pPg);
   42633   }
   42634   return rc;
   42635 }
   42636 
   42637 /*
   42638 ** Parameter zMaster is the name of a master journal file. A single journal
   42639 ** file that referred to the master journal file has just been rolled back.
   42640 ** This routine checks if it is possible to delete the master journal file,
   42641 ** and does so if it is.
   42642 **
   42643 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
   42644 ** available for use within this function.
   42645 **
   42646 ** When a master journal file is created, it is populated with the names
   42647 ** of all of its child journals, one after another, formatted as utf-8
   42648 ** encoded text. The end of each child journal file is marked with a
   42649 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
   42650 ** file for a transaction involving two databases might be:
   42651 **
   42652 **   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
   42653 **
   42654 ** A master journal file may only be deleted once all of its child
   42655 ** journals have been rolled back.
   42656 **
   42657 ** This function reads the contents of the master-journal file into
   42658 ** memory and loops through each of the child journal names. For
   42659 ** each child journal, it checks if:
   42660 **
   42661 **   * if the child journal exists, and if so
   42662 **   * if the child journal contains a reference to master journal
   42663 **     file zMaster
   42664 **
   42665 ** If a child journal can be found that matches both of the criteria
   42666 ** above, this function returns without doing anything. Otherwise, if
   42667 ** no such child journal can be found, file zMaster is deleted from
   42668 ** the file-system using sqlite3OsDelete().
   42669 **
   42670 ** If an IO error within this function, an error code is returned. This
   42671 ** function allocates memory by calling sqlite3Malloc(). If an allocation
   42672 ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
   42673 ** occur, SQLITE_OK is returned.
   42674 **
   42675 ** TODO: This function allocates a single block of memory to load
   42676 ** the entire contents of the master journal file. This could be
   42677 ** a couple of kilobytes or so - potentially larger than the page
   42678 ** size.
   42679 */
   42680 static int pager_delmaster(Pager *pPager, const char *zMaster){
   42681   sqlite3_vfs *pVfs = pPager->pVfs;
   42682   int rc;                   /* Return code */
   42683   sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
   42684   sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
   42685   char *zMasterJournal = 0; /* Contents of master journal file */
   42686   i64 nMasterJournal;       /* Size of master journal file */
   42687   char *zJournal;           /* Pointer to one journal within MJ file */
   42688   char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
   42689   int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
   42690 
   42691   /* Allocate space for both the pJournal and pMaster file descriptors.
   42692   ** If successful, open the master journal file for reading.
   42693   */
   42694   pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
   42695   pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
   42696   if( !pMaster ){
   42697     rc = SQLITE_NOMEM;
   42698   }else{
   42699     const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
   42700     rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
   42701   }
   42702   if( rc!=SQLITE_OK ) goto delmaster_out;
   42703 
   42704   /* Load the entire master journal file into space obtained from
   42705   ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
   42706   ** sufficient space (in zMasterPtr) to hold the names of master
   42707   ** journal files extracted from regular rollback-journals.
   42708   */
   42709   rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
   42710   if( rc!=SQLITE_OK ) goto delmaster_out;
   42711   nMasterPtr = pVfs->mxPathname+1;
   42712   zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
   42713   if( !zMasterJournal ){
   42714     rc = SQLITE_NOMEM;
   42715     goto delmaster_out;
   42716   }
   42717   zMasterPtr = &zMasterJournal[nMasterJournal+1];
   42718   rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
   42719   if( rc!=SQLITE_OK ) goto delmaster_out;
   42720   zMasterJournal[nMasterJournal] = 0;
   42721 
   42722   zJournal = zMasterJournal;
   42723   while( (zJournal-zMasterJournal)<nMasterJournal ){
   42724     int exists;
   42725     rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
   42726     if( rc!=SQLITE_OK ){
   42727       goto delmaster_out;
   42728     }
   42729     if( exists ){
   42730       /* One of the journals pointed to by the master journal exists.
   42731       ** Open it and check if it points at the master journal. If
   42732       ** so, return without deleting the master journal file.
   42733       */
   42734       int c;
   42735       int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
   42736       rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
   42737       if( rc!=SQLITE_OK ){
   42738         goto delmaster_out;
   42739       }
   42740 
   42741       rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
   42742       sqlite3OsClose(pJournal);
   42743       if( rc!=SQLITE_OK ){
   42744         goto delmaster_out;
   42745       }
   42746 
   42747       c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
   42748       if( c ){
   42749         /* We have a match. Do not delete the master journal file. */
   42750         goto delmaster_out;
   42751       }
   42752     }
   42753     zJournal += (sqlite3Strlen30(zJournal)+1);
   42754   }
   42755 
   42756   sqlite3OsClose(pMaster);
   42757   rc = sqlite3OsDelete(pVfs, zMaster, 0);
   42758 
   42759 delmaster_out:
   42760   sqlite3_free(zMasterJournal);
   42761   if( pMaster ){
   42762     sqlite3OsClose(pMaster);
   42763     assert( !isOpen(pJournal) );
   42764     sqlite3_free(pMaster);
   42765   }
   42766   return rc;
   42767 }
   42768 
   42769 
   42770 /*
   42771 ** This function is used to change the actual size of the database
   42772 ** file in the file-system. This only happens when committing a transaction,
   42773 ** or rolling back a transaction (including rolling back a hot-journal).
   42774 **
   42775 ** If the main database file is not open, or the pager is not in either
   42776 ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
   42777 ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
   42778 ** If the file on disk is currently larger than nPage pages, then use the VFS
   42779 ** xTruncate() method to truncate it.
   42780 **
   42781 ** Or, it might might be the case that the file on disk is smaller than
   42782 ** nPage pages. Some operating system implementations can get confused if
   42783 ** you try to truncate a file to some size that is larger than it
   42784 ** currently is, so detect this case and write a single zero byte to
   42785 ** the end of the new file instead.
   42786 **
   42787 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
   42788 ** the database file, return the error code to the caller.
   42789 */
   42790 static int pager_truncate(Pager *pPager, Pgno nPage){
   42791   int rc = SQLITE_OK;
   42792   assert( pPager->eState!=PAGER_ERROR );
   42793   assert( pPager->eState!=PAGER_READER );
   42794 
   42795   if( isOpen(pPager->fd)
   42796    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
   42797   ){
   42798     i64 currentSize, newSize;
   42799     int szPage = pPager->pageSize;
   42800     assert( pPager->eLock==EXCLUSIVE_LOCK );
   42801     /* TODO: Is it safe to use Pager.dbFileSize here? */
   42802     rc = sqlite3OsFileSize(pPager->fd, &currentSize);
   42803     newSize = szPage*(i64)nPage;
   42804     if( rc==SQLITE_OK && currentSize!=newSize ){
   42805       if( currentSize>newSize ){
   42806         rc = sqlite3OsTruncate(pPager->fd, newSize);
   42807       }else if( (currentSize+szPage)<=newSize ){
   42808         char *pTmp = pPager->pTmpSpace;
   42809         memset(pTmp, 0, szPage);
   42810         testcase( (newSize-szPage) == currentSize );
   42811         testcase( (newSize-szPage) >  currentSize );
   42812         rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
   42813       }
   42814       if( rc==SQLITE_OK ){
   42815         pPager->dbFileSize = nPage;
   42816       }
   42817     }
   42818   }
   42819   return rc;
   42820 }
   42821 
   42822 /*
   42823 ** Return a sanitized version of the sector-size of OS file pFile. The
   42824 ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
   42825 */
   42826 SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
   42827   int iRet = sqlite3OsSectorSize(pFile);
   42828   if( iRet<32 ){
   42829     iRet = 512;
   42830   }else if( iRet>MAX_SECTOR_SIZE ){
   42831     assert( MAX_SECTOR_SIZE>=512 );
   42832     iRet = MAX_SECTOR_SIZE;
   42833   }
   42834   return iRet;
   42835 }
   42836 
   42837 /*
   42838 ** Set the value of the Pager.sectorSize variable for the given
   42839 ** pager based on the value returned by the xSectorSize method
   42840 ** of the open database file. The sector size will be used used
   42841 ** to determine the size and alignment of journal header and
   42842 ** master journal pointers within created journal files.
   42843 **
   42844 ** For temporary files the effective sector size is always 512 bytes.
   42845 **
   42846 ** Otherwise, for non-temporary files, the effective sector size is
   42847 ** the value returned by the xSectorSize() method rounded up to 32 if
   42848 ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
   42849 ** is greater than MAX_SECTOR_SIZE.
   42850 **
   42851 ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
   42852 ** the effective sector size to its minimum value (512).  The purpose of
   42853 ** pPager->sectorSize is to define the "blast radius" of bytes that
   42854 ** might change if a crash occurs while writing to a single byte in
   42855 ** that range.  But with POWERSAFE_OVERWRITE, the blast radius is zero
   42856 ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
   42857 ** size.  For backwards compatibility of the rollback journal file format,
   42858 ** we cannot reduce the effective sector size below 512.
   42859 */
   42860 static void setSectorSize(Pager *pPager){
   42861   assert( isOpen(pPager->fd) || pPager->tempFile );
   42862 
   42863   if( pPager->tempFile
   42864    || (sqlite3OsDeviceCharacteristics(pPager->fd) &
   42865               SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
   42866   ){
   42867     /* Sector size doesn't matter for temporary files. Also, the file
   42868     ** may not have been opened yet, in which case the OsSectorSize()
   42869     ** call will segfault. */
   42870     pPager->sectorSize = 512;
   42871   }else{
   42872     pPager->sectorSize = sqlite3SectorSize(pPager->fd);
   42873   }
   42874 }
   42875 
   42876 /*
   42877 ** Playback the journal and thus restore the database file to
   42878 ** the state it was in before we started making changes.
   42879 **
   42880 ** The journal file format is as follows:
   42881 **
   42882 **  (1)  8 byte prefix.  A copy of aJournalMagic[].
   42883 **  (2)  4 byte big-endian integer which is the number of valid page records
   42884 **       in the journal.  If this value is 0xffffffff, then compute the
   42885 **       number of page records from the journal size.
   42886 **  (3)  4 byte big-endian integer which is the initial value for the
   42887 **       sanity checksum.
   42888 **  (4)  4 byte integer which is the number of pages to truncate the
   42889 **       database to during a rollback.
   42890 **  (5)  4 byte big-endian integer which is the sector size.  The header
   42891 **       is this many bytes in size.
   42892 **  (6)  4 byte big-endian integer which is the page size.
   42893 **  (7)  zero padding out to the next sector size.
   42894 **  (8)  Zero or more pages instances, each as follows:
   42895 **        +  4 byte page number.
   42896 **        +  pPager->pageSize bytes of data.
   42897 **        +  4 byte checksum
   42898 **
   42899 ** When we speak of the journal header, we mean the first 7 items above.
   42900 ** Each entry in the journal is an instance of the 8th item.
   42901 **
   42902 ** Call the value from the second bullet "nRec".  nRec is the number of
   42903 ** valid page entries in the journal.  In most cases, you can compute the
   42904 ** value of nRec from the size of the journal file.  But if a power
   42905 ** failure occurred while the journal was being written, it could be the
   42906 ** case that the size of the journal file had already been increased but
   42907 ** the extra entries had not yet made it safely to disk.  In such a case,
   42908 ** the value of nRec computed from the file size would be too large.  For
   42909 ** that reason, we always use the nRec value in the header.
   42910 **
   42911 ** If the nRec value is 0xffffffff it means that nRec should be computed
   42912 ** from the file size.  This value is used when the user selects the
   42913 ** no-sync option for the journal.  A power failure could lead to corruption
   42914 ** in this case.  But for things like temporary table (which will be
   42915 ** deleted when the power is restored) we don't care.
   42916 **
   42917 ** If the file opened as the journal file is not a well-formed
   42918 ** journal file then all pages up to the first corrupted page are rolled
   42919 ** back (or no pages if the journal header is corrupted). The journal file
   42920 ** is then deleted and SQLITE_OK returned, just as if no corruption had
   42921 ** been encountered.
   42922 **
   42923 ** If an I/O or malloc() error occurs, the journal-file is not deleted
   42924 ** and an error code is returned.
   42925 **
   42926 ** The isHot parameter indicates that we are trying to rollback a journal
   42927 ** that might be a hot journal.  Or, it could be that the journal is
   42928 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
   42929 ** If the journal really is hot, reset the pager cache prior rolling
   42930 ** back any content.  If the journal is merely persistent, no reset is
   42931 ** needed.
   42932 */
   42933 static int pager_playback(Pager *pPager, int isHot){
   42934   sqlite3_vfs *pVfs = pPager->pVfs;
   42935   i64 szJ;                 /* Size of the journal file in bytes */
   42936   u32 nRec;                /* Number of Records in the journal */
   42937   u32 u;                   /* Unsigned loop counter */
   42938   Pgno mxPg = 0;           /* Size of the original file in pages */
   42939   int rc;                  /* Result code of a subroutine */
   42940   int res = 1;             /* Value returned by sqlite3OsAccess() */
   42941   char *zMaster = 0;       /* Name of master journal file if any */
   42942   int needPagerReset;      /* True to reset page prior to first page rollback */
   42943   int nPlayback = 0;       /* Total number of pages restored from journal */
   42944 
   42945   /* Figure out how many records are in the journal.  Abort early if
   42946   ** the journal is empty.
   42947   */
   42948   assert( isOpen(pPager->jfd) );
   42949   rc = sqlite3OsFileSize(pPager->jfd, &szJ);
   42950   if( rc!=SQLITE_OK ){
   42951     goto end_playback;
   42952   }
   42953 
   42954   /* Read the master journal name from the journal, if it is present.
   42955   ** If a master journal file name is specified, but the file is not
   42956   ** present on disk, then the journal is not hot and does not need to be
   42957   ** played back.
   42958   **
   42959   ** TODO: Technically the following is an error because it assumes that
   42960   ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
   42961   ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
   42962   **  mxPathname is 512, which is the same as the minimum allowable value
   42963   ** for pageSize.
   42964   */
   42965   zMaster = pPager->pTmpSpace;
   42966   rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
   42967   if( rc==SQLITE_OK && zMaster[0] ){
   42968     rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
   42969   }
   42970   zMaster = 0;
   42971   if( rc!=SQLITE_OK || !res ){
   42972     goto end_playback;
   42973   }
   42974   pPager->journalOff = 0;
   42975   needPagerReset = isHot;
   42976 
   42977   /* This loop terminates either when a readJournalHdr() or
   42978   ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
   42979   ** occurs.
   42980   */
   42981   while( 1 ){
   42982     /* Read the next journal header from the journal file.  If there are
   42983     ** not enough bytes left in the journal file for a complete header, or
   42984     ** it is corrupted, then a process must have failed while writing it.
   42985     ** This indicates nothing more needs to be rolled back.
   42986     */
   42987     rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
   42988     if( rc!=SQLITE_OK ){
   42989       if( rc==SQLITE_DONE ){
   42990         rc = SQLITE_OK;
   42991       }
   42992       goto end_playback;
   42993     }
   42994 
   42995     /* If nRec is 0xffffffff, then this journal was created by a process
   42996     ** working in no-sync mode. This means that the rest of the journal
   42997     ** file consists of pages, there are no more journal headers. Compute
   42998     ** the value of nRec based on this assumption.
   42999     */
   43000     if( nRec==0xffffffff ){
   43001       assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
   43002       nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
   43003     }
   43004 
   43005     /* If nRec is 0 and this rollback is of a transaction created by this
   43006     ** process and if this is the final header in the journal, then it means
   43007     ** that this part of the journal was being filled but has not yet been
   43008     ** synced to disk.  Compute the number of pages based on the remaining
   43009     ** size of the file.
   43010     **
   43011     ** The third term of the test was added to fix ticket #2565.
   43012     ** When rolling back a hot journal, nRec==0 always means that the next
   43013     ** chunk of the journal contains zero pages to be rolled back.  But
   43014     ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
   43015     ** the journal, it means that the journal might contain additional
   43016     ** pages that need to be rolled back and that the number of pages
   43017     ** should be computed based on the journal file size.
   43018     */
   43019     if( nRec==0 && !isHot &&
   43020         pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
   43021       nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
   43022     }
   43023 
   43024     /* If this is the first header read from the journal, truncate the
   43025     ** database file back to its original size.
   43026     */
   43027     if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
   43028       rc = pager_truncate(pPager, mxPg);
   43029       if( rc!=SQLITE_OK ){
   43030         goto end_playback;
   43031       }
   43032       pPager->dbSize = mxPg;
   43033     }
   43034 
   43035     /* Copy original pages out of the journal and back into the
   43036     ** database file and/or page cache.
   43037     */
   43038     for(u=0; u<nRec; u++){
   43039       if( needPagerReset ){
   43040         pager_reset(pPager);
   43041         needPagerReset = 0;
   43042       }
   43043       rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
   43044       if( rc==SQLITE_OK ){
   43045         nPlayback++;
   43046       }else{
   43047         if( rc==SQLITE_DONE ){
   43048           pPager->journalOff = szJ;
   43049           break;
   43050         }else if( rc==SQLITE_IOERR_SHORT_READ ){
   43051           /* If the journal has been truncated, simply stop reading and
   43052           ** processing the journal. This might happen if the journal was
   43053           ** not completely written and synced prior to a crash.  In that
   43054           ** case, the database should have never been written in the
   43055           ** first place so it is OK to simply abandon the rollback. */
   43056           rc = SQLITE_OK;
   43057           goto end_playback;
   43058         }else{
   43059           /* If we are unable to rollback, quit and return the error
   43060           ** code.  This will cause the pager to enter the error state
   43061           ** so that no further harm will be done.  Perhaps the next
   43062           ** process to come along will be able to rollback the database.
   43063           */
   43064           goto end_playback;
   43065         }
   43066       }
   43067     }
   43068   }
   43069   /*NOTREACHED*/
   43070   assert( 0 );
   43071 
   43072 end_playback:
   43073   /* Following a rollback, the database file should be back in its original
   43074   ** state prior to the start of the transaction, so invoke the
   43075   ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
   43076   ** assertion that the transaction counter was modified.
   43077   */
   43078 #ifdef SQLITE_DEBUG
   43079   if( pPager->fd->pMethods ){
   43080     sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
   43081   }
   43082 #endif
   43083 
   43084   /* If this playback is happening automatically as a result of an IO or
   43085   ** malloc error that occurred after the change-counter was updated but
   43086   ** before the transaction was committed, then the change-counter
   43087   ** modification may just have been reverted. If this happens in exclusive
   43088   ** mode, then subsequent transactions performed by the connection will not
   43089   ** update the change-counter at all. This may lead to cache inconsistency
   43090   ** problems for other processes at some point in the future. So, just
   43091   ** in case this has happened, clear the changeCountDone flag now.
   43092   */
   43093   pPager->changeCountDone = pPager->tempFile;
   43094 
   43095   if( rc==SQLITE_OK ){
   43096     zMaster = pPager->pTmpSpace;
   43097     rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
   43098     testcase( rc!=SQLITE_OK );
   43099   }
   43100   if( rc==SQLITE_OK
   43101    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
   43102   ){
   43103     rc = sqlite3PagerSync(pPager, 0);
   43104   }
   43105   if( rc==SQLITE_OK ){
   43106     rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
   43107     testcase( rc!=SQLITE_OK );
   43108   }
   43109   if( rc==SQLITE_OK && zMaster[0] && res ){
   43110     /* If there was a master journal and this routine will return success,
   43111     ** see if it is possible to delete the master journal.
   43112     */
   43113     rc = pager_delmaster(pPager, zMaster);
   43114     testcase( rc!=SQLITE_OK );
   43115   }
   43116   if( isHot && nPlayback ){
   43117     sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
   43118                 nPlayback, pPager->zJournal);
   43119   }
   43120 
   43121   /* The Pager.sectorSize variable may have been updated while rolling
   43122   ** back a journal created by a process with a different sector size
   43123   ** value. Reset it to the correct value for this process.
   43124   */
   43125   setSectorSize(pPager);
   43126   return rc;
   43127 }
   43128 
   43129 
   43130 /*
   43131 ** Read the content for page pPg out of the database file and into
   43132 ** pPg->pData. A shared lock or greater must be held on the database
   43133 ** file before this function is called.
   43134 **
   43135 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
   43136 ** the value read from the database file.
   43137 **
   43138 ** If an IO error occurs, then the IO error is returned to the caller.
   43139 ** Otherwise, SQLITE_OK is returned.
   43140 */
   43141 static int readDbPage(PgHdr *pPg, u32 iFrame){
   43142   Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
   43143   Pgno pgno = pPg->pgno;       /* Page number to read */
   43144   int rc = SQLITE_OK;          /* Return code */
   43145   int pgsz = pPager->pageSize; /* Number of bytes to read */
   43146 
   43147   assert( pPager->eState>=PAGER_READER && !MEMDB );
   43148   assert( isOpen(pPager->fd) );
   43149 
   43150 #ifndef SQLITE_OMIT_WAL
   43151   if( iFrame ){
   43152     /* Try to pull the page from the write-ahead log. */
   43153     rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData);
   43154   }else
   43155 #endif
   43156   {
   43157     i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
   43158     rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
   43159     if( rc==SQLITE_IOERR_SHORT_READ ){
   43160       rc = SQLITE_OK;
   43161     }
   43162   }
   43163 
   43164   if( pgno==1 ){
   43165     if( rc ){
   43166       /* If the read is unsuccessful, set the dbFileVers[] to something
   43167       ** that will never be a valid file version.  dbFileVers[] is a copy
   43168       ** of bytes 24..39 of the database.  Bytes 28..31 should always be
   43169       ** zero or the size of the database in page. Bytes 32..35 and 35..39
   43170       ** should be page numbers which are never 0xffffffff.  So filling
   43171       ** pPager->dbFileVers[] with all 0xff bytes should suffice.
   43172       **
   43173       ** For an encrypted database, the situation is more complex:  bytes
   43174       ** 24..39 of the database are white noise.  But the probability of
   43175       ** white noising equaling 16 bytes of 0xff is vanishingly small so
   43176       ** we should still be ok.
   43177       */
   43178       memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
   43179     }else{
   43180       u8 *dbFileVers = &((u8*)pPg->pData)[24];
   43181       memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
   43182     }
   43183   }
   43184   CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
   43185 
   43186   PAGER_INCR(sqlite3_pager_readdb_count);
   43187   PAGER_INCR(pPager->nRead);
   43188   IOTRACE(("PGIN %p %d\n", pPager, pgno));
   43189   PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
   43190                PAGERID(pPager), pgno, pager_pagehash(pPg)));
   43191 
   43192   return rc;
   43193 }
   43194 
   43195 /*
   43196 ** Update the value of the change-counter at offsets 24 and 92 in
   43197 ** the header and the sqlite version number at offset 96.
   43198 **
   43199 ** This is an unconditional update.  See also the pager_incr_changecounter()
   43200 ** routine which only updates the change-counter if the update is actually
   43201 ** needed, as determined by the pPager->changeCountDone state variable.
   43202 */
   43203 static void pager_write_changecounter(PgHdr *pPg){
   43204   u32 change_counter;
   43205 
   43206   /* Increment the value just read and write it back to byte 24. */
   43207   change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
   43208   put32bits(((char*)pPg->pData)+24, change_counter);
   43209 
   43210   /* Also store the SQLite version number in bytes 96..99 and in
   43211   ** bytes 92..95 store the change counter for which the version number
   43212   ** is valid. */
   43213   put32bits(((char*)pPg->pData)+92, change_counter);
   43214   put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
   43215 }
   43216 
   43217 #ifndef SQLITE_OMIT_WAL
   43218 /*
   43219 ** This function is invoked once for each page that has already been
   43220 ** written into the log file when a WAL transaction is rolled back.
   43221 ** Parameter iPg is the page number of said page. The pCtx argument
   43222 ** is actually a pointer to the Pager structure.
   43223 **
   43224 ** If page iPg is present in the cache, and has no outstanding references,
   43225 ** it is discarded. Otherwise, if there are one or more outstanding
   43226 ** references, the page content is reloaded from the database. If the
   43227 ** attempt to reload content from the database is required and fails,
   43228 ** return an SQLite error code. Otherwise, SQLITE_OK.
   43229 */
   43230 static int pagerUndoCallback(void *pCtx, Pgno iPg){
   43231   int rc = SQLITE_OK;
   43232   Pager *pPager = (Pager *)pCtx;
   43233   PgHdr *pPg;
   43234 
   43235   assert( pagerUseWal(pPager) );
   43236   pPg = sqlite3PagerLookup(pPager, iPg);
   43237   if( pPg ){
   43238     if( sqlite3PcachePageRefcount(pPg)==1 ){
   43239       sqlite3PcacheDrop(pPg);
   43240     }else{
   43241       u32 iFrame = 0;
   43242       rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
   43243       if( rc==SQLITE_OK ){
   43244         rc = readDbPage(pPg, iFrame);
   43245       }
   43246       if( rc==SQLITE_OK ){
   43247         pPager->xReiniter(pPg);
   43248       }
   43249       sqlite3PagerUnrefNotNull(pPg);
   43250     }
   43251   }
   43252 
   43253   /* Normally, if a transaction is rolled back, any backup processes are
   43254   ** updated as data is copied out of the rollback journal and into the
   43255   ** database. This is not generally possible with a WAL database, as
   43256   ** rollback involves simply truncating the log file. Therefore, if one
   43257   ** or more frames have already been written to the log (and therefore
   43258   ** also copied into the backup databases) as part of this transaction,
   43259   ** the backups must be restarted.
   43260   */
   43261   sqlite3BackupRestart(pPager->pBackup);
   43262 
   43263   return rc;
   43264 }
   43265 
   43266 /*
   43267 ** This function is called to rollback a transaction on a WAL database.
   43268 */
   43269 static int pagerRollbackWal(Pager *pPager){
   43270   int rc;                         /* Return Code */
   43271   PgHdr *pList;                   /* List of dirty pages to revert */
   43272 
   43273   /* For all pages in the cache that are currently dirty or have already
   43274   ** been written (but not committed) to the log file, do one of the
   43275   ** following:
   43276   **
   43277   **   + Discard the cached page (if refcount==0), or
   43278   **   + Reload page content from the database (if refcount>0).
   43279   */
   43280   pPager->dbSize = pPager->dbOrigSize;
   43281   rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
   43282   pList = sqlite3PcacheDirtyList(pPager->pPCache);
   43283   while( pList && rc==SQLITE_OK ){
   43284     PgHdr *pNext = pList->pDirty;
   43285     rc = pagerUndoCallback((void *)pPager, pList->pgno);
   43286     pList = pNext;
   43287   }
   43288 
   43289   return rc;
   43290 }
   43291 
   43292 /*
   43293 ** This function is a wrapper around sqlite3WalFrames(). As well as logging
   43294 ** the contents of the list of pages headed by pList (connected by pDirty),
   43295 ** this function notifies any active backup processes that the pages have
   43296 ** changed.
   43297 **
   43298 ** The list of pages passed into this routine is always sorted by page number.
   43299 ** Hence, if page 1 appears anywhere on the list, it will be the first page.
   43300 */
   43301 static int pagerWalFrames(
   43302   Pager *pPager,                  /* Pager object */
   43303   PgHdr *pList,                   /* List of frames to log */
   43304   Pgno nTruncate,                 /* Database size after this commit */
   43305   int isCommit                    /* True if this is a commit */
   43306 ){
   43307   int rc;                         /* Return code */
   43308   int nList;                      /* Number of pages in pList */
   43309 #if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
   43310   PgHdr *p;                       /* For looping over pages */
   43311 #endif
   43312 
   43313   assert( pPager->pWal );
   43314   assert( pList );
   43315 #ifdef SQLITE_DEBUG
   43316   /* Verify that the page list is in accending order */
   43317   for(p=pList; p && p->pDirty; p=p->pDirty){
   43318     assert( p->pgno < p->pDirty->pgno );
   43319   }
   43320 #endif
   43321 
   43322   assert( pList->pDirty==0 || isCommit );
   43323   if( isCommit ){
   43324     /* If a WAL transaction is being committed, there is no point in writing
   43325     ** any pages with page numbers greater than nTruncate into the WAL file.
   43326     ** They will never be read by any client. So remove them from the pDirty
   43327     ** list here. */
   43328     PgHdr *p;
   43329     PgHdr **ppNext = &pList;
   43330     nList = 0;
   43331     for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
   43332       if( p->pgno<=nTruncate ){
   43333         ppNext = &p->pDirty;
   43334         nList++;
   43335       }
   43336     }
   43337     assert( pList );
   43338   }else{
   43339     nList = 1;
   43340   }
   43341   pPager->aStat[PAGER_STAT_WRITE] += nList;
   43342 
   43343   if( pList->pgno==1 ) pager_write_changecounter(pList);
   43344   rc = sqlite3WalFrames(pPager->pWal,
   43345       pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
   43346   );
   43347   if( rc==SQLITE_OK && pPager->pBackup ){
   43348     PgHdr *p;
   43349     for(p=pList; p; p=p->pDirty){
   43350       sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
   43351     }
   43352   }
   43353 
   43354 #ifdef SQLITE_CHECK_PAGES
   43355   pList = sqlite3PcacheDirtyList(pPager->pPCache);
   43356   for(p=pList; p; p=p->pDirty){
   43357     pager_set_pagehash(p);
   43358   }
   43359 #endif
   43360 
   43361   return rc;
   43362 }
   43363 
   43364 /*
   43365 ** Begin a read transaction on the WAL.
   43366 **
   43367 ** This routine used to be called "pagerOpenSnapshot()" because it essentially
   43368 ** makes a snapshot of the database at the current point in time and preserves
   43369 ** that snapshot for use by the reader in spite of concurrently changes by
   43370 ** other writers or checkpointers.
   43371 */
   43372 static int pagerBeginReadTransaction(Pager *pPager){
   43373   int rc;                         /* Return code */
   43374   int changed = 0;                /* True if cache must be reset */
   43375 
   43376   assert( pagerUseWal(pPager) );
   43377   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
   43378 
   43379   /* sqlite3WalEndReadTransaction() was not called for the previous
   43380   ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
   43381   ** are in locking_mode=NORMAL and EndRead() was previously called,
   43382   ** the duplicate call is harmless.
   43383   */
   43384   sqlite3WalEndReadTransaction(pPager->pWal);
   43385 
   43386   rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
   43387   if( rc!=SQLITE_OK || changed ){
   43388     pager_reset(pPager);
   43389     if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
   43390   }
   43391 
   43392   return rc;
   43393 }
   43394 #endif
   43395 
   43396 /*
   43397 ** This function is called as part of the transition from PAGER_OPEN
   43398 ** to PAGER_READER state to determine the size of the database file
   43399 ** in pages (assuming the page size currently stored in Pager.pageSize).
   43400 **
   43401 ** If no error occurs, SQLITE_OK is returned and the size of the database
   43402 ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
   43403 ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
   43404 */
   43405 static int pagerPagecount(Pager *pPager, Pgno *pnPage){
   43406   Pgno nPage;                     /* Value to return via *pnPage */
   43407 
   43408   /* Query the WAL sub-system for the database size. The WalDbsize()
   43409   ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
   43410   ** if the database size is not available. The database size is not
   43411   ** available from the WAL sub-system if the log file is empty or
   43412   ** contains no valid committed transactions.
   43413   */
   43414   assert( pPager->eState==PAGER_OPEN );
   43415   assert( pPager->eLock>=SHARED_LOCK );
   43416   nPage = sqlite3WalDbsize(pPager->pWal);
   43417 
   43418   /* If the database size was not available from the WAL sub-system,
   43419   ** determine it based on the size of the database file. If the size
   43420   ** of the database file is not an integer multiple of the page-size,
   43421   ** round down to the nearest page. Except, any file larger than 0
   43422   ** bytes in size is considered to contain at least one page.
   43423   */
   43424   if( nPage==0 ){
   43425     i64 n = 0;                    /* Size of db file in bytes */
   43426     assert( isOpen(pPager->fd) || pPager->tempFile );
   43427     if( isOpen(pPager->fd) ){
   43428       int rc = sqlite3OsFileSize(pPager->fd, &n);
   43429       if( rc!=SQLITE_OK ){
   43430         return rc;
   43431       }
   43432     }
   43433     nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
   43434   }
   43435 
   43436   /* If the current number of pages in the file is greater than the
   43437   ** configured maximum pager number, increase the allowed limit so
   43438   ** that the file can be read.
   43439   */
   43440   if( nPage>pPager->mxPgno ){
   43441     pPager->mxPgno = (Pgno)nPage;
   43442   }
   43443 
   43444   *pnPage = nPage;
   43445   return SQLITE_OK;
   43446 }
   43447 
   43448 #ifndef SQLITE_OMIT_WAL
   43449 /*
   43450 ** Check if the *-wal file that corresponds to the database opened by pPager
   43451 ** exists if the database is not empy, or verify that the *-wal file does
   43452 ** not exist (by deleting it) if the database file is empty.
   43453 **
   43454 ** If the database is not empty and the *-wal file exists, open the pager
   43455 ** in WAL mode.  If the database is empty or if no *-wal file exists and
   43456 ** if no error occurs, make sure Pager.journalMode is not set to
   43457 ** PAGER_JOURNALMODE_WAL.
   43458 **
   43459 ** Return SQLITE_OK or an error code.
   43460 **
   43461 ** The caller must hold a SHARED lock on the database file to call this
   43462 ** function. Because an EXCLUSIVE lock on the db file is required to delete
   43463 ** a WAL on a none-empty database, this ensures there is no race condition
   43464 ** between the xAccess() below and an xDelete() being executed by some
   43465 ** other connection.
   43466 */
   43467 static int pagerOpenWalIfPresent(Pager *pPager){
   43468   int rc = SQLITE_OK;
   43469   assert( pPager->eState==PAGER_OPEN );
   43470   assert( pPager->eLock>=SHARED_LOCK );
   43471 
   43472   if( !pPager->tempFile ){
   43473     int isWal;                    /* True if WAL file exists */
   43474     Pgno nPage;                   /* Size of the database file */
   43475 
   43476     rc = pagerPagecount(pPager, &nPage);
   43477     if( rc ) return rc;
   43478     if( nPage==0 ){
   43479       rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
   43480       if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
   43481       isWal = 0;
   43482     }else{
   43483       rc = sqlite3OsAccess(
   43484           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
   43485       );
   43486     }
   43487     if( rc==SQLITE_OK ){
   43488       if( isWal ){
   43489         testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
   43490         rc = sqlite3PagerOpenWal(pPager, 0);
   43491       }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
   43492         pPager->journalMode = PAGER_JOURNALMODE_DELETE;
   43493       }
   43494     }
   43495   }
   43496   return rc;
   43497 }
   43498 #endif
   43499 
   43500 /*
   43501 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
   43502 ** the entire master journal file. The case pSavepoint==NULL occurs when
   43503 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
   43504 ** savepoint.
   43505 **
   43506 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
   43507 ** being rolled back), then the rollback consists of up to three stages,
   43508 ** performed in the order specified:
   43509 **
   43510 **   * Pages are played back from the main journal starting at byte
   43511 **     offset PagerSavepoint.iOffset and continuing to
   43512 **     PagerSavepoint.iHdrOffset, or to the end of the main journal
   43513 **     file if PagerSavepoint.iHdrOffset is zero.
   43514 **
   43515 **   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
   43516 **     back starting from the journal header immediately following
   43517 **     PagerSavepoint.iHdrOffset to the end of the main journal file.
   43518 **
   43519 **   * Pages are then played back from the sub-journal file, starting
   43520 **     with the PagerSavepoint.iSubRec and continuing to the end of
   43521 **     the journal file.
   43522 **
   43523 ** Throughout the rollback process, each time a page is rolled back, the
   43524 ** corresponding bit is set in a bitvec structure (variable pDone in the
   43525 ** implementation below). This is used to ensure that a page is only
   43526 ** rolled back the first time it is encountered in either journal.
   43527 **
   43528 ** If pSavepoint is NULL, then pages are only played back from the main
   43529 ** journal file. There is no need for a bitvec in this case.
   43530 **
   43531 ** In either case, before playback commences the Pager.dbSize variable
   43532 ** is reset to the value that it held at the start of the savepoint
   43533 ** (or transaction). No page with a page-number greater than this value
   43534 ** is played back. If one is encountered it is simply skipped.
   43535 */
   43536 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
   43537   i64 szJ;                 /* Effective size of the main journal */
   43538   i64 iHdrOff;             /* End of first segment of main-journal records */
   43539   int rc = SQLITE_OK;      /* Return code */
   43540   Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
   43541 
   43542   assert( pPager->eState!=PAGER_ERROR );
   43543   assert( pPager->eState>=PAGER_WRITER_LOCKED );
   43544 
   43545   /* Allocate a bitvec to use to store the set of pages rolled back */
   43546   if( pSavepoint ){
   43547     pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
   43548     if( !pDone ){
   43549       return SQLITE_NOMEM;
   43550     }
   43551   }
   43552 
   43553   /* Set the database size back to the value it was before the savepoint
   43554   ** being reverted was opened.
   43555   */
   43556   pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
   43557   pPager->changeCountDone = pPager->tempFile;
   43558 
   43559   if( !pSavepoint && pagerUseWal(pPager) ){
   43560     return pagerRollbackWal(pPager);
   43561   }
   43562 
   43563   /* Use pPager->journalOff as the effective size of the main rollback
   43564   ** journal.  The actual file might be larger than this in
   43565   ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
   43566   ** past pPager->journalOff is off-limits to us.
   43567   */
   43568   szJ = pPager->journalOff;
   43569   assert( pagerUseWal(pPager)==0 || szJ==0 );
   43570 
   43571   /* Begin by rolling back records from the main journal starting at
   43572   ** PagerSavepoint.iOffset and continuing to the next journal header.
   43573   ** There might be records in the main journal that have a page number
   43574   ** greater than the current database size (pPager->dbSize) but those
   43575   ** will be skipped automatically.  Pages are added to pDone as they
   43576   ** are played back.
   43577   */
   43578   if( pSavepoint && !pagerUseWal(pPager) ){
   43579     iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
   43580     pPager->journalOff = pSavepoint->iOffset;
   43581     while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
   43582       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
   43583     }
   43584     assert( rc!=SQLITE_DONE );
   43585   }else{
   43586     pPager->journalOff = 0;
   43587   }
   43588 
   43589   /* Continue rolling back records out of the main journal starting at
   43590   ** the first journal header seen and continuing until the effective end
   43591   ** of the main journal file.  Continue to skip out-of-range pages and
   43592   ** continue adding pages rolled back to pDone.
   43593   */
   43594   while( rc==SQLITE_OK && pPager->journalOff<szJ ){
   43595     u32 ii;            /* Loop counter */
   43596     u32 nJRec = 0;     /* Number of Journal Records */
   43597     u32 dummy;
   43598     rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
   43599     assert( rc!=SQLITE_DONE );
   43600 
   43601     /*
   43602     ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
   43603     ** test is related to ticket #2565.  See the discussion in the
   43604     ** pager_playback() function for additional information.
   43605     */
   43606     if( nJRec==0
   43607      && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
   43608     ){
   43609       nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
   43610     }
   43611     for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
   43612       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
   43613     }
   43614     assert( rc!=SQLITE_DONE );
   43615   }
   43616   assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
   43617 
   43618   /* Finally,  rollback pages from the sub-journal.  Page that were
   43619   ** previously rolled back out of the main journal (and are hence in pDone)
   43620   ** will be skipped.  Out-of-range pages are also skipped.
   43621   */
   43622   if( pSavepoint ){
   43623     u32 ii;            /* Loop counter */
   43624     i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
   43625 
   43626     if( pagerUseWal(pPager) ){
   43627       rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
   43628     }
   43629     for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
   43630       assert( offset==(i64)ii*(4+pPager->pageSize) );
   43631       rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
   43632     }
   43633     assert( rc!=SQLITE_DONE );
   43634   }
   43635 
   43636   sqlite3BitvecDestroy(pDone);
   43637   if( rc==SQLITE_OK ){
   43638     pPager->journalOff = szJ;
   43639   }
   43640 
   43641   return rc;
   43642 }
   43643 
   43644 /*
   43645 ** Change the maximum number of in-memory pages that are allowed.
   43646 */
   43647 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
   43648   sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
   43649 }
   43650 
   43651 /*
   43652 ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
   43653 */
   43654 static void pagerFixMaplimit(Pager *pPager){
   43655 #if SQLITE_MAX_MMAP_SIZE>0
   43656   sqlite3_file *fd = pPager->fd;
   43657   if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
   43658     sqlite3_int64 sz;
   43659     sz = pPager->szMmap;
   43660     pPager->bUseFetch = (sz>0);
   43661     sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
   43662   }
   43663 #endif
   43664 }
   43665 
   43666 /*
   43667 ** Change the maximum size of any memory mapping made of the database file.
   43668 */
   43669 SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
   43670   pPager->szMmap = szMmap;
   43671   pagerFixMaplimit(pPager);
   43672 }
   43673 
   43674 /*
   43675 ** Free as much memory as possible from the pager.
   43676 */
   43677 SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
   43678   sqlite3PcacheShrink(pPager->pPCache);
   43679 }
   43680 
   43681 /*
   43682 ** Adjust settings of the pager to those specified in the pgFlags parameter.
   43683 **
   43684 ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
   43685 ** of the database to damage due to OS crashes or power failures by
   43686 ** changing the number of syncs()s when writing the journals.
   43687 ** There are three levels:
   43688 **
   43689 **    OFF       sqlite3OsSync() is never called.  This is the default
   43690 **              for temporary and transient files.
   43691 **
   43692 **    NORMAL    The journal is synced once before writes begin on the
   43693 **              database.  This is normally adequate protection, but
   43694 **              it is theoretically possible, though very unlikely,
   43695 **              that an inopertune power failure could leave the journal
   43696 **              in a state which would cause damage to the database
   43697 **              when it is rolled back.
   43698 **
   43699 **    FULL      The journal is synced twice before writes begin on the
   43700 **              database (with some additional information - the nRec field
   43701 **              of the journal header - being written in between the two
   43702 **              syncs).  If we assume that writing a
   43703 **              single disk sector is atomic, then this mode provides
   43704 **              assurance that the journal will not be corrupted to the
   43705 **              point of causing damage to the database during rollback.
   43706 **
   43707 ** The above is for a rollback-journal mode.  For WAL mode, OFF continues
   43708 ** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
   43709 ** prior to the start of checkpoint and that the database file is synced
   43710 ** at the conclusion of the checkpoint if the entire content of the WAL
   43711 ** was written back into the database.  But no sync operations occur for
   43712 ** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
   43713 ** file is synced following each commit operation, in addition to the
   43714 ** syncs associated with NORMAL.
   43715 **
   43716 ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The
   43717 ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
   43718 ** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an
   43719 ** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL
   43720 ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the
   43721 ** synchronous=FULL versus synchronous=NORMAL setting determines when
   43722 ** the xSync primitive is called and is relevant to all platforms.
   43723 **
   43724 ** Numeric values associated with these states are OFF==1, NORMAL=2,
   43725 ** and FULL=3.
   43726 */
   43727 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   43728 SQLITE_PRIVATE void sqlite3PagerSetFlags(
   43729   Pager *pPager,        /* The pager to set safety level for */
   43730   unsigned pgFlags      /* Various flags */
   43731 ){
   43732   unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
   43733   assert( level>=1 && level<=3 );
   43734   pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
   43735   pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
   43736   if( pPager->noSync ){
   43737     pPager->syncFlags = 0;
   43738     pPager->ckptSyncFlags = 0;
   43739   }else if( pgFlags & PAGER_FULLFSYNC ){
   43740     pPager->syncFlags = SQLITE_SYNC_FULL;
   43741     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
   43742   }else if( pgFlags & PAGER_CKPT_FULLFSYNC ){
   43743     pPager->syncFlags = SQLITE_SYNC_NORMAL;
   43744     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
   43745   }else{
   43746     pPager->syncFlags = SQLITE_SYNC_NORMAL;
   43747     pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
   43748   }
   43749   pPager->walSyncFlags = pPager->syncFlags;
   43750   if( pPager->fullSync ){
   43751     pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
   43752   }
   43753   if( pgFlags & PAGER_CACHESPILL ){
   43754     pPager->doNotSpill &= ~SPILLFLAG_OFF;
   43755   }else{
   43756     pPager->doNotSpill |= SPILLFLAG_OFF;
   43757   }
   43758 }
   43759 #endif
   43760 
   43761 /*
   43762 ** The following global variable is incremented whenever the library
   43763 ** attempts to open a temporary file.  This information is used for
   43764 ** testing and analysis only.
   43765 */
   43766 #ifdef SQLITE_TEST
   43767 SQLITE_API int sqlite3_opentemp_count = 0;
   43768 #endif
   43769 
   43770 /*
   43771 ** Open a temporary file.
   43772 **
   43773 ** Write the file descriptor into *pFile. Return SQLITE_OK on success
   43774 ** or some other error code if we fail. The OS will automatically
   43775 ** delete the temporary file when it is closed.
   43776 **
   43777 ** The flags passed to the VFS layer xOpen() call are those specified
   43778 ** by parameter vfsFlags ORed with the following:
   43779 **
   43780 **     SQLITE_OPEN_READWRITE
   43781 **     SQLITE_OPEN_CREATE
   43782 **     SQLITE_OPEN_EXCLUSIVE
   43783 **     SQLITE_OPEN_DELETEONCLOSE
   43784 */
   43785 static int pagerOpentemp(
   43786   Pager *pPager,        /* The pager object */
   43787   sqlite3_file *pFile,  /* Write the file descriptor here */
   43788   int vfsFlags          /* Flags passed through to the VFS */
   43789 ){
   43790   int rc;               /* Return code */
   43791 
   43792 #ifdef SQLITE_TEST
   43793   sqlite3_opentemp_count++;  /* Used for testing and analysis only */
   43794 #endif
   43795 
   43796   vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
   43797             SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
   43798   rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
   43799   assert( rc!=SQLITE_OK || isOpen(pFile) );
   43800   return rc;
   43801 }
   43802 
   43803 /*
   43804 ** Set the busy handler function.
   43805 **
   43806 ** The pager invokes the busy-handler if sqlite3OsLock() returns
   43807 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
   43808 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
   43809 ** lock. It does *not* invoke the busy handler when upgrading from
   43810 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
   43811 ** (which occurs during hot-journal rollback). Summary:
   43812 **
   43813 **   Transition                        | Invokes xBusyHandler
   43814 **   --------------------------------------------------------
   43815 **   NO_LOCK       -> SHARED_LOCK      | Yes
   43816 **   SHARED_LOCK   -> RESERVED_LOCK    | No
   43817 **   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
   43818 **   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
   43819 **
   43820 ** If the busy-handler callback returns non-zero, the lock is
   43821 ** retried. If it returns zero, then the SQLITE_BUSY error is
   43822 ** returned to the caller of the pager API function.
   43823 */
   43824 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
   43825   Pager *pPager,                       /* Pager object */
   43826   int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
   43827   void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
   43828 ){
   43829   pPager->xBusyHandler = xBusyHandler;
   43830   pPager->pBusyHandlerArg = pBusyHandlerArg;
   43831 
   43832   if( isOpen(pPager->fd) ){
   43833     void **ap = (void **)&pPager->xBusyHandler;
   43834     assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
   43835     assert( ap[1]==pBusyHandlerArg );
   43836     sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
   43837   }
   43838 }
   43839 
   43840 /*
   43841 ** Change the page size used by the Pager object. The new page size
   43842 ** is passed in *pPageSize.
   43843 **
   43844 ** If the pager is in the error state when this function is called, it
   43845 ** is a no-op. The value returned is the error state error code (i.e.
   43846 ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
   43847 **
   43848 ** Otherwise, if all of the following are true:
   43849 **
   43850 **   * the new page size (value of *pPageSize) is valid (a power
   43851 **     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
   43852 **
   43853 **   * there are no outstanding page references, and
   43854 **
   43855 **   * the database is either not an in-memory database or it is
   43856 **     an in-memory database that currently consists of zero pages.
   43857 **
   43858 ** then the pager object page size is set to *pPageSize.
   43859 **
   43860 ** If the page size is changed, then this function uses sqlite3PagerMalloc()
   43861 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
   43862 ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
   43863 ** In all other cases, SQLITE_OK is returned.
   43864 **
   43865 ** If the page size is not changed, either because one of the enumerated
   43866 ** conditions above is not true, the pager was in error state when this
   43867 ** function was called, or because the memory allocation attempt failed,
   43868 ** then *pPageSize is set to the old, retained page size before returning.
   43869 */
   43870 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
   43871   int rc = SQLITE_OK;
   43872 
   43873   /* It is not possible to do a full assert_pager_state() here, as this
   43874   ** function may be called from within PagerOpen(), before the state
   43875   ** of the Pager object is internally consistent.
   43876   **
   43877   ** At one point this function returned an error if the pager was in
   43878   ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
   43879   ** there is at least one outstanding page reference, this function
   43880   ** is a no-op for that case anyhow.
   43881   */
   43882 
   43883   u32 pageSize = *pPageSize;
   43884   assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
   43885   if( (pPager->memDb==0 || pPager->dbSize==0)
   43886    && sqlite3PcacheRefCount(pPager->pPCache)==0
   43887    && pageSize && pageSize!=(u32)pPager->pageSize
   43888   ){
   43889     char *pNew = NULL;             /* New temp space */
   43890     i64 nByte = 0;
   43891 
   43892     if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
   43893       rc = sqlite3OsFileSize(pPager->fd, &nByte);
   43894     }
   43895     if( rc==SQLITE_OK ){
   43896       pNew = (char *)sqlite3PageMalloc(pageSize);
   43897       if( !pNew ) rc = SQLITE_NOMEM;
   43898     }
   43899 
   43900     if( rc==SQLITE_OK ){
   43901       pager_reset(pPager);
   43902       pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
   43903       pPager->pageSize = pageSize;
   43904       sqlite3PageFree(pPager->pTmpSpace);
   43905       pPager->pTmpSpace = pNew;
   43906       sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
   43907     }
   43908   }
   43909 
   43910   *pPageSize = pPager->pageSize;
   43911   if( rc==SQLITE_OK ){
   43912     if( nReserve<0 ) nReserve = pPager->nReserve;
   43913     assert( nReserve>=0 && nReserve<1000 );
   43914     pPager->nReserve = (i16)nReserve;
   43915     pagerReportSize(pPager);
   43916     pagerFixMaplimit(pPager);
   43917   }
   43918   return rc;
   43919 }
   43920 
   43921 /*
   43922 ** Return a pointer to the "temporary page" buffer held internally
   43923 ** by the pager.  This is a buffer that is big enough to hold the
   43924 ** entire content of a database page.  This buffer is used internally
   43925 ** during rollback and will be overwritten whenever a rollback
   43926 ** occurs.  But other modules are free to use it too, as long as
   43927 ** no rollbacks are happening.
   43928 */
   43929 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
   43930   return pPager->pTmpSpace;
   43931 }
   43932 
   43933 /*
   43934 ** Attempt to set the maximum database page count if mxPage is positive.
   43935 ** Make no changes if mxPage is zero or negative.  And never reduce the
   43936 ** maximum page count below the current size of the database.
   43937 **
   43938 ** Regardless of mxPage, return the current maximum page count.
   43939 */
   43940 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
   43941   if( mxPage>0 ){
   43942     pPager->mxPgno = mxPage;
   43943   }
   43944   assert( pPager->eState!=PAGER_OPEN );      /* Called only by OP_MaxPgcnt */
   43945   assert( pPager->mxPgno>=pPager->dbSize );  /* OP_MaxPgcnt enforces this */
   43946   return pPager->mxPgno;
   43947 }
   43948 
   43949 /*
   43950 ** The following set of routines are used to disable the simulated
   43951 ** I/O error mechanism.  These routines are used to avoid simulated
   43952 ** errors in places where we do not care about errors.
   43953 **
   43954 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
   43955 ** and generate no code.
   43956 */
   43957 #ifdef SQLITE_TEST
   43958 SQLITE_API extern int sqlite3_io_error_pending;
   43959 SQLITE_API extern int sqlite3_io_error_hit;
   43960 static int saved_cnt;
   43961 void disable_simulated_io_errors(void){
   43962   saved_cnt = sqlite3_io_error_pending;
   43963   sqlite3_io_error_pending = -1;
   43964 }
   43965 void enable_simulated_io_errors(void){
   43966   sqlite3_io_error_pending = saved_cnt;
   43967 }
   43968 #else
   43969 # define disable_simulated_io_errors()
   43970 # define enable_simulated_io_errors()
   43971 #endif
   43972 
   43973 /*
   43974 ** Read the first N bytes from the beginning of the file into memory
   43975 ** that pDest points to.
   43976 **
   43977 ** If the pager was opened on a transient file (zFilename==""), or
   43978 ** opened on a file less than N bytes in size, the output buffer is
   43979 ** zeroed and SQLITE_OK returned. The rationale for this is that this
   43980 ** function is used to read database headers, and a new transient or
   43981 ** zero sized database has a header than consists entirely of zeroes.
   43982 **
   43983 ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
   43984 ** the error code is returned to the caller and the contents of the
   43985 ** output buffer undefined.
   43986 */
   43987 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
   43988   int rc = SQLITE_OK;
   43989   memset(pDest, 0, N);
   43990   assert( isOpen(pPager->fd) || pPager->tempFile );
   43991 
   43992   /* This routine is only called by btree immediately after creating
   43993   ** the Pager object.  There has not been an opportunity to transition
   43994   ** to WAL mode yet.
   43995   */
   43996   assert( !pagerUseWal(pPager) );
   43997 
   43998   if( isOpen(pPager->fd) ){
   43999     IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
   44000     rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
   44001     if( rc==SQLITE_IOERR_SHORT_READ ){
   44002       rc = SQLITE_OK;
   44003     }
   44004   }
   44005   return rc;
   44006 }
   44007 
   44008 /*
   44009 ** This function may only be called when a read-transaction is open on
   44010 ** the pager. It returns the total number of pages in the database.
   44011 **
   44012 ** However, if the file is between 1 and <page-size> bytes in size, then
   44013 ** this is considered a 1 page file.
   44014 */
   44015 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
   44016   assert( pPager->eState>=PAGER_READER );
   44017   assert( pPager->eState!=PAGER_WRITER_FINISHED );
   44018   *pnPage = (int)pPager->dbSize;
   44019 }
   44020 
   44021 
   44022 /*
   44023 ** Try to obtain a lock of type locktype on the database file. If
   44024 ** a similar or greater lock is already held, this function is a no-op
   44025 ** (returning SQLITE_OK immediately).
   44026 **
   44027 ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
   44028 ** the busy callback if the lock is currently not available. Repeat
   44029 ** until the busy callback returns false or until the attempt to
   44030 ** obtain the lock succeeds.
   44031 **
   44032 ** Return SQLITE_OK on success and an error code if we cannot obtain
   44033 ** the lock. If the lock is obtained successfully, set the Pager.state
   44034 ** variable to locktype before returning.
   44035 */
   44036 static int pager_wait_on_lock(Pager *pPager, int locktype){
   44037   int rc;                              /* Return code */
   44038 
   44039   /* Check that this is either a no-op (because the requested lock is
   44040   ** already held, or one of the transistions that the busy-handler
   44041   ** may be invoked during, according to the comment above
   44042   ** sqlite3PagerSetBusyhandler().
   44043   */
   44044   assert( (pPager->eLock>=locktype)
   44045        || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
   44046        || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
   44047   );
   44048 
   44049   do {
   44050     rc = pagerLockDb(pPager, locktype);
   44051   }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
   44052   return rc;
   44053 }
   44054 
   44055 /*
   44056 ** Function assertTruncateConstraint(pPager) checks that one of the
   44057 ** following is true for all dirty pages currently in the page-cache:
   44058 **
   44059 **   a) The page number is less than or equal to the size of the
   44060 **      current database image, in pages, OR
   44061 **
   44062 **   b) if the page content were written at this time, it would not
   44063 **      be necessary to write the current content out to the sub-journal
   44064 **      (as determined by function subjRequiresPage()).
   44065 **
   44066 ** If the condition asserted by this function were not true, and the
   44067 ** dirty page were to be discarded from the cache via the pagerStress()
   44068 ** routine, pagerStress() would not write the current page content to
   44069 ** the database file. If a savepoint transaction were rolled back after
   44070 ** this happened, the correct behavior would be to restore the current
   44071 ** content of the page. However, since this content is not present in either
   44072 ** the database file or the portion of the rollback journal and
   44073 ** sub-journal rolled back the content could not be restored and the
   44074 ** database image would become corrupt. It is therefore fortunate that
   44075 ** this circumstance cannot arise.
   44076 */
   44077 #if defined(SQLITE_DEBUG)
   44078 static void assertTruncateConstraintCb(PgHdr *pPg){
   44079   assert( pPg->flags&PGHDR_DIRTY );
   44080   assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
   44081 }
   44082 static void assertTruncateConstraint(Pager *pPager){
   44083   sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
   44084 }
   44085 #else
   44086 # define assertTruncateConstraint(pPager)
   44087 #endif
   44088 
   44089 /*
   44090 ** Truncate the in-memory database file image to nPage pages. This
   44091 ** function does not actually modify the database file on disk. It
   44092 ** just sets the internal state of the pager object so that the
   44093 ** truncation will be done when the current transaction is committed.
   44094 **
   44095 ** This function is only called right before committing a transaction.
   44096 ** Once this function has been called, the transaction must either be
   44097 ** rolled back or committed. It is not safe to call this function and
   44098 ** then continue writing to the database.
   44099 */
   44100 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
   44101   assert( pPager->dbSize>=nPage );
   44102   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
   44103   pPager->dbSize = nPage;
   44104 
   44105   /* At one point the code here called assertTruncateConstraint() to
   44106   ** ensure that all pages being truncated away by this operation are,
   44107   ** if one or more savepoints are open, present in the savepoint
   44108   ** journal so that they can be restored if the savepoint is rolled
   44109   ** back. This is no longer necessary as this function is now only
   44110   ** called right before committing a transaction. So although the
   44111   ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
   44112   ** they cannot be rolled back. So the assertTruncateConstraint() call
   44113   ** is no longer correct. */
   44114 }
   44115 
   44116 
   44117 /*
   44118 ** This function is called before attempting a hot-journal rollback. It
   44119 ** syncs the journal file to disk, then sets pPager->journalHdr to the
   44120 ** size of the journal file so that the pager_playback() routine knows
   44121 ** that the entire journal file has been synced.
   44122 **
   44123 ** Syncing a hot-journal to disk before attempting to roll it back ensures
   44124 ** that if a power-failure occurs during the rollback, the process that
   44125 ** attempts rollback following system recovery sees the same journal
   44126 ** content as this process.
   44127 **
   44128 ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
   44129 ** an SQLite error code.
   44130 */
   44131 static int pagerSyncHotJournal(Pager *pPager){
   44132   int rc = SQLITE_OK;
   44133   if( !pPager->noSync ){
   44134     rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
   44135   }
   44136   if( rc==SQLITE_OK ){
   44137     rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
   44138   }
   44139   return rc;
   44140 }
   44141 
   44142 /*
   44143 ** Obtain a reference to a memory mapped page object for page number pgno.
   44144 ** The new object will use the pointer pData, obtained from xFetch().
   44145 ** If successful, set *ppPage to point to the new page reference
   44146 ** and return SQLITE_OK. Otherwise, return an SQLite error code and set
   44147 ** *ppPage to zero.
   44148 **
   44149 ** Page references obtained by calling this function should be released
   44150 ** by calling pagerReleaseMapPage().
   44151 */
   44152 static int pagerAcquireMapPage(
   44153   Pager *pPager,                  /* Pager object */
   44154   Pgno pgno,                      /* Page number */
   44155   void *pData,                    /* xFetch()'d data for this page */
   44156   PgHdr **ppPage                  /* OUT: Acquired page object */
   44157 ){
   44158   PgHdr *p;                       /* Memory mapped page to return */
   44159 
   44160   if( pPager->pMmapFreelist ){
   44161     *ppPage = p = pPager->pMmapFreelist;
   44162     pPager->pMmapFreelist = p->pDirty;
   44163     p->pDirty = 0;
   44164     memset(p->pExtra, 0, pPager->nExtra);
   44165   }else{
   44166     *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
   44167     if( p==0 ){
   44168       sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
   44169       return SQLITE_NOMEM;
   44170     }
   44171     p->pExtra = (void *)&p[1];
   44172     p->flags = PGHDR_MMAP;
   44173     p->nRef = 1;
   44174     p->pPager = pPager;
   44175   }
   44176 
   44177   assert( p->pExtra==(void *)&p[1] );
   44178   assert( p->pPage==0 );
   44179   assert( p->flags==PGHDR_MMAP );
   44180   assert( p->pPager==pPager );
   44181   assert( p->nRef==1 );
   44182 
   44183   p->pgno = pgno;
   44184   p->pData = pData;
   44185   pPager->nMmapOut++;
   44186 
   44187   return SQLITE_OK;
   44188 }
   44189 
   44190 /*
   44191 ** Release a reference to page pPg. pPg must have been returned by an
   44192 ** earlier call to pagerAcquireMapPage().
   44193 */
   44194 static void pagerReleaseMapPage(PgHdr *pPg){
   44195   Pager *pPager = pPg->pPager;
   44196   pPager->nMmapOut--;
   44197   pPg->pDirty = pPager->pMmapFreelist;
   44198   pPager->pMmapFreelist = pPg;
   44199 
   44200   assert( pPager->fd->pMethods->iVersion>=3 );
   44201   sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
   44202 }
   44203 
   44204 /*
   44205 ** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
   44206 */
   44207 static void pagerFreeMapHdrs(Pager *pPager){
   44208   PgHdr *p;
   44209   PgHdr *pNext;
   44210   for(p=pPager->pMmapFreelist; p; p=pNext){
   44211     pNext = p->pDirty;
   44212     sqlite3_free(p);
   44213   }
   44214 }
   44215 
   44216 
   44217 /*
   44218 ** Shutdown the page cache.  Free all memory and close all files.
   44219 **
   44220 ** If a transaction was in progress when this routine is called, that
   44221 ** transaction is rolled back.  All outstanding pages are invalidated
   44222 ** and their memory is freed.  Any attempt to use a page associated
   44223 ** with this page cache after this function returns will likely
   44224 ** result in a coredump.
   44225 **
   44226 ** This function always succeeds. If a transaction is active an attempt
   44227 ** is made to roll it back. If an error occurs during the rollback
   44228 ** a hot journal may be left in the filesystem but no error is returned
   44229 ** to the caller.
   44230 */
   44231 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
   44232   u8 *pTmp = (u8 *)pPager->pTmpSpace;
   44233 
   44234   assert( assert_pager_state(pPager) );
   44235   disable_simulated_io_errors();
   44236   sqlite3BeginBenignMalloc();
   44237   pagerFreeMapHdrs(pPager);
   44238   /* pPager->errCode = 0; */
   44239   pPager->exclusiveMode = 0;
   44240 #ifndef SQLITE_OMIT_WAL
   44241   sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
   44242   pPager->pWal = 0;
   44243 #endif
   44244   pager_reset(pPager);
   44245   if( MEMDB ){
   44246     pager_unlock(pPager);
   44247   }else{
   44248     /* If it is open, sync the journal file before calling UnlockAndRollback.
   44249     ** If this is not done, then an unsynced portion of the open journal
   44250     ** file may be played back into the database. If a power failure occurs
   44251     ** while this is happening, the database could become corrupt.
   44252     **
   44253     ** If an error occurs while trying to sync the journal, shift the pager
   44254     ** into the ERROR state. This causes UnlockAndRollback to unlock the
   44255     ** database and close the journal file without attempting to roll it
   44256     ** back or finalize it. The next database user will have to do hot-journal
   44257     ** rollback before accessing the database file.
   44258     */
   44259     if( isOpen(pPager->jfd) ){
   44260       pager_error(pPager, pagerSyncHotJournal(pPager));
   44261     }
   44262     pagerUnlockAndRollback(pPager);
   44263   }
   44264   sqlite3EndBenignMalloc();
   44265   enable_simulated_io_errors();
   44266   PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
   44267   IOTRACE(("CLOSE %p\n", pPager))
   44268   sqlite3OsClose(pPager->jfd);
   44269   sqlite3OsClose(pPager->fd);
   44270   sqlite3PageFree(pTmp);
   44271   sqlite3PcacheClose(pPager->pPCache);
   44272 
   44273 #ifdef SQLITE_HAS_CODEC
   44274   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
   44275 #endif
   44276 
   44277   assert( !pPager->aSavepoint && !pPager->pInJournal );
   44278   assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
   44279 
   44280   sqlite3_free(pPager);
   44281   return SQLITE_OK;
   44282 }
   44283 
   44284 #if !defined(NDEBUG) || defined(SQLITE_TEST)
   44285 /*
   44286 ** Return the page number for page pPg.
   44287 */
   44288 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
   44289   return pPg->pgno;
   44290 }
   44291 #endif
   44292 
   44293 /*
   44294 ** Increment the reference count for page pPg.
   44295 */
   44296 SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
   44297   sqlite3PcacheRef(pPg);
   44298 }
   44299 
   44300 /*
   44301 ** Sync the journal. In other words, make sure all the pages that have
   44302 ** been written to the journal have actually reached the surface of the
   44303 ** disk and can be restored in the event of a hot-journal rollback.
   44304 **
   44305 ** If the Pager.noSync flag is set, then this function is a no-op.
   44306 ** Otherwise, the actions required depend on the journal-mode and the
   44307 ** device characteristics of the file-system, as follows:
   44308 **
   44309 **   * If the journal file is an in-memory journal file, no action need
   44310 **     be taken.
   44311 **
   44312 **   * Otherwise, if the device does not support the SAFE_APPEND property,
   44313 **     then the nRec field of the most recently written journal header
   44314 **     is updated to contain the number of journal records that have
   44315 **     been written following it. If the pager is operating in full-sync
   44316 **     mode, then the journal file is synced before this field is updated.
   44317 **
   44318 **   * If the device does not support the SEQUENTIAL property, then
   44319 **     journal file is synced.
   44320 **
   44321 ** Or, in pseudo-code:
   44322 **
   44323 **   if( NOT <in-memory journal> ){
   44324 **     if( NOT SAFE_APPEND ){
   44325 **       if( <full-sync mode> ) xSync(<journal file>);
   44326 **       <update nRec field>
   44327 **     }
   44328 **     if( NOT SEQUENTIAL ) xSync(<journal file>);
   44329 **   }
   44330 **
   44331 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
   44332 ** page currently held in memory before returning SQLITE_OK. If an IO
   44333 ** error is encountered, then the IO error code is returned to the caller.
   44334 */
   44335 static int syncJournal(Pager *pPager, int newHdr){
   44336   int rc;                         /* Return code */
   44337 
   44338   assert( pPager->eState==PAGER_WRITER_CACHEMOD
   44339        || pPager->eState==PAGER_WRITER_DBMOD
   44340   );
   44341   assert( assert_pager_state(pPager) );
   44342   assert( !pagerUseWal(pPager) );
   44343 
   44344   rc = sqlite3PagerExclusiveLock(pPager);
   44345   if( rc!=SQLITE_OK ) return rc;
   44346 
   44347   if( !pPager->noSync ){
   44348     assert( !pPager->tempFile );
   44349     if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
   44350       const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
   44351       assert( isOpen(pPager->jfd) );
   44352 
   44353       if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
   44354         /* This block deals with an obscure problem. If the last connection
   44355         ** that wrote to this database was operating in persistent-journal
   44356         ** mode, then the journal file may at this point actually be larger
   44357         ** than Pager.journalOff bytes. If the next thing in the journal
   44358         ** file happens to be a journal-header (written as part of the
   44359         ** previous connection's transaction), and a crash or power-failure
   44360         ** occurs after nRec is updated but before this connection writes
   44361         ** anything else to the journal file (or commits/rolls back its
   44362         ** transaction), then SQLite may become confused when doing the
   44363         ** hot-journal rollback following recovery. It may roll back all
   44364         ** of this connections data, then proceed to rolling back the old,
   44365         ** out-of-date data that follows it. Database corruption.
   44366         **
   44367         ** To work around this, if the journal file does appear to contain
   44368         ** a valid header following Pager.journalOff, then write a 0x00
   44369         ** byte to the start of it to prevent it from being recognized.
   44370         **
   44371         ** Variable iNextHdrOffset is set to the offset at which this
   44372         ** problematic header will occur, if it exists. aMagic is used
   44373         ** as a temporary buffer to inspect the first couple of bytes of
   44374         ** the potential journal header.
   44375         */
   44376         i64 iNextHdrOffset;
   44377         u8 aMagic[8];
   44378         u8 zHeader[sizeof(aJournalMagic)+4];
   44379 
   44380         memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
   44381         put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
   44382 
   44383         iNextHdrOffset = journalHdrOffset(pPager);
   44384         rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
   44385         if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
   44386           static const u8 zerobyte = 0;
   44387           rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
   44388         }
   44389         if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
   44390           return rc;
   44391         }
   44392 
   44393         /* Write the nRec value into the journal file header. If in
   44394         ** full-synchronous mode, sync the journal first. This ensures that
   44395         ** all data has really hit the disk before nRec is updated to mark
   44396         ** it as a candidate for rollback.
   44397         **
   44398         ** This is not required if the persistent media supports the
   44399         ** SAFE_APPEND property. Because in this case it is not possible
   44400         ** for garbage data to be appended to the file, the nRec field
   44401         ** is populated with 0xFFFFFFFF when the journal header is written
   44402         ** and never needs to be updated.
   44403         */
   44404         if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
   44405           PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
   44406           IOTRACE(("JSYNC %p\n", pPager))
   44407           rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
   44408           if( rc!=SQLITE_OK ) return rc;
   44409         }
   44410         IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
   44411         rc = sqlite3OsWrite(
   44412             pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
   44413         );
   44414         if( rc!=SQLITE_OK ) return rc;
   44415       }
   44416       if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
   44417         PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
   44418         IOTRACE(("JSYNC %p\n", pPager))
   44419         rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
   44420           (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
   44421         );
   44422         if( rc!=SQLITE_OK ) return rc;
   44423       }
   44424 
   44425       pPager->journalHdr = pPager->journalOff;
   44426       if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
   44427         pPager->nRec = 0;
   44428         rc = writeJournalHdr(pPager);
   44429         if( rc!=SQLITE_OK ) return rc;
   44430       }
   44431     }else{
   44432       pPager->journalHdr = pPager->journalOff;
   44433     }
   44434   }
   44435 
   44436   /* Unless the pager is in noSync mode, the journal file was just
   44437   ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
   44438   ** all pages.
   44439   */
   44440   sqlite3PcacheClearSyncFlags(pPager->pPCache);
   44441   pPager->eState = PAGER_WRITER_DBMOD;
   44442   assert( assert_pager_state(pPager) );
   44443   return SQLITE_OK;
   44444 }
   44445 
   44446 /*
   44447 ** The argument is the first in a linked list of dirty pages connected
   44448 ** by the PgHdr.pDirty pointer. This function writes each one of the
   44449 ** in-memory pages in the list to the database file. The argument may
   44450 ** be NULL, representing an empty list. In this case this function is
   44451 ** a no-op.
   44452 **
   44453 ** The pager must hold at least a RESERVED lock when this function
   44454 ** is called. Before writing anything to the database file, this lock
   44455 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
   44456 ** SQLITE_BUSY is returned and no data is written to the database file.
   44457 **
   44458 ** If the pager is a temp-file pager and the actual file-system file
   44459 ** is not yet open, it is created and opened before any data is
   44460 ** written out.
   44461 **
   44462 ** Once the lock has been upgraded and, if necessary, the file opened,
   44463 ** the pages are written out to the database file in list order. Writing
   44464 ** a page is skipped if it meets either of the following criteria:
   44465 **
   44466 **   * The page number is greater than Pager.dbSize, or
   44467 **   * The PGHDR_DONT_WRITE flag is set on the page.
   44468 **
   44469 ** If writing out a page causes the database file to grow, Pager.dbFileSize
   44470 ** is updated accordingly. If page 1 is written out, then the value cached
   44471 ** in Pager.dbFileVers[] is updated to match the new value stored in
   44472 ** the database file.
   44473 **
   44474 ** If everything is successful, SQLITE_OK is returned. If an IO error
   44475 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
   44476 ** be obtained, SQLITE_BUSY is returned.
   44477 */
   44478 static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
   44479   int rc = SQLITE_OK;                  /* Return code */
   44480 
   44481   /* This function is only called for rollback pagers in WRITER_DBMOD state. */
   44482   assert( !pagerUseWal(pPager) );
   44483   assert( pPager->eState==PAGER_WRITER_DBMOD );
   44484   assert( pPager->eLock==EXCLUSIVE_LOCK );
   44485 
   44486   /* If the file is a temp-file has not yet been opened, open it now. It
   44487   ** is not possible for rc to be other than SQLITE_OK if this branch
   44488   ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
   44489   */
   44490   if( !isOpen(pPager->fd) ){
   44491     assert( pPager->tempFile && rc==SQLITE_OK );
   44492     rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
   44493   }
   44494 
   44495   /* Before the first write, give the VFS a hint of what the final
   44496   ** file size will be.
   44497   */
   44498   assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
   44499   if( rc==SQLITE_OK
   44500    && pPager->dbHintSize<pPager->dbSize
   44501    && (pList->pDirty || pList->pgno>pPager->dbHintSize)
   44502   ){
   44503     sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
   44504     sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
   44505     pPager->dbHintSize = pPager->dbSize;
   44506   }
   44507 
   44508   while( rc==SQLITE_OK && pList ){
   44509     Pgno pgno = pList->pgno;
   44510 
   44511     /* If there are dirty pages in the page cache with page numbers greater
   44512     ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
   44513     ** make the file smaller (presumably by auto-vacuum code). Do not write
   44514     ** any such pages to the file.
   44515     **
   44516     ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
   44517     ** set (set by sqlite3PagerDontWrite()).
   44518     */
   44519     if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
   44520       i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
   44521       char *pData;                                   /* Data to write */
   44522 
   44523       assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
   44524       if( pList->pgno==1 ) pager_write_changecounter(pList);
   44525 
   44526       /* Encode the database */
   44527       CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
   44528 
   44529       /* Write out the page data. */
   44530       rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
   44531 
   44532       /* If page 1 was just written, update Pager.dbFileVers to match
   44533       ** the value now stored in the database file. If writing this
   44534       ** page caused the database file to grow, update dbFileSize.
   44535       */
   44536       if( pgno==1 ){
   44537         memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
   44538       }
   44539       if( pgno>pPager->dbFileSize ){
   44540         pPager->dbFileSize = pgno;
   44541       }
   44542       pPager->aStat[PAGER_STAT_WRITE]++;
   44543 
   44544       /* Update any backup objects copying the contents of this pager. */
   44545       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
   44546 
   44547       PAGERTRACE(("STORE %d page %d hash(%08x)\n",
   44548                    PAGERID(pPager), pgno, pager_pagehash(pList)));
   44549       IOTRACE(("PGOUT %p %d\n", pPager, pgno));
   44550       PAGER_INCR(sqlite3_pager_writedb_count);
   44551     }else{
   44552       PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
   44553     }
   44554     pager_set_pagehash(pList);
   44555     pList = pList->pDirty;
   44556   }
   44557 
   44558   return rc;
   44559 }
   44560 
   44561 /*
   44562 ** Ensure that the sub-journal file is open. If it is already open, this
   44563 ** function is a no-op.
   44564 **
   44565 ** SQLITE_OK is returned if everything goes according to plan. An
   44566 ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
   44567 ** fails.
   44568 */
   44569 static int openSubJournal(Pager *pPager){
   44570   int rc = SQLITE_OK;
   44571   if( !isOpen(pPager->sjfd) ){
   44572     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
   44573       sqlite3MemJournalOpen(pPager->sjfd);
   44574     }else{
   44575       rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
   44576     }
   44577   }
   44578   return rc;
   44579 }
   44580 
   44581 /*
   44582 ** Append a record of the current state of page pPg to the sub-journal.
   44583 ** It is the callers responsibility to use subjRequiresPage() to check
   44584 ** that it is really required before calling this function.
   44585 **
   44586 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
   44587 ** for all open savepoints before returning.
   44588 **
   44589 ** This function returns SQLITE_OK if everything is successful, an IO
   44590 ** error code if the attempt to write to the sub-journal fails, or
   44591 ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
   44592 ** bitvec.
   44593 */
   44594 static int subjournalPage(PgHdr *pPg){
   44595   int rc = SQLITE_OK;
   44596   Pager *pPager = pPg->pPager;
   44597   if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
   44598 
   44599     /* Open the sub-journal, if it has not already been opened */
   44600     assert( pPager->useJournal );
   44601     assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
   44602     assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
   44603     assert( pagerUseWal(pPager)
   44604          || pageInJournal(pPager, pPg)
   44605          || pPg->pgno>pPager->dbOrigSize
   44606     );
   44607     rc = openSubJournal(pPager);
   44608 
   44609     /* If the sub-journal was opened successfully (or was already open),
   44610     ** write the journal record into the file.  */
   44611     if( rc==SQLITE_OK ){
   44612       void *pData = pPg->pData;
   44613       i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
   44614       char *pData2;
   44615 
   44616       CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
   44617       PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
   44618       rc = write32bits(pPager->sjfd, offset, pPg->pgno);
   44619       if( rc==SQLITE_OK ){
   44620         rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
   44621       }
   44622     }
   44623   }
   44624   if( rc==SQLITE_OK ){
   44625     pPager->nSubRec++;
   44626     assert( pPager->nSavepoint>0 );
   44627     rc = addToSavepointBitvecs(pPager, pPg->pgno);
   44628   }
   44629   return rc;
   44630 }
   44631 
   44632 /*
   44633 ** This function is called by the pcache layer when it has reached some
   44634 ** soft memory limit. The first argument is a pointer to a Pager object
   44635 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
   44636 ** database). The second argument is a reference to a page that is
   44637 ** currently dirty but has no outstanding references. The page
   44638 ** is always associated with the Pager object passed as the first
   44639 ** argument.
   44640 **
   44641 ** The job of this function is to make pPg clean by writing its contents
   44642 ** out to the database file, if possible. This may involve syncing the
   44643 ** journal file.
   44644 **
   44645 ** If successful, sqlite3PcacheMakeClean() is called on the page and
   44646 ** SQLITE_OK returned. If an IO error occurs while trying to make the
   44647 ** page clean, the IO error code is returned. If the page cannot be
   44648 ** made clean for some other reason, but no error occurs, then SQLITE_OK
   44649 ** is returned by sqlite3PcacheMakeClean() is not called.
   44650 */
   44651 static int pagerStress(void *p, PgHdr *pPg){
   44652   Pager *pPager = (Pager *)p;
   44653   int rc = SQLITE_OK;
   44654 
   44655   assert( pPg->pPager==pPager );
   44656   assert( pPg->flags&PGHDR_DIRTY );
   44657 
   44658   /* The doNotSpill NOSYNC bit is set during times when doing a sync of
   44659   ** journal (and adding a new header) is not allowed.  This occurs
   44660   ** during calls to sqlite3PagerWrite() while trying to journal multiple
   44661   ** pages belonging to the same sector.
   44662   **
   44663   ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
   44664   ** regardless of whether or not a sync is required.  This is set during
   44665   ** a rollback or by user request, respectively.
   44666   **
   44667   ** Spilling is also prohibited when in an error state since that could
   44668   ** lead to database corruption.   In the current implementaton it
   44669   ** is impossible for sqlite3PcacheFetch() to be called with createFlag==1
   44670   ** while in the error state, hence it is impossible for this routine to
   44671   ** be called in the error state.  Nevertheless, we include a NEVER()
   44672   ** test for the error state as a safeguard against future changes.
   44673   */
   44674   if( NEVER(pPager->errCode) ) return SQLITE_OK;
   44675   testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
   44676   testcase( pPager->doNotSpill & SPILLFLAG_OFF );
   44677   testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
   44678   if( pPager->doNotSpill
   44679    && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
   44680       || (pPg->flags & PGHDR_NEED_SYNC)!=0)
   44681   ){
   44682     return SQLITE_OK;
   44683   }
   44684 
   44685   pPg->pDirty = 0;
   44686   if( pagerUseWal(pPager) ){
   44687     /* Write a single frame for this page to the log. */
   44688     if( subjRequiresPage(pPg) ){
   44689       rc = subjournalPage(pPg);
   44690     }
   44691     if( rc==SQLITE_OK ){
   44692       rc = pagerWalFrames(pPager, pPg, 0, 0);
   44693     }
   44694   }else{
   44695 
   44696     /* Sync the journal file if required. */
   44697     if( pPg->flags&PGHDR_NEED_SYNC
   44698      || pPager->eState==PAGER_WRITER_CACHEMOD
   44699     ){
   44700       rc = syncJournal(pPager, 1);
   44701     }
   44702 
   44703     /* If the page number of this page is larger than the current size of
   44704     ** the database image, it may need to be written to the sub-journal.
   44705     ** This is because the call to pager_write_pagelist() below will not
   44706     ** actually write data to the file in this case.
   44707     **
   44708     ** Consider the following sequence of events:
   44709     **
   44710     **   BEGIN;
   44711     **     <journal page X>
   44712     **     <modify page X>
   44713     **     SAVEPOINT sp;
   44714     **       <shrink database file to Y pages>
   44715     **       pagerStress(page X)
   44716     **     ROLLBACK TO sp;
   44717     **
   44718     ** If (X>Y), then when pagerStress is called page X will not be written
   44719     ** out to the database file, but will be dropped from the cache. Then,
   44720     ** following the "ROLLBACK TO sp" statement, reading page X will read
   44721     ** data from the database file. This will be the copy of page X as it
   44722     ** was when the transaction started, not as it was when "SAVEPOINT sp"
   44723     ** was executed.
   44724     **
   44725     ** The solution is to write the current data for page X into the
   44726     ** sub-journal file now (if it is not already there), so that it will
   44727     ** be restored to its current value when the "ROLLBACK TO sp" is
   44728     ** executed.
   44729     */
   44730     if( NEVER(
   44731         rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
   44732     ) ){
   44733       rc = subjournalPage(pPg);
   44734     }
   44735 
   44736     /* Write the contents of the page out to the database file. */
   44737     if( rc==SQLITE_OK ){
   44738       assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
   44739       rc = pager_write_pagelist(pPager, pPg);
   44740     }
   44741   }
   44742 
   44743   /* Mark the page as clean. */
   44744   if( rc==SQLITE_OK ){
   44745     PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
   44746     sqlite3PcacheMakeClean(pPg);
   44747   }
   44748 
   44749   return pager_error(pPager, rc);
   44750 }
   44751 
   44752 
   44753 /*
   44754 ** Allocate and initialize a new Pager object and put a pointer to it
   44755 ** in *ppPager. The pager should eventually be freed by passing it
   44756 ** to sqlite3PagerClose().
   44757 **
   44758 ** The zFilename argument is the path to the database file to open.
   44759 ** If zFilename is NULL then a randomly-named temporary file is created
   44760 ** and used as the file to be cached. Temporary files are be deleted
   44761 ** automatically when they are closed. If zFilename is ":memory:" then
   44762 ** all information is held in cache. It is never written to disk.
   44763 ** This can be used to implement an in-memory database.
   44764 **
   44765 ** The nExtra parameter specifies the number of bytes of space allocated
   44766 ** along with each page reference. This space is available to the user
   44767 ** via the sqlite3PagerGetExtra() API.
   44768 **
   44769 ** The flags argument is used to specify properties that affect the
   44770 ** operation of the pager. It should be passed some bitwise combination
   44771 ** of the PAGER_* flags.
   44772 **
   44773 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
   44774 ** of the xOpen() method of the supplied VFS when opening files.
   44775 **
   44776 ** If the pager object is allocated and the specified file opened
   44777 ** successfully, SQLITE_OK is returned and *ppPager set to point to
   44778 ** the new pager object. If an error occurs, *ppPager is set to NULL
   44779 ** and error code returned. This function may return SQLITE_NOMEM
   44780 ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
   44781 ** various SQLITE_IO_XXX errors.
   44782 */
   44783 SQLITE_PRIVATE int sqlite3PagerOpen(
   44784   sqlite3_vfs *pVfs,       /* The virtual file system to use */
   44785   Pager **ppPager,         /* OUT: Return the Pager structure here */
   44786   const char *zFilename,   /* Name of the database file to open */
   44787   int nExtra,              /* Extra bytes append to each in-memory page */
   44788   int flags,               /* flags controlling this file */
   44789   int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
   44790   void (*xReinit)(DbPage*) /* Function to reinitialize pages */
   44791 ){
   44792   u8 *pPtr;
   44793   Pager *pPager = 0;       /* Pager object to allocate and return */
   44794   int rc = SQLITE_OK;      /* Return code */
   44795   int tempFile = 0;        /* True for temp files (incl. in-memory files) */
   44796   int memDb = 0;           /* True if this is an in-memory file */
   44797   int readOnly = 0;        /* True if this is a read-only file */
   44798   int journalFileSize;     /* Bytes to allocate for each journal fd */
   44799   char *zPathname = 0;     /* Full path to database file */
   44800   int nPathname = 0;       /* Number of bytes in zPathname */
   44801   int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
   44802   int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
   44803   u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
   44804   const char *zUri = 0;    /* URI args to copy */
   44805   int nUri = 0;            /* Number of bytes of URI args at *zUri */
   44806 
   44807   /* Figure out how much space is required for each journal file-handle
   44808   ** (there are two of them, the main journal and the sub-journal). This
   44809   ** is the maximum space required for an in-memory journal file handle
   44810   ** and a regular journal file-handle. Note that a "regular journal-handle"
   44811   ** may be a wrapper capable of caching the first portion of the journal
   44812   ** file in memory to implement the atomic-write optimization (see
   44813   ** source file journal.c).
   44814   */
   44815   if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
   44816     journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
   44817   }else{
   44818     journalFileSize = ROUND8(sqlite3MemJournalSize());
   44819   }
   44820 
   44821   /* Set the output variable to NULL in case an error occurs. */
   44822   *ppPager = 0;
   44823 
   44824 #ifndef SQLITE_OMIT_MEMORYDB
   44825   if( flags & PAGER_MEMORY ){
   44826     memDb = 1;
   44827     if( zFilename && zFilename[0] ){
   44828       zPathname = sqlite3DbStrDup(0, zFilename);
   44829       if( zPathname==0  ) return SQLITE_NOMEM;
   44830       nPathname = sqlite3Strlen30(zPathname);
   44831       zFilename = 0;
   44832     }
   44833   }
   44834 #endif
   44835 
   44836   /* Compute and store the full pathname in an allocated buffer pointed
   44837   ** to by zPathname, length nPathname. Or, if this is a temporary file,
   44838   ** leave both nPathname and zPathname set to 0.
   44839   */
   44840   if( zFilename && zFilename[0] ){
   44841     const char *z;
   44842     nPathname = pVfs->mxPathname+1;
   44843     zPathname = sqlite3DbMallocRaw(0, nPathname*2);
   44844     if( zPathname==0 ){
   44845       return SQLITE_NOMEM;
   44846     }
   44847     zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
   44848     rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
   44849     nPathname = sqlite3Strlen30(zPathname);
   44850     z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
   44851     while( *z ){
   44852       z += sqlite3Strlen30(z)+1;
   44853       z += sqlite3Strlen30(z)+1;
   44854     }
   44855     nUri = (int)(&z[1] - zUri);
   44856     assert( nUri>=0 );
   44857     if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
   44858       /* This branch is taken when the journal path required by
   44859       ** the database being opened will be more than pVfs->mxPathname
   44860       ** bytes in length. This means the database cannot be opened,
   44861       ** as it will not be possible to open the journal file or even
   44862       ** check for a hot-journal before reading.
   44863       */
   44864       rc = SQLITE_CANTOPEN_BKPT;
   44865     }
   44866     if( rc!=SQLITE_OK ){
   44867       sqlite3DbFree(0, zPathname);
   44868       return rc;
   44869     }
   44870   }
   44871 
   44872   /* Allocate memory for the Pager structure, PCache object, the
   44873   ** three file descriptors, the database file name and the journal
   44874   ** file name. The layout in memory is as follows:
   44875   **
   44876   **     Pager object                    (sizeof(Pager) bytes)
   44877   **     PCache object                   (sqlite3PcacheSize() bytes)
   44878   **     Database file handle            (pVfs->szOsFile bytes)
   44879   **     Sub-journal file handle         (journalFileSize bytes)
   44880   **     Main journal file handle        (journalFileSize bytes)
   44881   **     Database file name              (nPathname+1 bytes)
   44882   **     Journal file name               (nPathname+8+1 bytes)
   44883   */
   44884   pPtr = (u8 *)sqlite3MallocZero(
   44885     ROUND8(sizeof(*pPager)) +      /* Pager structure */
   44886     ROUND8(pcacheSize) +           /* PCache object */
   44887     ROUND8(pVfs->szOsFile) +       /* The main db file */
   44888     journalFileSize * 2 +          /* The two journal files */
   44889     nPathname + 1 + nUri +         /* zFilename */
   44890     nPathname + 8 + 2              /* zJournal */
   44891 #ifndef SQLITE_OMIT_WAL
   44892     + nPathname + 4 + 2            /* zWal */
   44893 #endif
   44894   );
   44895   assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
   44896   if( !pPtr ){
   44897     sqlite3DbFree(0, zPathname);
   44898     return SQLITE_NOMEM;
   44899   }
   44900   pPager =              (Pager*)(pPtr);
   44901   pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
   44902   pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
   44903   pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
   44904   pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
   44905   pPager->zFilename =    (char*)(pPtr += journalFileSize);
   44906   assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
   44907 
   44908   /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
   44909   if( zPathname ){
   44910     assert( nPathname>0 );
   44911     pPager->zJournal =   (char*)(pPtr += nPathname + 1 + nUri);
   44912     memcpy(pPager->zFilename, zPathname, nPathname);
   44913     if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
   44914     memcpy(pPager->zJournal, zPathname, nPathname);
   44915     memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
   44916     sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
   44917 #ifndef SQLITE_OMIT_WAL
   44918     pPager->zWal = &pPager->zJournal[nPathname+8+1];
   44919     memcpy(pPager->zWal, zPathname, nPathname);
   44920     memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
   44921     sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
   44922 #endif
   44923     sqlite3DbFree(0, zPathname);
   44924   }
   44925   pPager->pVfs = pVfs;
   44926   pPager->vfsFlags = vfsFlags;
   44927 
   44928   /* Open the pager file.
   44929   */
   44930   if( zFilename && zFilename[0] ){
   44931     int fout = 0;                    /* VFS flags returned by xOpen() */
   44932     rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
   44933     assert( !memDb );
   44934     readOnly = (fout&SQLITE_OPEN_READONLY);
   44935 
   44936     /* If the file was successfully opened for read/write access,
   44937     ** choose a default page size in case we have to create the
   44938     ** database file. The default page size is the maximum of:
   44939     **
   44940     **    + SQLITE_DEFAULT_PAGE_SIZE,
   44941     **    + The value returned by sqlite3OsSectorSize()
   44942     **    + The largest page size that can be written atomically.
   44943     */
   44944     if( rc==SQLITE_OK ){
   44945       int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
   44946       if( !readOnly ){
   44947         setSectorSize(pPager);
   44948         assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
   44949         if( szPageDflt<pPager->sectorSize ){
   44950           if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
   44951             szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
   44952           }else{
   44953             szPageDflt = (u32)pPager->sectorSize;
   44954           }
   44955         }
   44956 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
   44957         {
   44958           int ii;
   44959           assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
   44960           assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
   44961           assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
   44962           for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
   44963             if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
   44964               szPageDflt = ii;
   44965             }
   44966           }
   44967         }
   44968 #endif
   44969       }
   44970       pPager->noLock = sqlite3_uri_boolean(zFilename, "nolock", 0);
   44971       if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0
   44972        || sqlite3_uri_boolean(zFilename, "immutable", 0) ){
   44973           vfsFlags |= SQLITE_OPEN_READONLY;
   44974           goto act_like_temp_file;
   44975       }
   44976     }
   44977   }else{
   44978     /* If a temporary file is requested, it is not opened immediately.
   44979     ** In this case we accept the default page size and delay actually
   44980     ** opening the file until the first call to OsWrite().
   44981     **
   44982     ** This branch is also run for an in-memory database. An in-memory
   44983     ** database is the same as a temp-file that is never written out to
   44984     ** disk and uses an in-memory rollback journal.
   44985     **
   44986     ** This branch also runs for files marked as immutable.
   44987     */
   44988 act_like_temp_file:
   44989     tempFile = 1;
   44990     pPager->eState = PAGER_READER;     /* Pretend we already have a lock */
   44991     pPager->eLock = EXCLUSIVE_LOCK;    /* Pretend we are in EXCLUSIVE locking mode */
   44992     pPager->noLock = 1;                /* Do no locking */
   44993     readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
   44994   }
   44995 
   44996   /* The following call to PagerSetPagesize() serves to set the value of
   44997   ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
   44998   */
   44999   if( rc==SQLITE_OK ){
   45000     assert( pPager->memDb==0 );
   45001     rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
   45002     testcase( rc!=SQLITE_OK );
   45003   }
   45004 
   45005   /* If an error occurred in either of the blocks above, free the
   45006   ** Pager structure and close the file.
   45007   */
   45008   if( rc!=SQLITE_OK ){
   45009     assert( !pPager->pTmpSpace );
   45010     sqlite3OsClose(pPager->fd);
   45011     sqlite3_free(pPager);
   45012     return rc;
   45013   }
   45014 
   45015   /* Initialize the PCache object. */
   45016   assert( nExtra<1000 );
   45017   nExtra = ROUND8(nExtra);
   45018   sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
   45019                     !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
   45020 
   45021   PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
   45022   IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
   45023 
   45024   pPager->useJournal = (u8)useJournal;
   45025   /* pPager->stmtOpen = 0; */
   45026   /* pPager->stmtInUse = 0; */
   45027   /* pPager->nRef = 0; */
   45028   /* pPager->stmtSize = 0; */
   45029   /* pPager->stmtJSize = 0; */
   45030   /* pPager->nPage = 0; */
   45031   pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
   45032   /* pPager->state = PAGER_UNLOCK; */
   45033   /* pPager->errMask = 0; */
   45034   pPager->tempFile = (u8)tempFile;
   45035   assert( tempFile==PAGER_LOCKINGMODE_NORMAL
   45036           || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
   45037   assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
   45038   pPager->exclusiveMode = (u8)tempFile;
   45039   pPager->changeCountDone = pPager->tempFile;
   45040   pPager->memDb = (u8)memDb;
   45041   pPager->readOnly = (u8)readOnly;
   45042   assert( useJournal || pPager->tempFile );
   45043   pPager->noSync = pPager->tempFile;
   45044   if( pPager->noSync ){
   45045     assert( pPager->fullSync==0 );
   45046     assert( pPager->syncFlags==0 );
   45047     assert( pPager->walSyncFlags==0 );
   45048     assert( pPager->ckptSyncFlags==0 );
   45049   }else{
   45050     pPager->fullSync = 1;
   45051     pPager->syncFlags = SQLITE_SYNC_NORMAL;
   45052     pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
   45053     pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
   45054   }
   45055   /* pPager->pFirst = 0; */
   45056   /* pPager->pFirstSynced = 0; */
   45057   /* pPager->pLast = 0; */
   45058   pPager->nExtra = (u16)nExtra;
   45059   pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
   45060   assert( isOpen(pPager->fd) || tempFile );
   45061   setSectorSize(pPager);
   45062   if( !useJournal ){
   45063     pPager->journalMode = PAGER_JOURNALMODE_OFF;
   45064   }else if( memDb ){
   45065     pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
   45066   }
   45067   /* pPager->xBusyHandler = 0; */
   45068   /* pPager->pBusyHandlerArg = 0; */
   45069   pPager->xReiniter = xReinit;
   45070   /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
   45071   /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
   45072 
   45073   *ppPager = pPager;
   45074   return SQLITE_OK;
   45075 }
   45076 
   45077 
   45078 /* Verify that the database file has not be deleted or renamed out from
   45079 ** under the pager.  Return SQLITE_OK if the database is still were it ought
   45080 ** to be on disk.  Return non-zero (SQLITE_READONLY_DBMOVED or some other error
   45081 ** code from sqlite3OsAccess()) if the database has gone missing.
   45082 */
   45083 static int databaseIsUnmoved(Pager *pPager){
   45084   int bHasMoved = 0;
   45085   int rc;
   45086 
   45087   if( pPager->tempFile ) return SQLITE_OK;
   45088   if( pPager->dbSize==0 ) return SQLITE_OK;
   45089   assert( pPager->zFilename && pPager->zFilename[0] );
   45090   rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
   45091   if( rc==SQLITE_NOTFOUND ){
   45092     /* If the HAS_MOVED file-control is unimplemented, assume that the file
   45093     ** has not been moved.  That is the historical behavior of SQLite: prior to
   45094     ** version 3.8.3, it never checked */
   45095     rc = SQLITE_OK;
   45096   }else if( rc==SQLITE_OK && bHasMoved ){
   45097     rc = SQLITE_READONLY_DBMOVED;
   45098   }
   45099   return rc;
   45100 }
   45101 
   45102 
   45103 /*
   45104 ** This function is called after transitioning from PAGER_UNLOCK to
   45105 ** PAGER_SHARED state. It tests if there is a hot journal present in
   45106 ** the file-system for the given pager. A hot journal is one that
   45107 ** needs to be played back. According to this function, a hot-journal
   45108 ** file exists if the following criteria are met:
   45109 **
   45110 **   * The journal file exists in the file system, and
   45111 **   * No process holds a RESERVED or greater lock on the database file, and
   45112 **   * The database file itself is greater than 0 bytes in size, and
   45113 **   * The first byte of the journal file exists and is not 0x00.
   45114 **
   45115 ** If the current size of the database file is 0 but a journal file
   45116 ** exists, that is probably an old journal left over from a prior
   45117 ** database with the same name. In this case the journal file is
   45118 ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
   45119 ** is returned.
   45120 **
   45121 ** This routine does not check if there is a master journal filename
   45122 ** at the end of the file. If there is, and that master journal file
   45123 ** does not exist, then the journal file is not really hot. In this
   45124 ** case this routine will return a false-positive. The pager_playback()
   45125 ** routine will discover that the journal file is not really hot and
   45126 ** will not roll it back.
   45127 **
   45128 ** If a hot-journal file is found to exist, *pExists is set to 1 and
   45129 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
   45130 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
   45131 ** to determine whether or not a hot-journal file exists, the IO error
   45132 ** code is returned and the value of *pExists is undefined.
   45133 */
   45134 static int hasHotJournal(Pager *pPager, int *pExists){
   45135   sqlite3_vfs * const pVfs = pPager->pVfs;
   45136   int rc = SQLITE_OK;           /* Return code */
   45137   int exists = 1;               /* True if a journal file is present */
   45138   int jrnlOpen = !!isOpen(pPager->jfd);
   45139 
   45140   assert( pPager->useJournal );
   45141   assert( isOpen(pPager->fd) );
   45142   assert( pPager->eState==PAGER_OPEN );
   45143 
   45144   assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
   45145     SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
   45146   ));
   45147 
   45148   *pExists = 0;
   45149   if( !jrnlOpen ){
   45150     rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
   45151   }
   45152   if( rc==SQLITE_OK && exists ){
   45153     int locked = 0;             /* True if some process holds a RESERVED lock */
   45154 
   45155     /* Race condition here:  Another process might have been holding the
   45156     ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
   45157     ** call above, but then delete the journal and drop the lock before
   45158     ** we get to the following sqlite3OsCheckReservedLock() call.  If that
   45159     ** is the case, this routine might think there is a hot journal when
   45160     ** in fact there is none.  This results in a false-positive which will
   45161     ** be dealt with by the playback routine.  Ticket #3883.
   45162     */
   45163     rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
   45164     if( rc==SQLITE_OK && !locked ){
   45165       Pgno nPage;                 /* Number of pages in database file */
   45166 
   45167       rc = pagerPagecount(pPager, &nPage);
   45168       if( rc==SQLITE_OK ){
   45169         /* If the database is zero pages in size, that means that either (1) the
   45170         ** journal is a remnant from a prior database with the same name where
   45171         ** the database file but not the journal was deleted, or (2) the initial
   45172         ** transaction that populates a new database is being rolled back.
   45173         ** In either case, the journal file can be deleted.  However, take care
   45174         ** not to delete the journal file if it is already open due to
   45175         ** journal_mode=PERSIST.
   45176         */
   45177         if( nPage==0 && !jrnlOpen ){
   45178           sqlite3BeginBenignMalloc();
   45179           if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
   45180             sqlite3OsDelete(pVfs, pPager->zJournal, 0);
   45181             if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
   45182           }
   45183           sqlite3EndBenignMalloc();
   45184         }else{
   45185           /* The journal file exists and no other connection has a reserved
   45186           ** or greater lock on the database file. Now check that there is
   45187           ** at least one non-zero bytes at the start of the journal file.
   45188           ** If there is, then we consider this journal to be hot. If not,
   45189           ** it can be ignored.
   45190           */
   45191           if( !jrnlOpen ){
   45192             int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
   45193             rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
   45194           }
   45195           if( rc==SQLITE_OK ){
   45196             u8 first = 0;
   45197             rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
   45198             if( rc==SQLITE_IOERR_SHORT_READ ){
   45199               rc = SQLITE_OK;
   45200             }
   45201             if( !jrnlOpen ){
   45202               sqlite3OsClose(pPager->jfd);
   45203             }
   45204             *pExists = (first!=0);
   45205           }else if( rc==SQLITE_CANTOPEN ){
   45206             /* If we cannot open the rollback journal file in order to see if
   45207             ** its has a zero header, that might be due to an I/O error, or
   45208             ** it might be due to the race condition described above and in
   45209             ** ticket #3883.  Either way, assume that the journal is hot.
   45210             ** This might be a false positive.  But if it is, then the
   45211             ** automatic journal playback and recovery mechanism will deal
   45212             ** with it under an EXCLUSIVE lock where we do not need to
   45213             ** worry so much with race conditions.
   45214             */
   45215             *pExists = 1;
   45216             rc = SQLITE_OK;
   45217           }
   45218         }
   45219       }
   45220     }
   45221   }
   45222 
   45223   return rc;
   45224 }
   45225 
   45226 /*
   45227 ** This function is called to obtain a shared lock on the database file.
   45228 ** It is illegal to call sqlite3PagerAcquire() until after this function
   45229 ** has been successfully called. If a shared-lock is already held when
   45230 ** this function is called, it is a no-op.
   45231 **
   45232 ** The following operations are also performed by this function.
   45233 **
   45234 **   1) If the pager is currently in PAGER_OPEN state (no lock held
   45235 **      on the database file), then an attempt is made to obtain a
   45236 **      SHARED lock on the database file. Immediately after obtaining
   45237 **      the SHARED lock, the file-system is checked for a hot-journal,
   45238 **      which is played back if present. Following any hot-journal
   45239 **      rollback, the contents of the cache are validated by checking
   45240 **      the 'change-counter' field of the database file header and
   45241 **      discarded if they are found to be invalid.
   45242 **
   45243 **   2) If the pager is running in exclusive-mode, and there are currently
   45244 **      no outstanding references to any pages, and is in the error state,
   45245 **      then an attempt is made to clear the error state by discarding
   45246 **      the contents of the page cache and rolling back any open journal
   45247 **      file.
   45248 **
   45249 ** If everything is successful, SQLITE_OK is returned. If an IO error
   45250 ** occurs while locking the database, checking for a hot-journal file or
   45251 ** rolling back a journal file, the IO error code is returned.
   45252 */
   45253 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
   45254   int rc = SQLITE_OK;                /* Return code */
   45255 
   45256   /* This routine is only called from b-tree and only when there are no
   45257   ** outstanding pages. This implies that the pager state should either
   45258   ** be OPEN or READER. READER is only possible if the pager is or was in
   45259   ** exclusive access mode.
   45260   */
   45261   assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
   45262   assert( assert_pager_state(pPager) );
   45263   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
   45264   if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
   45265 
   45266   if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
   45267     int bHotJournal = 1;          /* True if there exists a hot journal-file */
   45268 
   45269     assert( !MEMDB );
   45270 
   45271     rc = pager_wait_on_lock(pPager, SHARED_LOCK);
   45272     if( rc!=SQLITE_OK ){
   45273       assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
   45274       goto failed;
   45275     }
   45276 
   45277     /* If a journal file exists, and there is no RESERVED lock on the
   45278     ** database file, then it either needs to be played back or deleted.
   45279     */
   45280     if( pPager->eLock<=SHARED_LOCK ){
   45281       rc = hasHotJournal(pPager, &bHotJournal);
   45282     }
   45283     if( rc!=SQLITE_OK ){
   45284       goto failed;
   45285     }
   45286     if( bHotJournal ){
   45287       if( pPager->readOnly ){
   45288         rc = SQLITE_READONLY_ROLLBACK;
   45289         goto failed;
   45290       }
   45291 
   45292       /* Get an EXCLUSIVE lock on the database file. At this point it is
   45293       ** important that a RESERVED lock is not obtained on the way to the
   45294       ** EXCLUSIVE lock. If it were, another process might open the
   45295       ** database file, detect the RESERVED lock, and conclude that the
   45296       ** database is safe to read while this process is still rolling the
   45297       ** hot-journal back.
   45298       **
   45299       ** Because the intermediate RESERVED lock is not requested, any
   45300       ** other process attempting to access the database file will get to
   45301       ** this point in the code and fail to obtain its own EXCLUSIVE lock
   45302       ** on the database file.
   45303       **
   45304       ** Unless the pager is in locking_mode=exclusive mode, the lock is
   45305       ** downgraded to SHARED_LOCK before this function returns.
   45306       */
   45307       rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
   45308       if( rc!=SQLITE_OK ){
   45309         goto failed;
   45310       }
   45311 
   45312       /* If it is not already open and the file exists on disk, open the
   45313       ** journal for read/write access. Write access is required because
   45314       ** in exclusive-access mode the file descriptor will be kept open
   45315       ** and possibly used for a transaction later on. Also, write-access
   45316       ** is usually required to finalize the journal in journal_mode=persist
   45317       ** mode (and also for journal_mode=truncate on some systems).
   45318       **
   45319       ** If the journal does not exist, it usually means that some
   45320       ** other connection managed to get in and roll it back before
   45321       ** this connection obtained the exclusive lock above. Or, it
   45322       ** may mean that the pager was in the error-state when this
   45323       ** function was called and the journal file does not exist.
   45324       */
   45325       if( !isOpen(pPager->jfd) ){
   45326         sqlite3_vfs * const pVfs = pPager->pVfs;
   45327         int bExists;              /* True if journal file exists */
   45328         rc = sqlite3OsAccess(
   45329             pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
   45330         if( rc==SQLITE_OK && bExists ){
   45331           int fout = 0;
   45332           int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
   45333           assert( !pPager->tempFile );
   45334           rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
   45335           assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
   45336           if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
   45337             rc = SQLITE_CANTOPEN_BKPT;
   45338             sqlite3OsClose(pPager->jfd);
   45339           }
   45340         }
   45341       }
   45342 
   45343       /* Playback and delete the journal.  Drop the database write
   45344       ** lock and reacquire the read lock. Purge the cache before
   45345       ** playing back the hot-journal so that we don't end up with
   45346       ** an inconsistent cache.  Sync the hot journal before playing
   45347       ** it back since the process that crashed and left the hot journal
   45348       ** probably did not sync it and we are required to always sync
   45349       ** the journal before playing it back.
   45350       */
   45351       if( isOpen(pPager->jfd) ){
   45352         assert( rc==SQLITE_OK );
   45353         rc = pagerSyncHotJournal(pPager);
   45354         if( rc==SQLITE_OK ){
   45355           rc = pager_playback(pPager, 1);
   45356           pPager->eState = PAGER_OPEN;
   45357         }
   45358       }else if( !pPager->exclusiveMode ){
   45359         pagerUnlockDb(pPager, SHARED_LOCK);
   45360       }
   45361 
   45362       if( rc!=SQLITE_OK ){
   45363         /* This branch is taken if an error occurs while trying to open
   45364         ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
   45365         ** pager_unlock() routine will be called before returning to unlock
   45366         ** the file. If the unlock attempt fails, then Pager.eLock must be
   45367         ** set to UNKNOWN_LOCK (see the comment above the #define for
   45368         ** UNKNOWN_LOCK above for an explanation).
   45369         **
   45370         ** In order to get pager_unlock() to do this, set Pager.eState to
   45371         ** PAGER_ERROR now. This is not actually counted as a transition
   45372         ** to ERROR state in the state diagram at the top of this file,
   45373         ** since we know that the same call to pager_unlock() will very
   45374         ** shortly transition the pager object to the OPEN state. Calling
   45375         ** assert_pager_state() would fail now, as it should not be possible
   45376         ** to be in ERROR state when there are zero outstanding page
   45377         ** references.
   45378         */
   45379         pager_error(pPager, rc);
   45380         goto failed;
   45381       }
   45382 
   45383       assert( pPager->eState==PAGER_OPEN );
   45384       assert( (pPager->eLock==SHARED_LOCK)
   45385            || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
   45386       );
   45387     }
   45388 
   45389     if( !pPager->tempFile && (
   45390         pPager->pBackup
   45391      || sqlite3PcachePagecount(pPager->pPCache)>0
   45392      || USEFETCH(pPager)
   45393     )){
   45394       /* The shared-lock has just been acquired on the database file
   45395       ** and there are already pages in the cache (from a previous
   45396       ** read or write transaction).  Check to see if the database
   45397       ** has been modified.  If the database has changed, flush the
   45398       ** cache.
   45399       **
   45400       ** Database changes is detected by looking at 15 bytes beginning
   45401       ** at offset 24 into the file.  The first 4 of these 16 bytes are
   45402       ** a 32-bit counter that is incremented with each change.  The
   45403       ** other bytes change randomly with each file change when
   45404       ** a codec is in use.
   45405       **
   45406       ** There is a vanishingly small chance that a change will not be
   45407       ** detected.  The chance of an undetected change is so small that
   45408       ** it can be neglected.
   45409       */
   45410       Pgno nPage = 0;
   45411       char dbFileVers[sizeof(pPager->dbFileVers)];
   45412 
   45413       rc = pagerPagecount(pPager, &nPage);
   45414       if( rc ) goto failed;
   45415 
   45416       if( nPage>0 ){
   45417         IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
   45418         rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
   45419         if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
   45420           goto failed;
   45421         }
   45422       }else{
   45423         memset(dbFileVers, 0, sizeof(dbFileVers));
   45424       }
   45425 
   45426       if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
   45427         pager_reset(pPager);
   45428 
   45429         /* Unmap the database file. It is possible that external processes
   45430         ** may have truncated the database file and then extended it back
   45431         ** to its original size while this process was not holding a lock.
   45432         ** In this case there may exist a Pager.pMap mapping that appears
   45433         ** to be the right size but is not actually valid. Avoid this
   45434         ** possibility by unmapping the db here. */
   45435         if( USEFETCH(pPager) ){
   45436           sqlite3OsUnfetch(pPager->fd, 0, 0);
   45437         }
   45438       }
   45439     }
   45440 
   45441     /* If there is a WAL file in the file-system, open this database in WAL
   45442     ** mode. Otherwise, the following function call is a no-op.
   45443     */
   45444     rc = pagerOpenWalIfPresent(pPager);
   45445 #ifndef SQLITE_OMIT_WAL
   45446     assert( pPager->pWal==0 || rc==SQLITE_OK );
   45447 #endif
   45448   }
   45449 
   45450   if( pagerUseWal(pPager) ){
   45451     assert( rc==SQLITE_OK );
   45452     rc = pagerBeginReadTransaction(pPager);
   45453   }
   45454 
   45455   if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
   45456     rc = pagerPagecount(pPager, &pPager->dbSize);
   45457   }
   45458 
   45459  failed:
   45460   if( rc!=SQLITE_OK ){
   45461     assert( !MEMDB );
   45462     pager_unlock(pPager);
   45463     assert( pPager->eState==PAGER_OPEN );
   45464   }else{
   45465     pPager->eState = PAGER_READER;
   45466   }
   45467   return rc;
   45468 }
   45469 
   45470 /*
   45471 ** If the reference count has reached zero, rollback any active
   45472 ** transaction and unlock the pager.
   45473 **
   45474 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
   45475 ** the rollback journal, the unlock is not performed and there is
   45476 ** nothing to rollback, so this routine is a no-op.
   45477 */
   45478 static void pagerUnlockIfUnused(Pager *pPager){
   45479   if( pPager->nMmapOut==0 && (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
   45480     pagerUnlockAndRollback(pPager);
   45481   }
   45482 }
   45483 
   45484 /*
   45485 ** Acquire a reference to page number pgno in pager pPager (a page
   45486 ** reference has type DbPage*). If the requested reference is
   45487 ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
   45488 **
   45489 ** If the requested page is already in the cache, it is returned.
   45490 ** Otherwise, a new page object is allocated and populated with data
   45491 ** read from the database file. In some cases, the pcache module may
   45492 ** choose not to allocate a new page object and may reuse an existing
   45493 ** object with no outstanding references.
   45494 **
   45495 ** The extra data appended to a page is always initialized to zeros the
   45496 ** first time a page is loaded into memory. If the page requested is
   45497 ** already in the cache when this function is called, then the extra
   45498 ** data is left as it was when the page object was last used.
   45499 **
   45500 ** If the database image is smaller than the requested page or if a
   45501 ** non-zero value is passed as the noContent parameter and the
   45502 ** requested page is not already stored in the cache, then no
   45503 ** actual disk read occurs. In this case the memory image of the
   45504 ** page is initialized to all zeros.
   45505 **
   45506 ** If noContent is true, it means that we do not care about the contents
   45507 ** of the page. This occurs in two scenarios:
   45508 **
   45509 **   a) When reading a free-list leaf page from the database, and
   45510 **
   45511 **   b) When a savepoint is being rolled back and we need to load
   45512 **      a new page into the cache to be filled with the data read
   45513 **      from the savepoint journal.
   45514 **
   45515 ** If noContent is true, then the data returned is zeroed instead of
   45516 ** being read from the database. Additionally, the bits corresponding
   45517 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
   45518 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
   45519 ** savepoints are set. This means if the page is made writable at any
   45520 ** point in the future, using a call to sqlite3PagerWrite(), its contents
   45521 ** will not be journaled. This saves IO.
   45522 **
   45523 ** The acquisition might fail for several reasons.  In all cases,
   45524 ** an appropriate error code is returned and *ppPage is set to NULL.
   45525 **
   45526 ** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
   45527 ** to find a page in the in-memory cache first.  If the page is not already
   45528 ** in memory, this routine goes to disk to read it in whereas Lookup()
   45529 ** just returns 0.  This routine acquires a read-lock the first time it
   45530 ** has to go to disk, and could also playback an old journal if necessary.
   45531 ** Since Lookup() never goes to disk, it never has to deal with locks
   45532 ** or journal files.
   45533 */
   45534 SQLITE_PRIVATE int sqlite3PagerAcquire(
   45535   Pager *pPager,      /* The pager open on the database file */
   45536   Pgno pgno,          /* Page number to fetch */
   45537   DbPage **ppPage,    /* Write a pointer to the page here */
   45538   int flags           /* PAGER_GET_XXX flags */
   45539 ){
   45540   int rc = SQLITE_OK;
   45541   PgHdr *pPg = 0;
   45542   u32 iFrame = 0;                 /* Frame to read from WAL file */
   45543   const int noContent = (flags & PAGER_GET_NOCONTENT);
   45544 
   45545   /* It is acceptable to use a read-only (mmap) page for any page except
   45546   ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
   45547   ** flag was specified by the caller. And so long as the db is not a
   45548   ** temporary or in-memory database.  */
   45549   const int bMmapOk = (pgno!=1 && USEFETCH(pPager)
   45550    && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
   45551 #ifdef SQLITE_HAS_CODEC
   45552    && pPager->xCodec==0
   45553 #endif
   45554   );
   45555 
   45556   assert( pPager->eState>=PAGER_READER );
   45557   assert( assert_pager_state(pPager) );
   45558   assert( noContent==0 || bMmapOk==0 );
   45559 
   45560   if( pgno==0 ){
   45561     return SQLITE_CORRUPT_BKPT;
   45562   }
   45563 
   45564   /* If the pager is in the error state, return an error immediately.
   45565   ** Otherwise, request the page from the PCache layer. */
   45566   if( pPager->errCode!=SQLITE_OK ){
   45567     rc = pPager->errCode;
   45568   }else{
   45569 
   45570     if( bMmapOk && pagerUseWal(pPager) ){
   45571       rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
   45572       if( rc!=SQLITE_OK ) goto pager_acquire_err;
   45573     }
   45574 
   45575     if( bMmapOk && iFrame==0 ){
   45576       void *pData = 0;
   45577 
   45578       rc = sqlite3OsFetch(pPager->fd,
   45579           (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
   45580       );
   45581 
   45582       if( rc==SQLITE_OK && pData ){
   45583         if( pPager->eState>PAGER_READER ){
   45584           (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
   45585         }
   45586         if( pPg==0 ){
   45587           rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
   45588         }else{
   45589           sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
   45590         }
   45591         if( pPg ){
   45592           assert( rc==SQLITE_OK );
   45593           *ppPage = pPg;
   45594           return SQLITE_OK;
   45595         }
   45596       }
   45597       if( rc!=SQLITE_OK ){
   45598         goto pager_acquire_err;
   45599       }
   45600     }
   45601 
   45602     rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
   45603   }
   45604 
   45605   if( rc!=SQLITE_OK ){
   45606     /* Either the call to sqlite3PcacheFetch() returned an error or the
   45607     ** pager was already in the error-state when this function was called.
   45608     ** Set pPg to 0 and jump to the exception handler.  */
   45609     pPg = 0;
   45610     goto pager_acquire_err;
   45611   }
   45612   assert( (*ppPage)->pgno==pgno );
   45613   assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
   45614 
   45615   if( (*ppPage)->pPager && !noContent ){
   45616     /* In this case the pcache already contains an initialized copy of
   45617     ** the page. Return without further ado.  */
   45618     assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
   45619     pPager->aStat[PAGER_STAT_HIT]++;
   45620     return SQLITE_OK;
   45621 
   45622   }else{
   45623     /* The pager cache has created a new page. Its content needs to
   45624     ** be initialized.  */
   45625 
   45626     pPg = *ppPage;
   45627     pPg->pPager = pPager;
   45628 
   45629     /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
   45630     ** number greater than this, or the unused locking-page, is requested. */
   45631     if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
   45632       rc = SQLITE_CORRUPT_BKPT;
   45633       goto pager_acquire_err;
   45634     }
   45635 
   45636     if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
   45637       if( pgno>pPager->mxPgno ){
   45638         rc = SQLITE_FULL;
   45639         goto pager_acquire_err;
   45640       }
   45641       if( noContent ){
   45642         /* Failure to set the bits in the InJournal bit-vectors is benign.
   45643         ** It merely means that we might do some extra work to journal a
   45644         ** page that does not need to be journaled.  Nevertheless, be sure
   45645         ** to test the case where a malloc error occurs while trying to set
   45646         ** a bit in a bit vector.
   45647         */
   45648         sqlite3BeginBenignMalloc();
   45649         if( pgno<=pPager->dbOrigSize ){
   45650           TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
   45651           testcase( rc==SQLITE_NOMEM );
   45652         }
   45653         TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
   45654         testcase( rc==SQLITE_NOMEM );
   45655         sqlite3EndBenignMalloc();
   45656       }
   45657       memset(pPg->pData, 0, pPager->pageSize);
   45658       IOTRACE(("ZERO %p %d\n", pPager, pgno));
   45659     }else{
   45660       if( pagerUseWal(pPager) && bMmapOk==0 ){
   45661         rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
   45662         if( rc!=SQLITE_OK ) goto pager_acquire_err;
   45663       }
   45664       assert( pPg->pPager==pPager );
   45665       pPager->aStat[PAGER_STAT_MISS]++;
   45666       rc = readDbPage(pPg, iFrame);
   45667       if( rc!=SQLITE_OK ){
   45668         goto pager_acquire_err;
   45669       }
   45670     }
   45671     pager_set_pagehash(pPg);
   45672   }
   45673 
   45674   return SQLITE_OK;
   45675 
   45676 pager_acquire_err:
   45677   assert( rc!=SQLITE_OK );
   45678   if( pPg ){
   45679     sqlite3PcacheDrop(pPg);
   45680   }
   45681   pagerUnlockIfUnused(pPager);
   45682 
   45683   *ppPage = 0;
   45684   return rc;
   45685 }
   45686 
   45687 /*
   45688 ** Acquire a page if it is already in the in-memory cache.  Do
   45689 ** not read the page from disk.  Return a pointer to the page,
   45690 ** or 0 if the page is not in cache.
   45691 **
   45692 ** See also sqlite3PagerGet().  The difference between this routine
   45693 ** and sqlite3PagerGet() is that _get() will go to the disk and read
   45694 ** in the page if the page is not already in cache.  This routine
   45695 ** returns NULL if the page is not in cache or if a disk I/O error
   45696 ** has ever happened.
   45697 */
   45698 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
   45699   PgHdr *pPg = 0;
   45700   assert( pPager!=0 );
   45701   assert( pgno!=0 );
   45702   assert( pPager->pPCache!=0 );
   45703   assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );
   45704   sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
   45705   return pPg;
   45706 }
   45707 
   45708 /*
   45709 ** Release a page reference.
   45710 **
   45711 ** If the number of references to the page drop to zero, then the
   45712 ** page is added to the LRU list.  When all references to all pages
   45713 ** are released, a rollback occurs and the lock on the database is
   45714 ** removed.
   45715 */
   45716 SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){
   45717   Pager *pPager;
   45718   assert( pPg!=0 );
   45719   pPager = pPg->pPager;
   45720   if( pPg->flags & PGHDR_MMAP ){
   45721     pagerReleaseMapPage(pPg);
   45722   }else{
   45723     sqlite3PcacheRelease(pPg);
   45724   }
   45725   pagerUnlockIfUnused(pPager);
   45726 }
   45727 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
   45728   if( pPg ) sqlite3PagerUnrefNotNull(pPg);
   45729 }
   45730 
   45731 /*
   45732 ** This function is called at the start of every write transaction.
   45733 ** There must already be a RESERVED or EXCLUSIVE lock on the database
   45734 ** file when this routine is called.
   45735 **
   45736 ** Open the journal file for pager pPager and write a journal header
   45737 ** to the start of it. If there are active savepoints, open the sub-journal
   45738 ** as well. This function is only used when the journal file is being
   45739 ** opened to write a rollback log for a transaction. It is not used
   45740 ** when opening a hot journal file to roll it back.
   45741 **
   45742 ** If the journal file is already open (as it may be in exclusive mode),
   45743 ** then this function just writes a journal header to the start of the
   45744 ** already open file.
   45745 **
   45746 ** Whether or not the journal file is opened by this function, the
   45747 ** Pager.pInJournal bitvec structure is allocated.
   45748 **
   45749 ** Return SQLITE_OK if everything is successful. Otherwise, return
   45750 ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
   45751 ** an IO error code if opening or writing the journal file fails.
   45752 */
   45753 static int pager_open_journal(Pager *pPager){
   45754   int rc = SQLITE_OK;                        /* Return code */
   45755   sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
   45756 
   45757   assert( pPager->eState==PAGER_WRITER_LOCKED );
   45758   assert( assert_pager_state(pPager) );
   45759   assert( pPager->pInJournal==0 );
   45760 
   45761   /* If already in the error state, this function is a no-op.  But on
   45762   ** the other hand, this routine is never called if we are already in
   45763   ** an error state. */
   45764   if( NEVER(pPager->errCode) ) return pPager->errCode;
   45765 
   45766   if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
   45767     pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
   45768     if( pPager->pInJournal==0 ){
   45769       return SQLITE_NOMEM;
   45770     }
   45771 
   45772     /* Open the journal file if it is not already open. */
   45773     if( !isOpen(pPager->jfd) ){
   45774       if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
   45775         sqlite3MemJournalOpen(pPager->jfd);
   45776       }else{
   45777         const int flags =                   /* VFS flags to open journal file */
   45778           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
   45779           (pPager->tempFile ?
   45780             (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
   45781             (SQLITE_OPEN_MAIN_JOURNAL)
   45782           );
   45783 
   45784         /* Verify that the database still has the same name as it did when
   45785         ** it was originally opened. */
   45786         rc = databaseIsUnmoved(pPager);
   45787         if( rc==SQLITE_OK ){
   45788 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
   45789           rc = sqlite3JournalOpen(
   45790               pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
   45791           );
   45792 #else
   45793           rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
   45794 #endif
   45795         }
   45796       }
   45797       assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
   45798     }
   45799 
   45800 
   45801     /* Write the first journal header to the journal file and open
   45802     ** the sub-journal if necessary.
   45803     */
   45804     if( rc==SQLITE_OK ){
   45805       /* TODO: Check if all of these are really required. */
   45806       pPager->nRec = 0;
   45807       pPager->journalOff = 0;
   45808       pPager->setMaster = 0;
   45809       pPager->journalHdr = 0;
   45810       rc = writeJournalHdr(pPager);
   45811     }
   45812   }
   45813 
   45814   if( rc!=SQLITE_OK ){
   45815     sqlite3BitvecDestroy(pPager->pInJournal);
   45816     pPager->pInJournal = 0;
   45817   }else{
   45818     assert( pPager->eState==PAGER_WRITER_LOCKED );
   45819     pPager->eState = PAGER_WRITER_CACHEMOD;
   45820   }
   45821 
   45822   return rc;
   45823 }
   45824 
   45825 /*
   45826 ** Begin a write-transaction on the specified pager object. If a
   45827 ** write-transaction has already been opened, this function is a no-op.
   45828 **
   45829 ** If the exFlag argument is false, then acquire at least a RESERVED
   45830 ** lock on the database file. If exFlag is true, then acquire at least
   45831 ** an EXCLUSIVE lock. If such a lock is already held, no locking
   45832 ** functions need be called.
   45833 **
   45834 ** If the subjInMemory argument is non-zero, then any sub-journal opened
   45835 ** within this transaction will be opened as an in-memory file. This
   45836 ** has no effect if the sub-journal is already opened (as it may be when
   45837 ** running in exclusive mode) or if the transaction does not require a
   45838 ** sub-journal. If the subjInMemory argument is zero, then any required
   45839 ** sub-journal is implemented in-memory if pPager is an in-memory database,
   45840 ** or using a temporary file otherwise.
   45841 */
   45842 SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
   45843   int rc = SQLITE_OK;
   45844 
   45845   if( pPager->errCode ) return pPager->errCode;
   45846   assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
   45847   pPager->subjInMemory = (u8)subjInMemory;
   45848 
   45849   if( ALWAYS(pPager->eState==PAGER_READER) ){
   45850     assert( pPager->pInJournal==0 );
   45851 
   45852     if( pagerUseWal(pPager) ){
   45853       /* If the pager is configured to use locking_mode=exclusive, and an
   45854       ** exclusive lock on the database is not already held, obtain it now.
   45855       */
   45856       if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
   45857         rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
   45858         if( rc!=SQLITE_OK ){
   45859           return rc;
   45860         }
   45861         sqlite3WalExclusiveMode(pPager->pWal, 1);
   45862       }
   45863 
   45864       /* Grab the write lock on the log file. If successful, upgrade to
   45865       ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
   45866       ** The busy-handler is not invoked if another connection already
   45867       ** holds the write-lock. If possible, the upper layer will call it.
   45868       */
   45869       rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
   45870     }else{
   45871       /* Obtain a RESERVED lock on the database file. If the exFlag parameter
   45872       ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
   45873       ** busy-handler callback can be used when upgrading to the EXCLUSIVE
   45874       ** lock, but not when obtaining the RESERVED lock.
   45875       */
   45876       rc = pagerLockDb(pPager, RESERVED_LOCK);
   45877       if( rc==SQLITE_OK && exFlag ){
   45878         rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
   45879       }
   45880     }
   45881 
   45882     if( rc==SQLITE_OK ){
   45883       /* Change to WRITER_LOCKED state.
   45884       **
   45885       ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
   45886       ** when it has an open transaction, but never to DBMOD or FINISHED.
   45887       ** This is because in those states the code to roll back savepoint
   45888       ** transactions may copy data from the sub-journal into the database
   45889       ** file as well as into the page cache. Which would be incorrect in
   45890       ** WAL mode.
   45891       */
   45892       pPager->eState = PAGER_WRITER_LOCKED;
   45893       pPager->dbHintSize = pPager->dbSize;
   45894       pPager->dbFileSize = pPager->dbSize;
   45895       pPager->dbOrigSize = pPager->dbSize;
   45896       pPager->journalOff = 0;
   45897     }
   45898 
   45899     assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
   45900     assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
   45901     assert( assert_pager_state(pPager) );
   45902   }
   45903 
   45904   PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
   45905   return rc;
   45906 }
   45907 
   45908 /*
   45909 ** Mark a single data page as writeable. The page is written into the
   45910 ** main journal or sub-journal as required. If the page is written into
   45911 ** one of the journals, the corresponding bit is set in the
   45912 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
   45913 ** of any open savepoints as appropriate.
   45914 */
   45915 static int pager_write(PgHdr *pPg){
   45916   Pager *pPager = pPg->pPager;
   45917   int rc = SQLITE_OK;
   45918   int inJournal;
   45919 
   45920   /* This routine is not called unless a write-transaction has already
   45921   ** been started. The journal file may or may not be open at this point.
   45922   ** It is never called in the ERROR state.
   45923   */
   45924   assert( pPager->eState==PAGER_WRITER_LOCKED
   45925        || pPager->eState==PAGER_WRITER_CACHEMOD
   45926        || pPager->eState==PAGER_WRITER_DBMOD
   45927   );
   45928   assert( assert_pager_state(pPager) );
   45929   assert( pPager->errCode==0 );
   45930   assert( pPager->readOnly==0 );
   45931 
   45932   CHECK_PAGE(pPg);
   45933 
   45934   /* The journal file needs to be opened. Higher level routines have already
   45935   ** obtained the necessary locks to begin the write-transaction, but the
   45936   ** rollback journal might not yet be open. Open it now if this is the case.
   45937   **
   45938   ** This is done before calling sqlite3PcacheMakeDirty() on the page.
   45939   ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
   45940   ** an error might occur and the pager would end up in WRITER_LOCKED state
   45941   ** with pages marked as dirty in the cache.
   45942   */
   45943   if( pPager->eState==PAGER_WRITER_LOCKED ){
   45944     rc = pager_open_journal(pPager);
   45945     if( rc!=SQLITE_OK ) return rc;
   45946   }
   45947   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
   45948   assert( assert_pager_state(pPager) );
   45949 
   45950   /* Mark the page as dirty.  If the page has already been written
   45951   ** to the journal then we can return right away.
   45952   */
   45953   sqlite3PcacheMakeDirty(pPg);
   45954   inJournal = pageInJournal(pPager, pPg);
   45955   if( inJournal && (pPager->nSavepoint==0 || !subjRequiresPage(pPg)) ){
   45956     assert( !pagerUseWal(pPager) );
   45957   }else{
   45958 
   45959     /* The transaction journal now exists and we have a RESERVED or an
   45960     ** EXCLUSIVE lock on the main database file.  Write the current page to
   45961     ** the transaction journal if it is not there already.
   45962     */
   45963     if( !inJournal && !pagerUseWal(pPager) ){
   45964       assert( pagerUseWal(pPager)==0 );
   45965       if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
   45966         u32 cksum;
   45967         char *pData2;
   45968         i64 iOff = pPager->journalOff;
   45969 
   45970         /* We should never write to the journal file the page that
   45971         ** contains the database locks.  The following assert verifies
   45972         ** that we do not. */
   45973         assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
   45974 
   45975         assert( pPager->journalHdr<=pPager->journalOff );
   45976         CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
   45977         cksum = pager_cksum(pPager, (u8*)pData2);
   45978 
   45979         /* Even if an IO or diskfull error occurs while journalling the
   45980         ** page in the block above, set the need-sync flag for the page.
   45981         ** Otherwise, when the transaction is rolled back, the logic in
   45982         ** playback_one_page() will think that the page needs to be restored
   45983         ** in the database file. And if an IO error occurs while doing so,
   45984         ** then corruption may follow.
   45985         */
   45986         pPg->flags |= PGHDR_NEED_SYNC;
   45987 
   45988         rc = write32bits(pPager->jfd, iOff, pPg->pgno);
   45989         if( rc!=SQLITE_OK ) return rc;
   45990         rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
   45991         if( rc!=SQLITE_OK ) return rc;
   45992         rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
   45993         if( rc!=SQLITE_OK ) return rc;
   45994 
   45995         IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
   45996                  pPager->journalOff, pPager->pageSize));
   45997         PAGER_INCR(sqlite3_pager_writej_count);
   45998         PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
   45999              PAGERID(pPager), pPg->pgno,
   46000              ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
   46001 
   46002         pPager->journalOff += 8 + pPager->pageSize;
   46003         pPager->nRec++;
   46004         assert( pPager->pInJournal!=0 );
   46005         rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
   46006         testcase( rc==SQLITE_NOMEM );
   46007         assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
   46008         rc |= addToSavepointBitvecs(pPager, pPg->pgno);
   46009         if( rc!=SQLITE_OK ){
   46010           assert( rc==SQLITE_NOMEM );
   46011           return rc;
   46012         }
   46013       }else{
   46014         if( pPager->eState!=PAGER_WRITER_DBMOD ){
   46015           pPg->flags |= PGHDR_NEED_SYNC;
   46016         }
   46017         PAGERTRACE(("APPEND %d page %d needSync=%d\n",
   46018                 PAGERID(pPager), pPg->pgno,
   46019                ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
   46020       }
   46021     }
   46022 
   46023     /* If the statement journal is open and the page is not in it,
   46024     ** then write the current page to the statement journal.  Note that
   46025     ** the statement journal format differs from the standard journal format
   46026     ** in that it omits the checksums and the header.
   46027     */
   46028     if( pPager->nSavepoint>0 && subjRequiresPage(pPg) ){
   46029       rc = subjournalPage(pPg);
   46030     }
   46031   }
   46032 
   46033   /* Update the database size and return.
   46034   */
   46035   if( pPager->dbSize<pPg->pgno ){
   46036     pPager->dbSize = pPg->pgno;
   46037   }
   46038   return rc;
   46039 }
   46040 
   46041 /*
   46042 ** Mark a data page as writeable. This routine must be called before
   46043 ** making changes to a page. The caller must check the return value
   46044 ** of this function and be careful not to change any page data unless
   46045 ** this routine returns SQLITE_OK.
   46046 **
   46047 ** The difference between this function and pager_write() is that this
   46048 ** function also deals with the special case where 2 or more pages
   46049 ** fit on a single disk sector. In this case all co-resident pages
   46050 ** must have been written to the journal file before returning.
   46051 **
   46052 ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
   46053 ** as appropriate. Otherwise, SQLITE_OK.
   46054 */
   46055 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
   46056   int rc = SQLITE_OK;
   46057 
   46058   PgHdr *pPg = pDbPage;
   46059   Pager *pPager = pPg->pPager;
   46060 
   46061   assert( (pPg->flags & PGHDR_MMAP)==0 );
   46062   assert( pPager->eState>=PAGER_WRITER_LOCKED );
   46063   assert( pPager->eState!=PAGER_ERROR );
   46064   assert( assert_pager_state(pPager) );
   46065 
   46066   if( pPager->sectorSize > (u32)pPager->pageSize ){
   46067     Pgno nPageCount;          /* Total number of pages in database file */
   46068     Pgno pg1;                 /* First page of the sector pPg is located on. */
   46069     int nPage = 0;            /* Number of pages starting at pg1 to journal */
   46070     int ii;                   /* Loop counter */
   46071     int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */
   46072     Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
   46073 
   46074     /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
   46075     ** a journal header to be written between the pages journaled by
   46076     ** this function.
   46077     */
   46078     assert( !MEMDB );
   46079     assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
   46080     pPager->doNotSpill |= SPILLFLAG_NOSYNC;
   46081 
   46082     /* This trick assumes that both the page-size and sector-size are
   46083     ** an integer power of 2. It sets variable pg1 to the identifier
   46084     ** of the first page of the sector pPg is located on.
   46085     */
   46086     pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
   46087 
   46088     nPageCount = pPager->dbSize;
   46089     if( pPg->pgno>nPageCount ){
   46090       nPage = (pPg->pgno - pg1)+1;
   46091     }else if( (pg1+nPagePerSector-1)>nPageCount ){
   46092       nPage = nPageCount+1-pg1;
   46093     }else{
   46094       nPage = nPagePerSector;
   46095     }
   46096     assert(nPage>0);
   46097     assert(pg1<=pPg->pgno);
   46098     assert((pg1+nPage)>pPg->pgno);
   46099 
   46100     for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
   46101       Pgno pg = pg1+ii;
   46102       PgHdr *pPage;
   46103       if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
   46104         if( pg!=PAGER_MJ_PGNO(pPager) ){
   46105           rc = sqlite3PagerGet(pPager, pg, &pPage);
   46106           if( rc==SQLITE_OK ){
   46107             rc = pager_write(pPage);
   46108             if( pPage->flags&PGHDR_NEED_SYNC ){
   46109               needSync = 1;
   46110             }
   46111             sqlite3PagerUnrefNotNull(pPage);
   46112           }
   46113         }
   46114       }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
   46115         if( pPage->flags&PGHDR_NEED_SYNC ){
   46116           needSync = 1;
   46117         }
   46118         sqlite3PagerUnrefNotNull(pPage);
   46119       }
   46120     }
   46121 
   46122     /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
   46123     ** starting at pg1, then it needs to be set for all of them. Because
   46124     ** writing to any of these nPage pages may damage the others, the
   46125     ** journal file must contain sync()ed copies of all of them
   46126     ** before any of them can be written out to the database file.
   46127     */
   46128     if( rc==SQLITE_OK && needSync ){
   46129       assert( !MEMDB );
   46130       for(ii=0; ii<nPage; ii++){
   46131         PgHdr *pPage = pager_lookup(pPager, pg1+ii);
   46132         if( pPage ){
   46133           pPage->flags |= PGHDR_NEED_SYNC;
   46134           sqlite3PagerUnrefNotNull(pPage);
   46135         }
   46136       }
   46137     }
   46138 
   46139     assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
   46140     pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
   46141   }else{
   46142     rc = pager_write(pDbPage);
   46143   }
   46144   return rc;
   46145 }
   46146 
   46147 /*
   46148 ** Return TRUE if the page given in the argument was previously passed
   46149 ** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
   46150 ** to change the content of the page.
   46151 */
   46152 #ifndef NDEBUG
   46153 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
   46154   return pPg->flags&PGHDR_DIRTY;
   46155 }
   46156 #endif
   46157 
   46158 /*
   46159 ** A call to this routine tells the pager that it is not necessary to
   46160 ** write the information on page pPg back to the disk, even though
   46161 ** that page might be marked as dirty.  This happens, for example, when
   46162 ** the page has been added as a leaf of the freelist and so its
   46163 ** content no longer matters.
   46164 **
   46165 ** The overlying software layer calls this routine when all of the data
   46166 ** on the given page is unused. The pager marks the page as clean so
   46167 ** that it does not get written to disk.
   46168 **
   46169 ** Tests show that this optimization can quadruple the speed of large
   46170 ** DELETE operations.
   46171 */
   46172 SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
   46173   Pager *pPager = pPg->pPager;
   46174   if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
   46175     PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
   46176     IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
   46177     pPg->flags |= PGHDR_DONT_WRITE;
   46178     pager_set_pagehash(pPg);
   46179   }
   46180 }
   46181 
   46182 /*
   46183 ** This routine is called to increment the value of the database file
   46184 ** change-counter, stored as a 4-byte big-endian integer starting at
   46185 ** byte offset 24 of the pager file.  The secondary change counter at
   46186 ** 92 is also updated, as is the SQLite version number at offset 96.
   46187 **
   46188 ** But this only happens if the pPager->changeCountDone flag is false.
   46189 ** To avoid excess churning of page 1, the update only happens once.
   46190 ** See also the pager_write_changecounter() routine that does an
   46191 ** unconditional update of the change counters.
   46192 **
   46193 ** If the isDirectMode flag is zero, then this is done by calling
   46194 ** sqlite3PagerWrite() on page 1, then modifying the contents of the
   46195 ** page data. In this case the file will be updated when the current
   46196 ** transaction is committed.
   46197 **
   46198 ** The isDirectMode flag may only be non-zero if the library was compiled
   46199 ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
   46200 ** if isDirect is non-zero, then the database file is updated directly
   46201 ** by writing an updated version of page 1 using a call to the
   46202 ** sqlite3OsWrite() function.
   46203 */
   46204 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
   46205   int rc = SQLITE_OK;
   46206 
   46207   assert( pPager->eState==PAGER_WRITER_CACHEMOD
   46208        || pPager->eState==PAGER_WRITER_DBMOD
   46209   );
   46210   assert( assert_pager_state(pPager) );
   46211 
   46212   /* Declare and initialize constant integer 'isDirect'. If the
   46213   ** atomic-write optimization is enabled in this build, then isDirect
   46214   ** is initialized to the value passed as the isDirectMode parameter
   46215   ** to this function. Otherwise, it is always set to zero.
   46216   **
   46217   ** The idea is that if the atomic-write optimization is not
   46218   ** enabled at compile time, the compiler can omit the tests of
   46219   ** 'isDirect' below, as well as the block enclosed in the
   46220   ** "if( isDirect )" condition.
   46221   */
   46222 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
   46223 # define DIRECT_MODE 0
   46224   assert( isDirectMode==0 );
   46225   UNUSED_PARAMETER(isDirectMode);
   46226 #else
   46227 # define DIRECT_MODE isDirectMode
   46228 #endif
   46229 
   46230   if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
   46231     PgHdr *pPgHdr;                /* Reference to page 1 */
   46232 
   46233     assert( !pPager->tempFile && isOpen(pPager->fd) );
   46234 
   46235     /* Open page 1 of the file for writing. */
   46236     rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
   46237     assert( pPgHdr==0 || rc==SQLITE_OK );
   46238 
   46239     /* If page one was fetched successfully, and this function is not
   46240     ** operating in direct-mode, make page 1 writable.  When not in
   46241     ** direct mode, page 1 is always held in cache and hence the PagerGet()
   46242     ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
   46243     */
   46244     if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
   46245       rc = sqlite3PagerWrite(pPgHdr);
   46246     }
   46247 
   46248     if( rc==SQLITE_OK ){
   46249       /* Actually do the update of the change counter */
   46250       pager_write_changecounter(pPgHdr);
   46251 
   46252       /* If running in direct mode, write the contents of page 1 to the file. */
   46253       if( DIRECT_MODE ){
   46254         const void *zBuf;
   46255         assert( pPager->dbFileSize>0 );
   46256         CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
   46257         if( rc==SQLITE_OK ){
   46258           rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
   46259           pPager->aStat[PAGER_STAT_WRITE]++;
   46260         }
   46261         if( rc==SQLITE_OK ){
   46262           /* Update the pager's copy of the change-counter. Otherwise, the
   46263           ** next time a read transaction is opened the cache will be
   46264           ** flushed (as the change-counter values will not match).  */
   46265           const void *pCopy = (const void *)&((const char *)zBuf)[24];
   46266           memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
   46267           pPager->changeCountDone = 1;
   46268         }
   46269       }else{
   46270         pPager->changeCountDone = 1;
   46271       }
   46272     }
   46273 
   46274     /* Release the page reference. */
   46275     sqlite3PagerUnref(pPgHdr);
   46276   }
   46277   return rc;
   46278 }
   46279 
   46280 /*
   46281 ** Sync the database file to disk. This is a no-op for in-memory databases
   46282 ** or pages with the Pager.noSync flag set.
   46283 **
   46284 ** If successful, or if called on a pager for which it is a no-op, this
   46285 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
   46286 */
   46287 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){
   46288   int rc = SQLITE_OK;
   46289 
   46290   if( isOpen(pPager->fd) ){
   46291     void *pArg = (void*)zMaster;
   46292     rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
   46293     if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
   46294   }
   46295   if( rc==SQLITE_OK && !pPager->noSync ){
   46296     assert( !MEMDB );
   46297     rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
   46298   }
   46299   return rc;
   46300 }
   46301 
   46302 /*
   46303 ** This function may only be called while a write-transaction is active in
   46304 ** rollback. If the connection is in WAL mode, this call is a no-op.
   46305 ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
   46306 ** the database file, an attempt is made to obtain one.
   46307 **
   46308 ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
   46309 ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
   46310 ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
   46311 ** returned.
   46312 */
   46313 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
   46314   int rc = SQLITE_OK;
   46315   assert( pPager->eState==PAGER_WRITER_CACHEMOD
   46316        || pPager->eState==PAGER_WRITER_DBMOD
   46317        || pPager->eState==PAGER_WRITER_LOCKED
   46318   );
   46319   assert( assert_pager_state(pPager) );
   46320   if( 0==pagerUseWal(pPager) ){
   46321     rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
   46322   }
   46323   return rc;
   46324 }
   46325 
   46326 /*
   46327 ** Sync the database file for the pager pPager. zMaster points to the name
   46328 ** of a master journal file that should be written into the individual
   46329 ** journal file. zMaster may be NULL, which is interpreted as no master
   46330 ** journal (a single database transaction).
   46331 **
   46332 ** This routine ensures that:
   46333 **
   46334 **   * The database file change-counter is updated,
   46335 **   * the journal is synced (unless the atomic-write optimization is used),
   46336 **   * all dirty pages are written to the database file,
   46337 **   * the database file is truncated (if required), and
   46338 **   * the database file synced.
   46339 **
   46340 ** The only thing that remains to commit the transaction is to finalize
   46341 ** (delete, truncate or zero the first part of) the journal file (or
   46342 ** delete the master journal file if specified).
   46343 **
   46344 ** Note that if zMaster==NULL, this does not overwrite a previous value
   46345 ** passed to an sqlite3PagerCommitPhaseOne() call.
   46346 **
   46347 ** If the final parameter - noSync - is true, then the database file itself
   46348 ** is not synced. The caller must call sqlite3PagerSync() directly to
   46349 ** sync the database file before calling CommitPhaseTwo() to delete the
   46350 ** journal file in this case.
   46351 */
   46352 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
   46353   Pager *pPager,                  /* Pager object */
   46354   const char *zMaster,            /* If not NULL, the master journal name */
   46355   int noSync                      /* True to omit the xSync on the db file */
   46356 ){
   46357   int rc = SQLITE_OK;             /* Return code */
   46358 
   46359   assert( pPager->eState==PAGER_WRITER_LOCKED
   46360        || pPager->eState==PAGER_WRITER_CACHEMOD
   46361        || pPager->eState==PAGER_WRITER_DBMOD
   46362        || pPager->eState==PAGER_ERROR
   46363   );
   46364   assert( assert_pager_state(pPager) );
   46365 
   46366   /* If a prior error occurred, report that error again. */
   46367   if( NEVER(pPager->errCode) ) return pPager->errCode;
   46368 
   46369   PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
   46370       pPager->zFilename, zMaster, pPager->dbSize));
   46371 
   46372   /* If no database changes have been made, return early. */
   46373   if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
   46374 
   46375   if( MEMDB ){
   46376     /* If this is an in-memory db, or no pages have been written to, or this
   46377     ** function has already been called, it is mostly a no-op.  However, any
   46378     ** backup in progress needs to be restarted.
   46379     */
   46380     sqlite3BackupRestart(pPager->pBackup);
   46381   }else{
   46382     if( pagerUseWal(pPager) ){
   46383       PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
   46384       PgHdr *pPageOne = 0;
   46385       if( pList==0 ){
   46386         /* Must have at least one page for the WAL commit flag.
   46387         ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
   46388         rc = sqlite3PagerGet(pPager, 1, &pPageOne);
   46389         pList = pPageOne;
   46390         pList->pDirty = 0;
   46391       }
   46392       assert( rc==SQLITE_OK );
   46393       if( ALWAYS(pList) ){
   46394         rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
   46395       }
   46396       sqlite3PagerUnref(pPageOne);
   46397       if( rc==SQLITE_OK ){
   46398         sqlite3PcacheCleanAll(pPager->pPCache);
   46399       }
   46400     }else{
   46401       /* The following block updates the change-counter. Exactly how it
   46402       ** does this depends on whether or not the atomic-update optimization
   46403       ** was enabled at compile time, and if this transaction meets the
   46404       ** runtime criteria to use the operation:
   46405       **
   46406       **    * The file-system supports the atomic-write property for
   46407       **      blocks of size page-size, and
   46408       **    * This commit is not part of a multi-file transaction, and
   46409       **    * Exactly one page has been modified and store in the journal file.
   46410       **
   46411       ** If the optimization was not enabled at compile time, then the
   46412       ** pager_incr_changecounter() function is called to update the change
   46413       ** counter in 'indirect-mode'. If the optimization is compiled in but
   46414       ** is not applicable to this transaction, call sqlite3JournalCreate()
   46415       ** to make sure the journal file has actually been created, then call
   46416       ** pager_incr_changecounter() to update the change-counter in indirect
   46417       ** mode.
   46418       **
   46419       ** Otherwise, if the optimization is both enabled and applicable,
   46420       ** then call pager_incr_changecounter() to update the change-counter
   46421       ** in 'direct' mode. In this case the journal file will never be
   46422       ** created for this transaction.
   46423       */
   46424   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
   46425       PgHdr *pPg;
   46426       assert( isOpen(pPager->jfd)
   46427            || pPager->journalMode==PAGER_JOURNALMODE_OFF
   46428            || pPager->journalMode==PAGER_JOURNALMODE_WAL
   46429       );
   46430       if( !zMaster && isOpen(pPager->jfd)
   46431        && pPager->journalOff==jrnlBufferSize(pPager)
   46432        && pPager->dbSize>=pPager->dbOrigSize
   46433        && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
   46434       ){
   46435         /* Update the db file change counter via the direct-write method. The
   46436         ** following call will modify the in-memory representation of page 1
   46437         ** to include the updated change counter and then write page 1
   46438         ** directly to the database file. Because of the atomic-write
   46439         ** property of the host file-system, this is safe.
   46440         */
   46441         rc = pager_incr_changecounter(pPager, 1);
   46442       }else{
   46443         rc = sqlite3JournalCreate(pPager->jfd);
   46444         if( rc==SQLITE_OK ){
   46445           rc = pager_incr_changecounter(pPager, 0);
   46446         }
   46447       }
   46448   #else
   46449       rc = pager_incr_changecounter(pPager, 0);
   46450   #endif
   46451       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
   46452 
   46453       /* Write the master journal name into the journal file. If a master
   46454       ** journal file name has already been written to the journal file,
   46455       ** or if zMaster is NULL (no master journal), then this call is a no-op.
   46456       */
   46457       rc = writeMasterJournal(pPager, zMaster);
   46458       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
   46459 
   46460       /* Sync the journal file and write all dirty pages to the database.
   46461       ** If the atomic-update optimization is being used, this sync will not
   46462       ** create the journal file or perform any real IO.
   46463       **
   46464       ** Because the change-counter page was just modified, unless the
   46465       ** atomic-update optimization is used it is almost certain that the
   46466       ** journal requires a sync here. However, in locking_mode=exclusive
   46467       ** on a system under memory pressure it is just possible that this is
   46468       ** not the case. In this case it is likely enough that the redundant
   46469       ** xSync() call will be changed to a no-op by the OS anyhow.
   46470       */
   46471       rc = syncJournal(pPager, 0);
   46472       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
   46473 
   46474       rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
   46475       if( rc!=SQLITE_OK ){
   46476         assert( rc!=SQLITE_IOERR_BLOCKED );
   46477         goto commit_phase_one_exit;
   46478       }
   46479       sqlite3PcacheCleanAll(pPager->pPCache);
   46480 
   46481       /* If the file on disk is smaller than the database image, use
   46482       ** pager_truncate to grow the file here. This can happen if the database
   46483       ** image was extended as part of the current transaction and then the
   46484       ** last page in the db image moved to the free-list. In this case the
   46485       ** last page is never written out to disk, leaving the database file
   46486       ** undersized. Fix this now if it is the case.  */
   46487       if( pPager->dbSize>pPager->dbFileSize ){
   46488         Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
   46489         assert( pPager->eState==PAGER_WRITER_DBMOD );
   46490         rc = pager_truncate(pPager, nNew);
   46491         if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
   46492       }
   46493 
   46494       /* Finally, sync the database file. */
   46495       if( !noSync ){
   46496         rc = sqlite3PagerSync(pPager, zMaster);
   46497       }
   46498       IOTRACE(("DBSYNC %p\n", pPager))
   46499     }
   46500   }
   46501 
   46502 commit_phase_one_exit:
   46503   if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
   46504     pPager->eState = PAGER_WRITER_FINISHED;
   46505   }
   46506   return rc;
   46507 }
   46508 
   46509 
   46510 /*
   46511 ** When this function is called, the database file has been completely
   46512 ** updated to reflect the changes made by the current transaction and
   46513 ** synced to disk. The journal file still exists in the file-system
   46514 ** though, and if a failure occurs at this point it will eventually
   46515 ** be used as a hot-journal and the current transaction rolled back.
   46516 **
   46517 ** This function finalizes the journal file, either by deleting,
   46518 ** truncating or partially zeroing it, so that it cannot be used
   46519 ** for hot-journal rollback. Once this is done the transaction is
   46520 ** irrevocably committed.
   46521 **
   46522 ** If an error occurs, an IO error code is returned and the pager
   46523 ** moves into the error state. Otherwise, SQLITE_OK is returned.
   46524 */
   46525 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
   46526   int rc = SQLITE_OK;                  /* Return code */
   46527 
   46528   /* This routine should not be called if a prior error has occurred.
   46529   ** But if (due to a coding error elsewhere in the system) it does get
   46530   ** called, just return the same error code without doing anything. */
   46531   if( NEVER(pPager->errCode) ) return pPager->errCode;
   46532 
   46533   assert( pPager->eState==PAGER_WRITER_LOCKED
   46534        || pPager->eState==PAGER_WRITER_FINISHED
   46535        || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
   46536   );
   46537   assert( assert_pager_state(pPager) );
   46538 
   46539   /* An optimization. If the database was not actually modified during
   46540   ** this transaction, the pager is running in exclusive-mode and is
   46541   ** using persistent journals, then this function is a no-op.
   46542   **
   46543   ** The start of the journal file currently contains a single journal
   46544   ** header with the nRec field set to 0. If such a journal is used as
   46545   ** a hot-journal during hot-journal rollback, 0 changes will be made
   46546   ** to the database file. So there is no need to zero the journal
   46547   ** header. Since the pager is in exclusive mode, there is no need
   46548   ** to drop any locks either.
   46549   */
   46550   if( pPager->eState==PAGER_WRITER_LOCKED
   46551    && pPager->exclusiveMode
   46552    && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
   46553   ){
   46554     assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
   46555     pPager->eState = PAGER_READER;
   46556     return SQLITE_OK;
   46557   }
   46558 
   46559   PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
   46560   rc = pager_end_transaction(pPager, pPager->setMaster, 1);
   46561   return pager_error(pPager, rc);
   46562 }
   46563 
   46564 /*
   46565 ** If a write transaction is open, then all changes made within the
   46566 ** transaction are reverted and the current write-transaction is closed.
   46567 ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
   46568 ** state if an error occurs.
   46569 **
   46570 ** If the pager is already in PAGER_ERROR state when this function is called,
   46571 ** it returns Pager.errCode immediately. No work is performed in this case.
   46572 **
   46573 ** Otherwise, in rollback mode, this function performs two functions:
   46574 **
   46575 **   1) It rolls back the journal file, restoring all database file and
   46576 **      in-memory cache pages to the state they were in when the transaction
   46577 **      was opened, and
   46578 **
   46579 **   2) It finalizes the journal file, so that it is not used for hot
   46580 **      rollback at any point in the future.
   46581 **
   46582 ** Finalization of the journal file (task 2) is only performed if the
   46583 ** rollback is successful.
   46584 **
   46585 ** In WAL mode, all cache-entries containing data modified within the
   46586 ** current transaction are either expelled from the cache or reverted to
   46587 ** their pre-transaction state by re-reading data from the database or
   46588 ** WAL files. The WAL transaction is then closed.
   46589 */
   46590 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
   46591   int rc = SQLITE_OK;                  /* Return code */
   46592   PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
   46593 
   46594   /* PagerRollback() is a no-op if called in READER or OPEN state. If
   46595   ** the pager is already in the ERROR state, the rollback is not
   46596   ** attempted here. Instead, the error code is returned to the caller.
   46597   */
   46598   assert( assert_pager_state(pPager) );
   46599   if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
   46600   if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
   46601 
   46602   if( pagerUseWal(pPager) ){
   46603     int rc2;
   46604     rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
   46605     rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
   46606     if( rc==SQLITE_OK ) rc = rc2;
   46607   }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
   46608     int eState = pPager->eState;
   46609     rc = pager_end_transaction(pPager, 0, 0);
   46610     if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
   46611       /* This can happen using journal_mode=off. Move the pager to the error
   46612       ** state to indicate that the contents of the cache may not be trusted.
   46613       ** Any active readers will get SQLITE_ABORT.
   46614       */
   46615       pPager->errCode = SQLITE_ABORT;
   46616       pPager->eState = PAGER_ERROR;
   46617       return rc;
   46618     }
   46619   }else{
   46620     rc = pager_playback(pPager, 0);
   46621   }
   46622 
   46623   assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
   46624   assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
   46625           || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR
   46626           || rc==SQLITE_CANTOPEN
   46627   );
   46628 
   46629   /* If an error occurs during a ROLLBACK, we can no longer trust the pager
   46630   ** cache. So call pager_error() on the way out to make any error persistent.
   46631   */
   46632   return pager_error(pPager, rc);
   46633 }
   46634 
   46635 /*
   46636 ** Return TRUE if the database file is opened read-only.  Return FALSE
   46637 ** if the database is (in theory) writable.
   46638 */
   46639 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
   46640   return pPager->readOnly;
   46641 }
   46642 
   46643 /*
   46644 ** Return the number of references to the pager.
   46645 */
   46646 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
   46647   return sqlite3PcacheRefCount(pPager->pPCache);
   46648 }
   46649 
   46650 /*
   46651 ** Return the approximate number of bytes of memory currently
   46652 ** used by the pager and its associated cache.
   46653 */
   46654 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
   46655   int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
   46656                                      + 5*sizeof(void*);
   46657   return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
   46658            + sqlite3MallocSize(pPager)
   46659            + pPager->pageSize;
   46660 }
   46661 
   46662 /*
   46663 ** Return the number of references to the specified page.
   46664 */
   46665 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
   46666   return sqlite3PcachePageRefcount(pPage);
   46667 }
   46668 
   46669 #ifdef SQLITE_TEST
   46670 /*
   46671 ** This routine is used for testing and analysis only.
   46672 */
   46673 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
   46674   static int a[11];
   46675   a[0] = sqlite3PcacheRefCount(pPager->pPCache);
   46676   a[1] = sqlite3PcachePagecount(pPager->pPCache);
   46677   a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
   46678   a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
   46679   a[4] = pPager->eState;
   46680   a[5] = pPager->errCode;
   46681   a[6] = pPager->aStat[PAGER_STAT_HIT];
   46682   a[7] = pPager->aStat[PAGER_STAT_MISS];
   46683   a[8] = 0;  /* Used to be pPager->nOvfl */
   46684   a[9] = pPager->nRead;
   46685   a[10] = pPager->aStat[PAGER_STAT_WRITE];
   46686   return a;
   46687 }
   46688 #endif
   46689 
   46690 /*
   46691 ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
   46692 ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
   46693 ** current cache hit or miss count, according to the value of eStat. If the
   46694 ** reset parameter is non-zero, the cache hit or miss count is zeroed before
   46695 ** returning.
   46696 */
   46697 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
   46698 
   46699   assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
   46700        || eStat==SQLITE_DBSTATUS_CACHE_MISS
   46701        || eStat==SQLITE_DBSTATUS_CACHE_WRITE
   46702   );
   46703 
   46704   assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
   46705   assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
   46706   assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
   46707 
   46708   *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
   46709   if( reset ){
   46710     pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
   46711   }
   46712 }
   46713 
   46714 /*
   46715 ** Return true if this is an in-memory pager.
   46716 */
   46717 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
   46718   return MEMDB;
   46719 }
   46720 
   46721 /*
   46722 ** Check that there are at least nSavepoint savepoints open. If there are
   46723 ** currently less than nSavepoints open, then open one or more savepoints
   46724 ** to make up the difference. If the number of savepoints is already
   46725 ** equal to nSavepoint, then this function is a no-op.
   46726 **
   46727 ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
   46728 ** occurs while opening the sub-journal file, then an IO error code is
   46729 ** returned. Otherwise, SQLITE_OK.
   46730 */
   46731 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
   46732   int rc = SQLITE_OK;                       /* Return code */
   46733   int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
   46734 
   46735   assert( pPager->eState>=PAGER_WRITER_LOCKED );
   46736   assert( assert_pager_state(pPager) );
   46737 
   46738   if( nSavepoint>nCurrent && pPager->useJournal ){
   46739     int ii;                                 /* Iterator variable */
   46740     PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
   46741 
   46742     /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
   46743     ** if the allocation fails. Otherwise, zero the new portion in case a
   46744     ** malloc failure occurs while populating it in the for(...) loop below.
   46745     */
   46746     aNew = (PagerSavepoint *)sqlite3Realloc(
   46747         pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
   46748     );
   46749     if( !aNew ){
   46750       return SQLITE_NOMEM;
   46751     }
   46752     memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
   46753     pPager->aSavepoint = aNew;
   46754 
   46755     /* Populate the PagerSavepoint structures just allocated. */
   46756     for(ii=nCurrent; ii<nSavepoint; ii++){
   46757       aNew[ii].nOrig = pPager->dbSize;
   46758       if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
   46759         aNew[ii].iOffset = pPager->journalOff;
   46760       }else{
   46761         aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
   46762       }
   46763       aNew[ii].iSubRec = pPager->nSubRec;
   46764       aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
   46765       if( !aNew[ii].pInSavepoint ){
   46766         return SQLITE_NOMEM;
   46767       }
   46768       if( pagerUseWal(pPager) ){
   46769         sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
   46770       }
   46771       pPager->nSavepoint = ii+1;
   46772     }
   46773     assert( pPager->nSavepoint==nSavepoint );
   46774     assertTruncateConstraint(pPager);
   46775   }
   46776 
   46777   return rc;
   46778 }
   46779 
   46780 /*
   46781 ** This function is called to rollback or release (commit) a savepoint.
   46782 ** The savepoint to release or rollback need not be the most recently
   46783 ** created savepoint.
   46784 **
   46785 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
   46786 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
   46787 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
   46788 ** that have occurred since the specified savepoint was created.
   46789 **
   46790 ** The savepoint to rollback or release is identified by parameter
   46791 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
   46792 ** (the first created). A value of (Pager.nSavepoint-1) means operate
   46793 ** on the most recently created savepoint. If iSavepoint is greater than
   46794 ** (Pager.nSavepoint-1), then this function is a no-op.
   46795 **
   46796 ** If a negative value is passed to this function, then the current
   46797 ** transaction is rolled back. This is different to calling
   46798 ** sqlite3PagerRollback() because this function does not terminate
   46799 ** the transaction or unlock the database, it just restores the
   46800 ** contents of the database to its original state.
   46801 **
   46802 ** In any case, all savepoints with an index greater than iSavepoint
   46803 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
   46804 ** then savepoint iSavepoint is also destroyed.
   46805 **
   46806 ** This function may return SQLITE_NOMEM if a memory allocation fails,
   46807 ** or an IO error code if an IO error occurs while rolling back a
   46808 ** savepoint. If no errors occur, SQLITE_OK is returned.
   46809 */
   46810 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
   46811   int rc = pPager->errCode;       /* Return code */
   46812 
   46813   assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
   46814   assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
   46815 
   46816   if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
   46817     int ii;            /* Iterator variable */
   46818     int nNew;          /* Number of remaining savepoints after this op. */
   46819 
   46820     /* Figure out how many savepoints will still be active after this
   46821     ** operation. Store this value in nNew. Then free resources associated
   46822     ** with any savepoints that are destroyed by this operation.
   46823     */
   46824     nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
   46825     for(ii=nNew; ii<pPager->nSavepoint; ii++){
   46826       sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
   46827     }
   46828     pPager->nSavepoint = nNew;
   46829 
   46830     /* If this is a release of the outermost savepoint, truncate
   46831     ** the sub-journal to zero bytes in size. */
   46832     if( op==SAVEPOINT_RELEASE ){
   46833       if( nNew==0 && isOpen(pPager->sjfd) ){
   46834         /* Only truncate if it is an in-memory sub-journal. */
   46835         if( sqlite3IsMemJournal(pPager->sjfd) ){
   46836           rc = sqlite3OsTruncate(pPager->sjfd, 0);
   46837           assert( rc==SQLITE_OK );
   46838         }
   46839         pPager->nSubRec = 0;
   46840       }
   46841     }
   46842     /* Else this is a rollback operation, playback the specified savepoint.
   46843     ** If this is a temp-file, it is possible that the journal file has
   46844     ** not yet been opened. In this case there have been no changes to
   46845     ** the database file, so the playback operation can be skipped.
   46846     */
   46847     else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
   46848       PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
   46849       rc = pagerPlaybackSavepoint(pPager, pSavepoint);
   46850       assert(rc!=SQLITE_DONE);
   46851     }
   46852   }
   46853 
   46854   return rc;
   46855 }
   46856 
   46857 /*
   46858 ** Return the full pathname of the database file.
   46859 **
   46860 ** Except, if the pager is in-memory only, then return an empty string if
   46861 ** nullIfMemDb is true.  This routine is called with nullIfMemDb==1 when
   46862 ** used to report the filename to the user, for compatibility with legacy
   46863 ** behavior.  But when the Btree needs to know the filename for matching to
   46864 ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
   46865 ** participate in shared-cache.
   46866 */
   46867 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
   46868   return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
   46869 }
   46870 
   46871 /*
   46872 ** Return the VFS structure for the pager.
   46873 */
   46874 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
   46875   return pPager->pVfs;
   46876 }
   46877 
   46878 /*
   46879 ** Return the file handle for the database file associated
   46880 ** with the pager.  This might return NULL if the file has
   46881 ** not yet been opened.
   46882 */
   46883 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
   46884   return pPager->fd;
   46885 }
   46886 
   46887 /*
   46888 ** Return the full pathname of the journal file.
   46889 */
   46890 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
   46891   return pPager->zJournal;
   46892 }
   46893 
   46894 /*
   46895 ** Return true if fsync() calls are disabled for this pager.  Return FALSE
   46896 ** if fsync()s are executed normally.
   46897 */
   46898 SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
   46899   return pPager->noSync;
   46900 }
   46901 
   46902 #ifdef SQLITE_HAS_CODEC
   46903 /*
   46904 ** Set or retrieve the codec for this pager
   46905 */
   46906 SQLITE_PRIVATE void sqlite3PagerSetCodec(
   46907   Pager *pPager,
   46908   void *(*xCodec)(void*,void*,Pgno,int),
   46909   void (*xCodecSizeChng)(void*,int,int),
   46910   void (*xCodecFree)(void*),
   46911   void *pCodec
   46912 ){
   46913   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
   46914   pPager->xCodec = pPager->memDb ? 0 : xCodec;
   46915   pPager->xCodecSizeChng = xCodecSizeChng;
   46916   pPager->xCodecFree = xCodecFree;
   46917   pPager->pCodec = pCodec;
   46918   pagerReportSize(pPager);
   46919 }
   46920 SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
   46921   return pPager->pCodec;
   46922 }
   46923 
   46924 /*
   46925 ** This function is called by the wal module when writing page content
   46926 ** into the log file.
   46927 **
   46928 ** This function returns a pointer to a buffer containing the encrypted
   46929 ** page content. If a malloc fails, this function may return NULL.
   46930 */
   46931 SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
   46932   void *aData = 0;
   46933   CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
   46934   return aData;
   46935 }
   46936 
   46937 /*
   46938 ** Return the current pager state
   46939 */
   46940 SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
   46941   return pPager->eState;
   46942 }
   46943 #endif /* SQLITE_HAS_CODEC */
   46944 
   46945 #ifndef SQLITE_OMIT_AUTOVACUUM
   46946 /*
   46947 ** Move the page pPg to location pgno in the file.
   46948 **
   46949 ** There must be no references to the page previously located at
   46950 ** pgno (which we call pPgOld) though that page is allowed to be
   46951 ** in cache.  If the page previously located at pgno is not already
   46952 ** in the rollback journal, it is not put there by by this routine.
   46953 **
   46954 ** References to the page pPg remain valid. Updating any
   46955 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
   46956 ** allocated along with the page) is the responsibility of the caller.
   46957 **
   46958 ** A transaction must be active when this routine is called. It used to be
   46959 ** required that a statement transaction was not active, but this restriction
   46960 ** has been removed (CREATE INDEX needs to move a page when a statement
   46961 ** transaction is active).
   46962 **
   46963 ** If the fourth argument, isCommit, is non-zero, then this page is being
   46964 ** moved as part of a database reorganization just before the transaction
   46965 ** is being committed. In this case, it is guaranteed that the database page
   46966 ** pPg refers to will not be written to again within this transaction.
   46967 **
   46968 ** This function may return SQLITE_NOMEM or an IO error code if an error
   46969 ** occurs. Otherwise, it returns SQLITE_OK.
   46970 */
   46971 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
   46972   PgHdr *pPgOld;               /* The page being overwritten. */
   46973   Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
   46974   int rc;                      /* Return code */
   46975   Pgno origPgno;               /* The original page number */
   46976 
   46977   assert( pPg->nRef>0 );
   46978   assert( pPager->eState==PAGER_WRITER_CACHEMOD
   46979        || pPager->eState==PAGER_WRITER_DBMOD
   46980   );
   46981   assert( assert_pager_state(pPager) );
   46982 
   46983   /* In order to be able to rollback, an in-memory database must journal
   46984   ** the page we are moving from.
   46985   */
   46986   if( MEMDB ){
   46987     rc = sqlite3PagerWrite(pPg);
   46988     if( rc ) return rc;
   46989   }
   46990 
   46991   /* If the page being moved is dirty and has not been saved by the latest
   46992   ** savepoint, then save the current contents of the page into the
   46993   ** sub-journal now. This is required to handle the following scenario:
   46994   **
   46995   **   BEGIN;
   46996   **     <journal page X, then modify it in memory>
   46997   **     SAVEPOINT one;
   46998   **       <Move page X to location Y>
   46999   **     ROLLBACK TO one;
   47000   **
   47001   ** If page X were not written to the sub-journal here, it would not
   47002   ** be possible to restore its contents when the "ROLLBACK TO one"
   47003   ** statement were is processed.
   47004   **
   47005   ** subjournalPage() may need to allocate space to store pPg->pgno into
   47006   ** one or more savepoint bitvecs. This is the reason this function
   47007   ** may return SQLITE_NOMEM.
   47008   */
   47009   if( pPg->flags&PGHDR_DIRTY
   47010    && subjRequiresPage(pPg)
   47011    && SQLITE_OK!=(rc = subjournalPage(pPg))
   47012   ){
   47013     return rc;
   47014   }
   47015 
   47016   PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
   47017       PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
   47018   IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
   47019 
   47020   /* If the journal needs to be sync()ed before page pPg->pgno can
   47021   ** be written to, store pPg->pgno in local variable needSyncPgno.
   47022   **
   47023   ** If the isCommit flag is set, there is no need to remember that
   47024   ** the journal needs to be sync()ed before database page pPg->pgno
   47025   ** can be written to. The caller has already promised not to write to it.
   47026   */
   47027   if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
   47028     needSyncPgno = pPg->pgno;
   47029     assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
   47030             pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
   47031     assert( pPg->flags&PGHDR_DIRTY );
   47032   }
   47033 
   47034   /* If the cache contains a page with page-number pgno, remove it
   47035   ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
   47036   ** page pgno before the 'move' operation, it needs to be retained
   47037   ** for the page moved there.
   47038   */
   47039   pPg->flags &= ~PGHDR_NEED_SYNC;
   47040   pPgOld = pager_lookup(pPager, pgno);
   47041   assert( !pPgOld || pPgOld->nRef==1 );
   47042   if( pPgOld ){
   47043     pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
   47044     if( MEMDB ){
   47045       /* Do not discard pages from an in-memory database since we might
   47046       ** need to rollback later.  Just move the page out of the way. */
   47047       sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
   47048     }else{
   47049       sqlite3PcacheDrop(pPgOld);
   47050     }
   47051   }
   47052 
   47053   origPgno = pPg->pgno;
   47054   sqlite3PcacheMove(pPg, pgno);
   47055   sqlite3PcacheMakeDirty(pPg);
   47056 
   47057   /* For an in-memory database, make sure the original page continues
   47058   ** to exist, in case the transaction needs to roll back.  Use pPgOld
   47059   ** as the original page since it has already been allocated.
   47060   */
   47061   if( MEMDB ){
   47062     assert( pPgOld );
   47063     sqlite3PcacheMove(pPgOld, origPgno);
   47064     sqlite3PagerUnrefNotNull(pPgOld);
   47065   }
   47066 
   47067   if( needSyncPgno ){
   47068     /* If needSyncPgno is non-zero, then the journal file needs to be
   47069     ** sync()ed before any data is written to database file page needSyncPgno.
   47070     ** Currently, no such page exists in the page-cache and the
   47071     ** "is journaled" bitvec flag has been set. This needs to be remedied by
   47072     ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
   47073     ** flag.
   47074     **
   47075     ** If the attempt to load the page into the page-cache fails, (due
   47076     ** to a malloc() or IO failure), clear the bit in the pInJournal[]
   47077     ** array. Otherwise, if the page is loaded and written again in
   47078     ** this transaction, it may be written to the database file before
   47079     ** it is synced into the journal file. This way, it may end up in
   47080     ** the journal file twice, but that is not a problem.
   47081     */
   47082     PgHdr *pPgHdr;
   47083     rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
   47084     if( rc!=SQLITE_OK ){
   47085       if( needSyncPgno<=pPager->dbOrigSize ){
   47086         assert( pPager->pTmpSpace!=0 );
   47087         sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
   47088       }
   47089       return rc;
   47090     }
   47091     pPgHdr->flags |= PGHDR_NEED_SYNC;
   47092     sqlite3PcacheMakeDirty(pPgHdr);
   47093     sqlite3PagerUnrefNotNull(pPgHdr);
   47094   }
   47095 
   47096   return SQLITE_OK;
   47097 }
   47098 #endif
   47099 
   47100 /*
   47101 ** Return a pointer to the data for the specified page.
   47102 */
   47103 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
   47104   assert( pPg->nRef>0 || pPg->pPager->memDb );
   47105   return pPg->pData;
   47106 }
   47107 
   47108 /*
   47109 ** Return a pointer to the Pager.nExtra bytes of "extra" space
   47110 ** allocated along with the specified page.
   47111 */
   47112 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
   47113   return pPg->pExtra;
   47114 }
   47115 
   47116 /*
   47117 ** Get/set the locking-mode for this pager. Parameter eMode must be one
   47118 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
   47119 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
   47120 ** the locking-mode is set to the value specified.
   47121 **
   47122 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
   47123 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
   47124 ** locking-mode.
   47125 */
   47126 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
   47127   assert( eMode==PAGER_LOCKINGMODE_QUERY
   47128             || eMode==PAGER_LOCKINGMODE_NORMAL
   47129             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
   47130   assert( PAGER_LOCKINGMODE_QUERY<0 );
   47131   assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
   47132   assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
   47133   if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
   47134     pPager->exclusiveMode = (u8)eMode;
   47135   }
   47136   return (int)pPager->exclusiveMode;
   47137 }
   47138 
   47139 /*
   47140 ** Set the journal-mode for this pager. Parameter eMode must be one of:
   47141 **
   47142 **    PAGER_JOURNALMODE_DELETE
   47143 **    PAGER_JOURNALMODE_TRUNCATE
   47144 **    PAGER_JOURNALMODE_PERSIST
   47145 **    PAGER_JOURNALMODE_OFF
   47146 **    PAGER_JOURNALMODE_MEMORY
   47147 **    PAGER_JOURNALMODE_WAL
   47148 **
   47149 ** The journalmode is set to the value specified if the change is allowed.
   47150 ** The change may be disallowed for the following reasons:
   47151 **
   47152 **   *  An in-memory database can only have its journal_mode set to _OFF
   47153 **      or _MEMORY.
   47154 **
   47155 **   *  Temporary databases cannot have _WAL journalmode.
   47156 **
   47157 ** The returned indicate the current (possibly updated) journal-mode.
   47158 */
   47159 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
   47160   u8 eOld = pPager->journalMode;    /* Prior journalmode */
   47161 
   47162 #ifdef SQLITE_DEBUG
   47163   /* The print_pager_state() routine is intended to be used by the debugger
   47164   ** only.  We invoke it once here to suppress a compiler warning. */
   47165   print_pager_state(pPager);
   47166 #endif
   47167 
   47168 
   47169   /* The eMode parameter is always valid */
   47170   assert(      eMode==PAGER_JOURNALMODE_DELETE
   47171             || eMode==PAGER_JOURNALMODE_TRUNCATE
   47172             || eMode==PAGER_JOURNALMODE_PERSIST
   47173             || eMode==PAGER_JOURNALMODE_OFF
   47174             || eMode==PAGER_JOURNALMODE_WAL
   47175             || eMode==PAGER_JOURNALMODE_MEMORY );
   47176 
   47177   /* This routine is only called from the OP_JournalMode opcode, and
   47178   ** the logic there will never allow a temporary file to be changed
   47179   ** to WAL mode.
   47180   */
   47181   assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
   47182 
   47183   /* Do allow the journalmode of an in-memory database to be set to
   47184   ** anything other than MEMORY or OFF
   47185   */
   47186   if( MEMDB ){
   47187     assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
   47188     if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
   47189       eMode = eOld;
   47190     }
   47191   }
   47192 
   47193   if( eMode!=eOld ){
   47194 
   47195     /* Change the journal mode. */
   47196     assert( pPager->eState!=PAGER_ERROR );
   47197     pPager->journalMode = (u8)eMode;
   47198 
   47199     /* When transistioning from TRUNCATE or PERSIST to any other journal
   47200     ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
   47201     ** delete the journal file.
   47202     */
   47203     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
   47204     assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
   47205     assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
   47206     assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
   47207     assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
   47208     assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
   47209 
   47210     assert( isOpen(pPager->fd) || pPager->exclusiveMode );
   47211     if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
   47212 
   47213       /* In this case we would like to delete the journal file. If it is
   47214       ** not possible, then that is not a problem. Deleting the journal file
   47215       ** here is an optimization only.
   47216       **
   47217       ** Before deleting the journal file, obtain a RESERVED lock on the
   47218       ** database file. This ensures that the journal file is not deleted
   47219       ** while it is in use by some other client.
   47220       */
   47221       sqlite3OsClose(pPager->jfd);
   47222       if( pPager->eLock>=RESERVED_LOCK ){
   47223         sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
   47224       }else{
   47225         int rc = SQLITE_OK;
   47226         int state = pPager->eState;
   47227         assert( state==PAGER_OPEN || state==PAGER_READER );
   47228         if( state==PAGER_OPEN ){
   47229           rc = sqlite3PagerSharedLock(pPager);
   47230         }
   47231         if( pPager->eState==PAGER_READER ){
   47232           assert( rc==SQLITE_OK );
   47233           rc = pagerLockDb(pPager, RESERVED_LOCK);
   47234         }
   47235         if( rc==SQLITE_OK ){
   47236           sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
   47237         }
   47238         if( rc==SQLITE_OK && state==PAGER_READER ){
   47239           pagerUnlockDb(pPager, SHARED_LOCK);
   47240         }else if( state==PAGER_OPEN ){
   47241           pager_unlock(pPager);
   47242         }
   47243         assert( state==pPager->eState );
   47244       }
   47245     }
   47246   }
   47247 
   47248   /* Return the new journal mode */
   47249   return (int)pPager->journalMode;
   47250 }
   47251 
   47252 /*
   47253 ** Return the current journal mode.
   47254 */
   47255 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
   47256   return (int)pPager->journalMode;
   47257 }
   47258 
   47259 /*
   47260 ** Return TRUE if the pager is in a state where it is OK to change the
   47261 ** journalmode.  Journalmode changes can only happen when the database
   47262 ** is unmodified.
   47263 */
   47264 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
   47265   assert( assert_pager_state(pPager) );
   47266   if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
   47267   if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
   47268   return 1;
   47269 }
   47270 
   47271 /*
   47272 ** Get/set the size-limit used for persistent journal files.
   47273 **
   47274 ** Setting the size limit to -1 means no limit is enforced.
   47275 ** An attempt to set a limit smaller than -1 is a no-op.
   47276 */
   47277 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
   47278   if( iLimit>=-1 ){
   47279     pPager->journalSizeLimit = iLimit;
   47280     sqlite3WalLimit(pPager->pWal, iLimit);
   47281   }
   47282   return pPager->journalSizeLimit;
   47283 }
   47284 
   47285 /*
   47286 ** Return a pointer to the pPager->pBackup variable. The backup module
   47287 ** in backup.c maintains the content of this variable. This module
   47288 ** uses it opaquely as an argument to sqlite3BackupRestart() and
   47289 ** sqlite3BackupUpdate() only.
   47290 */
   47291 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
   47292   return &pPager->pBackup;
   47293 }
   47294 
   47295 #ifndef SQLITE_OMIT_VACUUM
   47296 /*
   47297 ** Unless this is an in-memory or temporary database, clear the pager cache.
   47298 */
   47299 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
   47300   if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
   47301 }
   47302 #endif
   47303 
   47304 #ifndef SQLITE_OMIT_WAL
   47305 /*
   47306 ** This function is called when the user invokes "PRAGMA wal_checkpoint",
   47307 ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
   47308 ** or wal_blocking_checkpoint() API functions.
   47309 **
   47310 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
   47311 */
   47312 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
   47313   int rc = SQLITE_OK;
   47314   if( pPager->pWal ){
   47315     rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
   47316         pPager->xBusyHandler, pPager->pBusyHandlerArg,
   47317         pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
   47318         pnLog, pnCkpt
   47319     );
   47320   }
   47321   return rc;
   47322 }
   47323 
   47324 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
   47325   return sqlite3WalCallback(pPager->pWal);
   47326 }
   47327 
   47328 /*
   47329 ** Return true if the underlying VFS for the given pager supports the
   47330 ** primitives necessary for write-ahead logging.
   47331 */
   47332 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
   47333   const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
   47334   return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
   47335 }
   47336 
   47337 /*
   47338 ** Attempt to take an exclusive lock on the database file. If a PENDING lock
   47339 ** is obtained instead, immediately release it.
   47340 */
   47341 static int pagerExclusiveLock(Pager *pPager){
   47342   int rc;                         /* Return code */
   47343 
   47344   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
   47345   rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
   47346   if( rc!=SQLITE_OK ){
   47347     /* If the attempt to grab the exclusive lock failed, release the
   47348     ** pending lock that may have been obtained instead.  */
   47349     pagerUnlockDb(pPager, SHARED_LOCK);
   47350   }
   47351 
   47352   return rc;
   47353 }
   47354 
   47355 /*
   47356 ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
   47357 ** exclusive-locking mode when this function is called, take an EXCLUSIVE
   47358 ** lock on the database file and use heap-memory to store the wal-index
   47359 ** in. Otherwise, use the normal shared-memory.
   47360 */
   47361 static int pagerOpenWal(Pager *pPager){
   47362   int rc = SQLITE_OK;
   47363 
   47364   assert( pPager->pWal==0 && pPager->tempFile==0 );
   47365   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
   47366 
   47367   /* If the pager is already in exclusive-mode, the WAL module will use
   47368   ** heap-memory for the wal-index instead of the VFS shared-memory
   47369   ** implementation. Take the exclusive lock now, before opening the WAL
   47370   ** file, to make sure this is safe.
   47371   */
   47372   if( pPager->exclusiveMode ){
   47373     rc = pagerExclusiveLock(pPager);
   47374   }
   47375 
   47376   /* Open the connection to the log file. If this operation fails,
   47377   ** (e.g. due to malloc() failure), return an error code.
   47378   */
   47379   if( rc==SQLITE_OK ){
   47380     rc = sqlite3WalOpen(pPager->pVfs,
   47381         pPager->fd, pPager->zWal, pPager->exclusiveMode,
   47382         pPager->journalSizeLimit, &pPager->pWal
   47383     );
   47384   }
   47385   pagerFixMaplimit(pPager);
   47386 
   47387   return rc;
   47388 }
   47389 
   47390 
   47391 /*
   47392 ** The caller must be holding a SHARED lock on the database file to call
   47393 ** this function.
   47394 **
   47395 ** If the pager passed as the first argument is open on a real database
   47396 ** file (not a temp file or an in-memory database), and the WAL file
   47397 ** is not already open, make an attempt to open it now. If successful,
   47398 ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
   47399 ** not support the xShmXXX() methods, return an error code. *pbOpen is
   47400 ** not modified in either case.
   47401 **
   47402 ** If the pager is open on a temp-file (or in-memory database), or if
   47403 ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
   47404 ** without doing anything.
   47405 */
   47406 SQLITE_PRIVATE int sqlite3PagerOpenWal(
   47407   Pager *pPager,                  /* Pager object */
   47408   int *pbOpen                     /* OUT: Set to true if call is a no-op */
   47409 ){
   47410   int rc = SQLITE_OK;             /* Return code */
   47411 
   47412   assert( assert_pager_state(pPager) );
   47413   assert( pPager->eState==PAGER_OPEN   || pbOpen );
   47414   assert( pPager->eState==PAGER_READER || !pbOpen );
   47415   assert( pbOpen==0 || *pbOpen==0 );
   47416   assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
   47417 
   47418   if( !pPager->tempFile && !pPager->pWal ){
   47419     if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
   47420 
   47421     /* Close any rollback journal previously open */
   47422     sqlite3OsClose(pPager->jfd);
   47423 
   47424     rc = pagerOpenWal(pPager);
   47425     if( rc==SQLITE_OK ){
   47426       pPager->journalMode = PAGER_JOURNALMODE_WAL;
   47427       pPager->eState = PAGER_OPEN;
   47428     }
   47429   }else{
   47430     *pbOpen = 1;
   47431   }
   47432 
   47433   return rc;
   47434 }
   47435 
   47436 /*
   47437 ** This function is called to close the connection to the log file prior
   47438 ** to switching from WAL to rollback mode.
   47439 **
   47440 ** Before closing the log file, this function attempts to take an
   47441 ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
   47442 ** error (SQLITE_BUSY) is returned and the log connection is not closed.
   47443 ** If successful, the EXCLUSIVE lock is not released before returning.
   47444 */
   47445 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
   47446   int rc = SQLITE_OK;
   47447 
   47448   assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
   47449 
   47450   /* If the log file is not already open, but does exist in the file-system,
   47451   ** it may need to be checkpointed before the connection can switch to
   47452   ** rollback mode. Open it now so this can happen.
   47453   */
   47454   if( !pPager->pWal ){
   47455     int logexists = 0;
   47456     rc = pagerLockDb(pPager, SHARED_LOCK);
   47457     if( rc==SQLITE_OK ){
   47458       rc = sqlite3OsAccess(
   47459           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
   47460       );
   47461     }
   47462     if( rc==SQLITE_OK && logexists ){
   47463       rc = pagerOpenWal(pPager);
   47464     }
   47465   }
   47466 
   47467   /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
   47468   ** the database file, the log and log-summary files will be deleted.
   47469   */
   47470   if( rc==SQLITE_OK && pPager->pWal ){
   47471     rc = pagerExclusiveLock(pPager);
   47472     if( rc==SQLITE_OK ){
   47473       rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
   47474                            pPager->pageSize, (u8*)pPager->pTmpSpace);
   47475       pPager->pWal = 0;
   47476       pagerFixMaplimit(pPager);
   47477     }
   47478   }
   47479   return rc;
   47480 }
   47481 
   47482 #endif /* !SQLITE_OMIT_WAL */
   47483 
   47484 #ifdef SQLITE_ENABLE_ZIPVFS
   47485 /*
   47486 ** A read-lock must be held on the pager when this function is called. If
   47487 ** the pager is in WAL mode and the WAL file currently contains one or more
   47488 ** frames, return the size in bytes of the page images stored within the
   47489 ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
   47490 ** is empty, return 0.
   47491 */
   47492 SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
   47493   assert( pPager->eState==PAGER_READER );
   47494   return sqlite3WalFramesize(pPager->pWal);
   47495 }
   47496 #endif
   47497 
   47498 #endif /* SQLITE_OMIT_DISKIO */
   47499 
   47500 /************** End of pager.c ***********************************************/
   47501 /************** Begin file wal.c *********************************************/
   47502 /*
   47503 ** 2010 February 1
   47504 **
   47505 ** The author disclaims copyright to this source code.  In place of
   47506 ** a legal notice, here is a blessing:
   47507 **
   47508 **    May you do good and not evil.
   47509 **    May you find forgiveness for yourself and forgive others.
   47510 **    May you share freely, never taking more than you give.
   47511 **
   47512 *************************************************************************
   47513 **
   47514 ** This file contains the implementation of a write-ahead log (WAL) used in
   47515 ** "journal_mode=WAL" mode.
   47516 **
   47517 ** WRITE-AHEAD LOG (WAL) FILE FORMAT
   47518 **
   47519 ** A WAL file consists of a header followed by zero or more "frames".
   47520 ** Each frame records the revised content of a single page from the
   47521 ** database file.  All changes to the database are recorded by writing
   47522 ** frames into the WAL.  Transactions commit when a frame is written that
   47523 ** contains a commit marker.  A single WAL can and usually does record
   47524 ** multiple transactions.  Periodically, the content of the WAL is
   47525 ** transferred back into the database file in an operation called a
   47526 ** "checkpoint".
   47527 **
   47528 ** A single WAL file can be used multiple times.  In other words, the
   47529 ** WAL can fill up with frames and then be checkpointed and then new
   47530 ** frames can overwrite the old ones.  A WAL always grows from beginning
   47531 ** toward the end.  Checksums and counters attached to each frame are
   47532 ** used to determine which frames within the WAL are valid and which
   47533 ** are leftovers from prior checkpoints.
   47534 **
   47535 ** The WAL header is 32 bytes in size and consists of the following eight
   47536 ** big-endian 32-bit unsigned integer values:
   47537 **
   47538 **     0: Magic number.  0x377f0682 or 0x377f0683
   47539 **     4: File format version.  Currently 3007000
   47540 **     8: Database page size.  Example: 1024
   47541 **    12: Checkpoint sequence number
   47542 **    16: Salt-1, random integer incremented with each checkpoint
   47543 **    20: Salt-2, a different random integer changing with each ckpt
   47544 **    24: Checksum-1 (first part of checksum for first 24 bytes of header).
   47545 **    28: Checksum-2 (second part of checksum for first 24 bytes of header).
   47546 **
   47547 ** Immediately following the wal-header are zero or more frames. Each
   47548 ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
   47549 ** of page data. The frame-header is six big-endian 32-bit unsigned
   47550 ** integer values, as follows:
   47551 **
   47552 **     0: Page number.
   47553 **     4: For commit records, the size of the database image in pages
   47554 **        after the commit. For all other records, zero.
   47555 **     8: Salt-1 (copied from the header)
   47556 **    12: Salt-2 (copied from the header)
   47557 **    16: Checksum-1.
   47558 **    20: Checksum-2.
   47559 **
   47560 ** A frame is considered valid if and only if the following conditions are
   47561 ** true:
   47562 **
   47563 **    (1) The salt-1 and salt-2 values in the frame-header match
   47564 **        salt values in the wal-header
   47565 **
   47566 **    (2) The checksum values in the final 8 bytes of the frame-header
   47567 **        exactly match the checksum computed consecutively on the
   47568 **        WAL header and the first 8 bytes and the content of all frames
   47569 **        up to and including the current frame.
   47570 **
   47571 ** The checksum is computed using 32-bit big-endian integers if the
   47572 ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
   47573 ** is computed using little-endian if the magic number is 0x377f0682.
   47574 ** The checksum values are always stored in the frame header in a
   47575 ** big-endian format regardless of which byte order is used to compute
   47576 ** the checksum.  The checksum is computed by interpreting the input as
   47577 ** an even number of unsigned 32-bit integers: x[0] through x[N].  The
   47578 ** algorithm used for the checksum is as follows:
   47579 **
   47580 **   for i from 0 to n-1 step 2:
   47581 **     s0 += x[i] + s1;
   47582 **     s1 += x[i+1] + s0;
   47583 **   endfor
   47584 **
   47585 ** Note that s0 and s1 are both weighted checksums using fibonacci weights
   47586 ** in reverse order (the largest fibonacci weight occurs on the first element
   47587 ** of the sequence being summed.)  The s1 value spans all 32-bit
   47588 ** terms of the sequence whereas s0 omits the final term.
   47589 **
   47590 ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
   47591 ** WAL is transferred into the database, then the database is VFS.xSync-ed.
   47592 ** The VFS.xSync operations serve as write barriers - all writes launched
   47593 ** before the xSync must complete before any write that launches after the
   47594 ** xSync begins.
   47595 **
   47596 ** After each checkpoint, the salt-1 value is incremented and the salt-2
   47597 ** value is randomized.  This prevents old and new frames in the WAL from
   47598 ** being considered valid at the same time and being checkpointing together
   47599 ** following a crash.
   47600 **
   47601 ** READER ALGORITHM
   47602 **
   47603 ** To read a page from the database (call it page number P), a reader
   47604 ** first checks the WAL to see if it contains page P.  If so, then the
   47605 ** last valid instance of page P that is a followed by a commit frame
   47606 ** or is a commit frame itself becomes the value read.  If the WAL
   47607 ** contains no copies of page P that are valid and which are a commit
   47608 ** frame or are followed by a commit frame, then page P is read from
   47609 ** the database file.
   47610 **
   47611 ** To start a read transaction, the reader records the index of the last
   47612 ** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
   47613 ** for all subsequent read operations.  New transactions can be appended
   47614 ** to the WAL, but as long as the reader uses its original mxFrame value
   47615 ** and ignores the newly appended content, it will see a consistent snapshot
   47616 ** of the database from a single point in time.  This technique allows
   47617 ** multiple concurrent readers to view different versions of the database
   47618 ** content simultaneously.
   47619 **
   47620 ** The reader algorithm in the previous paragraphs works correctly, but
   47621 ** because frames for page P can appear anywhere within the WAL, the
   47622 ** reader has to scan the entire WAL looking for page P frames.  If the
   47623 ** WAL is large (multiple megabytes is typical) that scan can be slow,
   47624 ** and read performance suffers.  To overcome this problem, a separate
   47625 ** data structure called the wal-index is maintained to expedite the
   47626 ** search for frames of a particular page.
   47627 **
   47628 ** WAL-INDEX FORMAT
   47629 **
   47630 ** Conceptually, the wal-index is shared memory, though VFS implementations
   47631 ** might choose to implement the wal-index using a mmapped file.  Because
   47632 ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
   47633 ** on a network filesystem.  All users of the database must be able to
   47634 ** share memory.
   47635 **
   47636 ** The wal-index is transient.  After a crash, the wal-index can (and should
   47637 ** be) reconstructed from the original WAL file.  In fact, the VFS is required
   47638 ** to either truncate or zero the header of the wal-index when the last
   47639 ** connection to it closes.  Because the wal-index is transient, it can
   47640 ** use an architecture-specific format; it does not have to be cross-platform.
   47641 ** Hence, unlike the database and WAL file formats which store all values
   47642 ** as big endian, the wal-index can store multi-byte values in the native
   47643 ** byte order of the host computer.
   47644 **
   47645 ** The purpose of the wal-index is to answer this question quickly:  Given
   47646 ** a page number P and a maximum frame index M, return the index of the
   47647 ** last frame in the wal before frame M for page P in the WAL, or return
   47648 ** NULL if there are no frames for page P in the WAL prior to M.
   47649 **
   47650 ** The wal-index consists of a header region, followed by an one or
   47651 ** more index blocks.
   47652 **
   47653 ** The wal-index header contains the total number of frames within the WAL
   47654 ** in the mxFrame field.
   47655 **
   47656 ** Each index block except for the first contains information on
   47657 ** HASHTABLE_NPAGE frames. The first index block contains information on
   47658 ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
   47659 ** HASHTABLE_NPAGE are selected so that together the wal-index header and
   47660 ** first index block are the same size as all other index blocks in the
   47661 ** wal-index.
   47662 **
   47663 ** Each index block contains two sections, a page-mapping that contains the
   47664 ** database page number associated with each wal frame, and a hash-table
   47665 ** that allows readers to query an index block for a specific page number.
   47666 ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
   47667 ** for the first index block) 32-bit page numbers. The first entry in the
   47668 ** first index-block contains the database page number corresponding to the
   47669 ** first frame in the WAL file. The first entry in the second index block
   47670 ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
   47671 ** the log, and so on.
   47672 **
   47673 ** The last index block in a wal-index usually contains less than the full
   47674 ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
   47675 ** depending on the contents of the WAL file. This does not change the
   47676 ** allocated size of the page-mapping array - the page-mapping array merely
   47677 ** contains unused entries.
   47678 **
   47679 ** Even without using the hash table, the last frame for page P
   47680 ** can be found by scanning the page-mapping sections of each index block
   47681 ** starting with the last index block and moving toward the first, and
   47682 ** within each index block, starting at the end and moving toward the
   47683 ** beginning.  The first entry that equals P corresponds to the frame
   47684 ** holding the content for that page.
   47685 **
   47686 ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
   47687 ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
   47688 ** hash table for each page number in the mapping section, so the hash
   47689 ** table is never more than half full.  The expected number of collisions
   47690 ** prior to finding a match is 1.  Each entry of the hash table is an
   47691 ** 1-based index of an entry in the mapping section of the same
   47692 ** index block.   Let K be the 1-based index of the largest entry in
   47693 ** the mapping section.  (For index blocks other than the last, K will
   47694 ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
   47695 ** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
   47696 ** contain a value of 0.
   47697 **
   47698 ** To look for page P in the hash table, first compute a hash iKey on
   47699 ** P as follows:
   47700 **
   47701 **      iKey = (P * 383) % HASHTABLE_NSLOT
   47702 **
   47703 ** Then start scanning entries of the hash table, starting with iKey
   47704 ** (wrapping around to the beginning when the end of the hash table is
   47705 ** reached) until an unused hash slot is found. Let the first unused slot
   47706 ** be at index iUnused.  (iUnused might be less than iKey if there was
   47707 ** wrap-around.) Because the hash table is never more than half full,
   47708 ** the search is guaranteed to eventually hit an unused entry.  Let
   47709 ** iMax be the value between iKey and iUnused, closest to iUnused,
   47710 ** where aHash[iMax]==P.  If there is no iMax entry (if there exists
   47711 ** no hash slot such that aHash[i]==p) then page P is not in the
   47712 ** current index block.  Otherwise the iMax-th mapping entry of the
   47713 ** current index block corresponds to the last entry that references
   47714 ** page P.
   47715 **
   47716 ** A hash search begins with the last index block and moves toward the
   47717 ** first index block, looking for entries corresponding to page P.  On
   47718 ** average, only two or three slots in each index block need to be
   47719 ** examined in order to either find the last entry for page P, or to
   47720 ** establish that no such entry exists in the block.  Each index block
   47721 ** holds over 4000 entries.  So two or three index blocks are sufficient
   47722 ** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
   47723 ** comparisons (on average) suffice to either locate a frame in the
   47724 ** WAL or to establish that the frame does not exist in the WAL.  This
   47725 ** is much faster than scanning the entire 10MB WAL.
   47726 **
   47727 ** Note that entries are added in order of increasing K.  Hence, one
   47728 ** reader might be using some value K0 and a second reader that started
   47729 ** at a later time (after additional transactions were added to the WAL
   47730 ** and to the wal-index) might be using a different value K1, where K1>K0.
   47731 ** Both readers can use the same hash table and mapping section to get
   47732 ** the correct result.  There may be entries in the hash table with
   47733 ** K>K0 but to the first reader, those entries will appear to be unused
   47734 ** slots in the hash table and so the first reader will get an answer as
   47735 ** if no values greater than K0 had ever been inserted into the hash table
   47736 ** in the first place - which is what reader one wants.  Meanwhile, the
   47737 ** second reader using K1 will see additional values that were inserted
   47738 ** later, which is exactly what reader two wants.
   47739 **
   47740 ** When a rollback occurs, the value of K is decreased. Hash table entries
   47741 ** that correspond to frames greater than the new K value are removed
   47742 ** from the hash table at this point.
   47743 */
   47744 #ifndef SQLITE_OMIT_WAL
   47745 
   47746 
   47747 /*
   47748 ** Trace output macros
   47749 */
   47750 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
   47751 SQLITE_PRIVATE int sqlite3WalTrace = 0;
   47752 # define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
   47753 #else
   47754 # define WALTRACE(X)
   47755 #endif
   47756 
   47757 /*
   47758 ** The maximum (and only) versions of the wal and wal-index formats
   47759 ** that may be interpreted by this version of SQLite.
   47760 **
   47761 ** If a client begins recovering a WAL file and finds that (a) the checksum
   47762 ** values in the wal-header are correct and (b) the version field is not
   47763 ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
   47764 **
   47765 ** Similarly, if a client successfully reads a wal-index header (i.e. the
   47766 ** checksum test is successful) and finds that the version field is not
   47767 ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
   47768 ** returns SQLITE_CANTOPEN.
   47769 */
   47770 #define WAL_MAX_VERSION      3007000
   47771 #define WALINDEX_MAX_VERSION 3007000
   47772 
   47773 /*
   47774 ** Indices of various locking bytes.   WAL_NREADER is the number
   47775 ** of available reader locks and should be at least 3.
   47776 */
   47777 #define WAL_WRITE_LOCK         0
   47778 #define WAL_ALL_BUT_WRITE      1
   47779 #define WAL_CKPT_LOCK          1
   47780 #define WAL_RECOVER_LOCK       2
   47781 #define WAL_READ_LOCK(I)       (3+(I))
   47782 #define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
   47783 
   47784 
   47785 /* Object declarations */
   47786 typedef struct WalIndexHdr WalIndexHdr;
   47787 typedef struct WalIterator WalIterator;
   47788 typedef struct WalCkptInfo WalCkptInfo;
   47789 
   47790 
   47791 /*
   47792 ** The following object holds a copy of the wal-index header content.
   47793 **
   47794 ** The actual header in the wal-index consists of two copies of this
   47795 ** object.
   47796 **
   47797 ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
   47798 ** Or it can be 1 to represent a 65536-byte page.  The latter case was
   47799 ** added in 3.7.1 when support for 64K pages was added.
   47800 */
   47801 struct WalIndexHdr {
   47802   u32 iVersion;                   /* Wal-index version */
   47803   u32 unused;                     /* Unused (padding) field */
   47804   u32 iChange;                    /* Counter incremented each transaction */
   47805   u8 isInit;                      /* 1 when initialized */
   47806   u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
   47807   u16 szPage;                     /* Database page size in bytes. 1==64K */
   47808   u32 mxFrame;                    /* Index of last valid frame in the WAL */
   47809   u32 nPage;                      /* Size of database in pages */
   47810   u32 aFrameCksum[2];             /* Checksum of last frame in log */
   47811   u32 aSalt[2];                   /* Two salt values copied from WAL header */
   47812   u32 aCksum[2];                  /* Checksum over all prior fields */
   47813 };
   47814 
   47815 /*
   47816 ** A copy of the following object occurs in the wal-index immediately
   47817 ** following the second copy of the WalIndexHdr.  This object stores
   47818 ** information used by checkpoint.
   47819 **
   47820 ** nBackfill is the number of frames in the WAL that have been written
   47821 ** back into the database. (We call the act of moving content from WAL to
   47822 ** database "backfilling".)  The nBackfill number is never greater than
   47823 ** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
   47824 ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
   47825 ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
   47826 ** mxFrame back to zero when the WAL is reset.
   47827 **
   47828 ** There is one entry in aReadMark[] for each reader lock.  If a reader
   47829 ** holds read-lock K, then the value in aReadMark[K] is no greater than
   47830 ** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
   47831 ** for any aReadMark[] means that entry is unused.  aReadMark[0] is
   47832 ** a special case; its value is never used and it exists as a place-holder
   47833 ** to avoid having to offset aReadMark[] indexs by one.  Readers holding
   47834 ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
   47835 ** directly from the database.
   47836 **
   47837 ** The value of aReadMark[K] may only be changed by a thread that
   47838 ** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
   47839 ** aReadMark[K] cannot changed while there is a reader is using that mark
   47840 ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
   47841 **
   47842 ** The checkpointer may only transfer frames from WAL to database where
   47843 ** the frame numbers are less than or equal to every aReadMark[] that is
   47844 ** in use (that is, every aReadMark[j] for which there is a corresponding
   47845 ** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
   47846 ** largest value and will increase an unused aReadMark[] to mxFrame if there
   47847 ** is not already an aReadMark[] equal to mxFrame.  The exception to the
   47848 ** previous sentence is when nBackfill equals mxFrame (meaning that everything
   47849 ** in the WAL has been backfilled into the database) then new readers
   47850 ** will choose aReadMark[0] which has value 0 and hence such reader will
   47851 ** get all their all content directly from the database file and ignore
   47852 ** the WAL.
   47853 **
   47854 ** Writers normally append new frames to the end of the WAL.  However,
   47855 ** if nBackfill equals mxFrame (meaning that all WAL content has been
   47856 ** written back into the database) and if no readers are using the WAL
   47857 ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
   47858 ** the writer will first "reset" the WAL back to the beginning and start
   47859 ** writing new content beginning at frame 1.
   47860 **
   47861 ** We assume that 32-bit loads are atomic and so no locks are needed in
   47862 ** order to read from any aReadMark[] entries.
   47863 */
   47864 struct WalCkptInfo {
   47865   u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
   47866   u32 aReadMark[WAL_NREADER];     /* Reader marks */
   47867 };
   47868 #define READMARK_NOT_USED  0xffffffff
   47869 
   47870 
   47871 /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
   47872 ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
   47873 ** only support mandatory file-locks, we do not read or write data
   47874 ** from the region of the file on which locks are applied.
   47875 */
   47876 #define WALINDEX_LOCK_OFFSET   (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
   47877 #define WALINDEX_LOCK_RESERVED 16
   47878 #define WALINDEX_HDR_SIZE      (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
   47879 
   47880 /* Size of header before each frame in wal */
   47881 #define WAL_FRAME_HDRSIZE 24
   47882 
   47883 /* Size of write ahead log header, including checksum. */
   47884 /* #define WAL_HDRSIZE 24 */
   47885 #define WAL_HDRSIZE 32
   47886 
   47887 /* WAL magic value. Either this value, or the same value with the least
   47888 ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
   47889 ** big-endian format in the first 4 bytes of a WAL file.
   47890 **
   47891 ** If the LSB is set, then the checksums for each frame within the WAL
   47892 ** file are calculated by treating all data as an array of 32-bit
   47893 ** big-endian words. Otherwise, they are calculated by interpreting
   47894 ** all data as 32-bit little-endian words.
   47895 */
   47896 #define WAL_MAGIC 0x377f0682
   47897 
   47898 /*
   47899 ** Return the offset of frame iFrame in the write-ahead log file,
   47900 ** assuming a database page size of szPage bytes. The offset returned
   47901 ** is to the start of the write-ahead log frame-header.
   47902 */
   47903 #define walFrameOffset(iFrame, szPage) (                               \
   47904   WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
   47905 )
   47906 
   47907 /*
   47908 ** An open write-ahead log file is represented by an instance of the
   47909 ** following object.
   47910 */
   47911 struct Wal {
   47912   sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
   47913   sqlite3_file *pDbFd;       /* File handle for the database file */
   47914   sqlite3_file *pWalFd;      /* File handle for WAL file */
   47915   u32 iCallback;             /* Value to pass to log callback (or 0) */
   47916   i64 mxWalSize;             /* Truncate WAL to this size upon reset */
   47917   int nWiData;               /* Size of array apWiData */
   47918   int szFirstBlock;          /* Size of first block written to WAL file */
   47919   volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
   47920   u32 szPage;                /* Database page size */
   47921   i16 readLock;              /* Which read lock is being held.  -1 for none */
   47922   u8 syncFlags;              /* Flags to use to sync header writes */
   47923   u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
   47924   u8 writeLock;              /* True if in a write transaction */
   47925   u8 ckptLock;               /* True if holding a checkpoint lock */
   47926   u8 readOnly;               /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
   47927   u8 truncateOnCommit;       /* True to truncate WAL file on commit */
   47928   u8 syncHeader;             /* Fsync the WAL header if true */
   47929   u8 padToSectorBoundary;    /* Pad transactions out to the next sector */
   47930   WalIndexHdr hdr;           /* Wal-index header for current transaction */
   47931   const char *zWalName;      /* Name of WAL file */
   47932   u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
   47933 #ifdef SQLITE_DEBUG
   47934   u8 lockError;              /* True if a locking error has occurred */
   47935 #endif
   47936 };
   47937 
   47938 /*
   47939 ** Candidate values for Wal.exclusiveMode.
   47940 */
   47941 #define WAL_NORMAL_MODE     0
   47942 #define WAL_EXCLUSIVE_MODE  1
   47943 #define WAL_HEAPMEMORY_MODE 2
   47944 
   47945 /*
   47946 ** Possible values for WAL.readOnly
   47947 */
   47948 #define WAL_RDWR        0    /* Normal read/write connection */
   47949 #define WAL_RDONLY      1    /* The WAL file is readonly */
   47950 #define WAL_SHM_RDONLY  2    /* The SHM file is readonly */
   47951 
   47952 /*
   47953 ** Each page of the wal-index mapping contains a hash-table made up of
   47954 ** an array of HASHTABLE_NSLOT elements of the following type.
   47955 */
   47956 typedef u16 ht_slot;
   47957 
   47958 /*
   47959 ** This structure is used to implement an iterator that loops through
   47960 ** all frames in the WAL in database page order. Where two or more frames
   47961 ** correspond to the same database page, the iterator visits only the
   47962 ** frame most recently written to the WAL (in other words, the frame with
   47963 ** the largest index).
   47964 **
   47965 ** The internals of this structure are only accessed by:
   47966 **
   47967 **   walIteratorInit() - Create a new iterator,
   47968 **   walIteratorNext() - Step an iterator,
   47969 **   walIteratorFree() - Free an iterator.
   47970 **
   47971 ** This functionality is used by the checkpoint code (see walCheckpoint()).
   47972 */
   47973 struct WalIterator {
   47974   int iPrior;                     /* Last result returned from the iterator */
   47975   int nSegment;                   /* Number of entries in aSegment[] */
   47976   struct WalSegment {
   47977     int iNext;                    /* Next slot in aIndex[] not yet returned */
   47978     ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
   47979     u32 *aPgno;                   /* Array of page numbers. */
   47980     int nEntry;                   /* Nr. of entries in aPgno[] and aIndex[] */
   47981     int iZero;                    /* Frame number associated with aPgno[0] */
   47982   } aSegment[1];                  /* One for every 32KB page in the wal-index */
   47983 };
   47984 
   47985 /*
   47986 ** Define the parameters of the hash tables in the wal-index file. There
   47987 ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
   47988 ** wal-index.
   47989 **
   47990 ** Changing any of these constants will alter the wal-index format and
   47991 ** create incompatibilities.
   47992 */
   47993 #define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
   47994 #define HASHTABLE_HASH_1     383                  /* Should be prime */
   47995 #define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
   47996 
   47997 /*
   47998 ** The block of page numbers associated with the first hash-table in a
   47999 ** wal-index is smaller than usual. This is so that there is a complete
   48000 ** hash-table on each aligned 32KB page of the wal-index.
   48001 */
   48002 #define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
   48003 
   48004 /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
   48005 #define WALINDEX_PGSZ   (                                         \
   48006     sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
   48007 )
   48008 
   48009 /*
   48010 ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
   48011 ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
   48012 ** numbered from zero.
   48013 **
   48014 ** If this call is successful, *ppPage is set to point to the wal-index
   48015 ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
   48016 ** then an SQLite error code is returned and *ppPage is set to 0.
   48017 */
   48018 static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
   48019   int rc = SQLITE_OK;
   48020 
   48021   /* Enlarge the pWal->apWiData[] array if required */
   48022   if( pWal->nWiData<=iPage ){
   48023     int nByte = sizeof(u32*)*(iPage+1);
   48024     volatile u32 **apNew;
   48025     apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
   48026     if( !apNew ){
   48027       *ppPage = 0;
   48028       return SQLITE_NOMEM;
   48029     }
   48030     memset((void*)&apNew[pWal->nWiData], 0,
   48031            sizeof(u32*)*(iPage+1-pWal->nWiData));
   48032     pWal->apWiData = apNew;
   48033     pWal->nWiData = iPage+1;
   48034   }
   48035 
   48036   /* Request a pointer to the required page from the VFS */
   48037   if( pWal->apWiData[iPage]==0 ){
   48038     if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
   48039       pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
   48040       if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
   48041     }else{
   48042       rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
   48043           pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
   48044       );
   48045       if( rc==SQLITE_READONLY ){
   48046         pWal->readOnly |= WAL_SHM_RDONLY;
   48047         rc = SQLITE_OK;
   48048       }
   48049     }
   48050   }
   48051 
   48052   *ppPage = pWal->apWiData[iPage];
   48053   assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
   48054   return rc;
   48055 }
   48056 
   48057 /*
   48058 ** Return a pointer to the WalCkptInfo structure in the wal-index.
   48059 */
   48060 static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
   48061   assert( pWal->nWiData>0 && pWal->apWiData[0] );
   48062   return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
   48063 }
   48064 
   48065 /*
   48066 ** Return a pointer to the WalIndexHdr structure in the wal-index.
   48067 */
   48068 static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
   48069   assert( pWal->nWiData>0 && pWal->apWiData[0] );
   48070   return (volatile WalIndexHdr*)pWal->apWiData[0];
   48071 }
   48072 
   48073 /*
   48074 ** The argument to this macro must be of type u32. On a little-endian
   48075 ** architecture, it returns the u32 value that results from interpreting
   48076 ** the 4 bytes as a big-endian value. On a big-endian architecture, it
   48077 ** returns the value that would be produced by intepreting the 4 bytes
   48078 ** of the input value as a little-endian integer.
   48079 */
   48080 #define BYTESWAP32(x) ( \
   48081     (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
   48082   + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
   48083 )
   48084 
   48085 /*
   48086 ** Generate or extend an 8 byte checksum based on the data in
   48087 ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
   48088 ** initial values of 0 and 0 if aIn==NULL).
   48089 **
   48090 ** The checksum is written back into aOut[] before returning.
   48091 **
   48092 ** nByte must be a positive multiple of 8.
   48093 */
   48094 static void walChecksumBytes(
   48095   int nativeCksum, /* True for native byte-order, false for non-native */
   48096   u8 *a,           /* Content to be checksummed */
   48097   int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
   48098   const u32 *aIn,  /* Initial checksum value input */
   48099   u32 *aOut        /* OUT: Final checksum value output */
   48100 ){
   48101   u32 s1, s2;
   48102   u32 *aData = (u32 *)a;
   48103   u32 *aEnd = (u32 *)&a[nByte];
   48104 
   48105   if( aIn ){
   48106     s1 = aIn[0];
   48107     s2 = aIn[1];
   48108   }else{
   48109     s1 = s2 = 0;
   48110   }
   48111 
   48112   assert( nByte>=8 );
   48113   assert( (nByte&0x00000007)==0 );
   48114 
   48115   if( nativeCksum ){
   48116     do {
   48117       s1 += *aData++ + s2;
   48118       s2 += *aData++ + s1;
   48119     }while( aData<aEnd );
   48120   }else{
   48121     do {
   48122       s1 += BYTESWAP32(aData[0]) + s2;
   48123       s2 += BYTESWAP32(aData[1]) + s1;
   48124       aData += 2;
   48125     }while( aData<aEnd );
   48126   }
   48127 
   48128   aOut[0] = s1;
   48129   aOut[1] = s2;
   48130 }
   48131 
   48132 static void walShmBarrier(Wal *pWal){
   48133   if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
   48134     sqlite3OsShmBarrier(pWal->pDbFd);
   48135   }
   48136 }
   48137 
   48138 /*
   48139 ** Write the header information in pWal->hdr into the wal-index.
   48140 **
   48141 ** The checksum on pWal->hdr is updated before it is written.
   48142 */
   48143 static void walIndexWriteHdr(Wal *pWal){
   48144   volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
   48145   const int nCksum = offsetof(WalIndexHdr, aCksum);
   48146 
   48147   assert( pWal->writeLock );
   48148   pWal->hdr.isInit = 1;
   48149   pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
   48150   walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
   48151   memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
   48152   walShmBarrier(pWal);
   48153   memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
   48154 }
   48155 
   48156 /*
   48157 ** This function encodes a single frame header and writes it to a buffer
   48158 ** supplied by the caller. A frame-header is made up of a series of
   48159 ** 4-byte big-endian integers, as follows:
   48160 **
   48161 **     0: Page number.
   48162 **     4: For commit records, the size of the database image in pages
   48163 **        after the commit. For all other records, zero.
   48164 **     8: Salt-1 (copied from the wal-header)
   48165 **    12: Salt-2 (copied from the wal-header)
   48166 **    16: Checksum-1.
   48167 **    20: Checksum-2.
   48168 */
   48169 static void walEncodeFrame(
   48170   Wal *pWal,                      /* The write-ahead log */
   48171   u32 iPage,                      /* Database page number for frame */
   48172   u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
   48173   u8 *aData,                      /* Pointer to page data */
   48174   u8 *aFrame                      /* OUT: Write encoded frame here */
   48175 ){
   48176   int nativeCksum;                /* True for native byte-order checksums */
   48177   u32 *aCksum = pWal->hdr.aFrameCksum;
   48178   assert( WAL_FRAME_HDRSIZE==24 );
   48179   sqlite3Put4byte(&aFrame[0], iPage);
   48180   sqlite3Put4byte(&aFrame[4], nTruncate);
   48181   memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
   48182 
   48183   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
   48184   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
   48185   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
   48186 
   48187   sqlite3Put4byte(&aFrame[16], aCksum[0]);
   48188   sqlite3Put4byte(&aFrame[20], aCksum[1]);
   48189 }
   48190 
   48191 /*
   48192 ** Check to see if the frame with header in aFrame[] and content
   48193 ** in aData[] is valid.  If it is a valid frame, fill *piPage and
   48194 ** *pnTruncate and return true.  Return if the frame is not valid.
   48195 */
   48196 static int walDecodeFrame(
   48197   Wal *pWal,                      /* The write-ahead log */
   48198   u32 *piPage,                    /* OUT: Database page number for frame */
   48199   u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
   48200   u8 *aData,                      /* Pointer to page data (for checksum) */
   48201   u8 *aFrame                      /* Frame data */
   48202 ){
   48203   int nativeCksum;                /* True for native byte-order checksums */
   48204   u32 *aCksum = pWal->hdr.aFrameCksum;
   48205   u32 pgno;                       /* Page number of the frame */
   48206   assert( WAL_FRAME_HDRSIZE==24 );
   48207 
   48208   /* A frame is only valid if the salt values in the frame-header
   48209   ** match the salt values in the wal-header.
   48210   */
   48211   if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
   48212     return 0;
   48213   }
   48214 
   48215   /* A frame is only valid if the page number is creater than zero.
   48216   */
   48217   pgno = sqlite3Get4byte(&aFrame[0]);
   48218   if( pgno==0 ){
   48219     return 0;
   48220   }
   48221 
   48222   /* A frame is only valid if a checksum of the WAL header,
   48223   ** all prior frams, the first 16 bytes of this frame-header,
   48224   ** and the frame-data matches the checksum in the last 8
   48225   ** bytes of this frame-header.
   48226   */
   48227   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
   48228   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
   48229   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
   48230   if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
   48231    || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
   48232   ){
   48233     /* Checksum failed. */
   48234     return 0;
   48235   }
   48236 
   48237   /* If we reach this point, the frame is valid.  Return the page number
   48238   ** and the new database size.
   48239   */
   48240   *piPage = pgno;
   48241   *pnTruncate = sqlite3Get4byte(&aFrame[4]);
   48242   return 1;
   48243 }
   48244 
   48245 
   48246 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
   48247 /*
   48248 ** Names of locks.  This routine is used to provide debugging output and is not
   48249 ** a part of an ordinary build.
   48250 */
   48251 static const char *walLockName(int lockIdx){
   48252   if( lockIdx==WAL_WRITE_LOCK ){
   48253     return "WRITE-LOCK";
   48254   }else if( lockIdx==WAL_CKPT_LOCK ){
   48255     return "CKPT-LOCK";
   48256   }else if( lockIdx==WAL_RECOVER_LOCK ){
   48257     return "RECOVER-LOCK";
   48258   }else{
   48259     static char zName[15];
   48260     sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
   48261                      lockIdx-WAL_READ_LOCK(0));
   48262     return zName;
   48263   }
   48264 }
   48265 #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
   48266 
   48267 
   48268 /*
   48269 ** Set or release locks on the WAL.  Locks are either shared or exclusive.
   48270 ** A lock cannot be moved directly between shared and exclusive - it must go
   48271 ** through the unlocked state first.
   48272 **
   48273 ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
   48274 */
   48275 static int walLockShared(Wal *pWal, int lockIdx){
   48276   int rc;
   48277   if( pWal->exclusiveMode ) return SQLITE_OK;
   48278   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
   48279                         SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
   48280   WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
   48281             walLockName(lockIdx), rc ? "failed" : "ok"));
   48282   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
   48283   return rc;
   48284 }
   48285 static void walUnlockShared(Wal *pWal, int lockIdx){
   48286   if( pWal->exclusiveMode ) return;
   48287   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
   48288                          SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
   48289   WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
   48290 }
   48291 static int walLockExclusive(Wal *pWal, int lockIdx, int n){
   48292   int rc;
   48293   if( pWal->exclusiveMode ) return SQLITE_OK;
   48294   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
   48295                         SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
   48296   WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
   48297             walLockName(lockIdx), n, rc ? "failed" : "ok"));
   48298   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
   48299   return rc;
   48300 }
   48301 static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
   48302   if( pWal->exclusiveMode ) return;
   48303   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
   48304                          SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
   48305   WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
   48306              walLockName(lockIdx), n));
   48307 }
   48308 
   48309 /*
   48310 ** Compute a hash on a page number.  The resulting hash value must land
   48311 ** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
   48312 ** the hash to the next value in the event of a collision.
   48313 */
   48314 static int walHash(u32 iPage){
   48315   assert( iPage>0 );
   48316   assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
   48317   return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
   48318 }
   48319 static int walNextHash(int iPriorHash){
   48320   return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
   48321 }
   48322 
   48323 /*
   48324 ** Return pointers to the hash table and page number array stored on
   48325 ** page iHash of the wal-index. The wal-index is broken into 32KB pages
   48326 ** numbered starting from 0.
   48327 **
   48328 ** Set output variable *paHash to point to the start of the hash table
   48329 ** in the wal-index file. Set *piZero to one less than the frame
   48330 ** number of the first frame indexed by this hash table. If a
   48331 ** slot in the hash table is set to N, it refers to frame number
   48332 ** (*piZero+N) in the log.
   48333 **
   48334 ** Finally, set *paPgno so that *paPgno[1] is the page number of the
   48335 ** first frame indexed by the hash table, frame (*piZero+1).
   48336 */
   48337 static int walHashGet(
   48338   Wal *pWal,                      /* WAL handle */
   48339   int iHash,                      /* Find the iHash'th table */
   48340   volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
   48341   volatile u32 **paPgno,          /* OUT: Pointer to page number array */
   48342   u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
   48343 ){
   48344   int rc;                         /* Return code */
   48345   volatile u32 *aPgno;
   48346 
   48347   rc = walIndexPage(pWal, iHash, &aPgno);
   48348   assert( rc==SQLITE_OK || iHash>0 );
   48349 
   48350   if( rc==SQLITE_OK ){
   48351     u32 iZero;
   48352     volatile ht_slot *aHash;
   48353 
   48354     aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
   48355     if( iHash==0 ){
   48356       aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
   48357       iZero = 0;
   48358     }else{
   48359       iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
   48360     }
   48361 
   48362     *paPgno = &aPgno[-1];
   48363     *paHash = aHash;
   48364     *piZero = iZero;
   48365   }
   48366   return rc;
   48367 }
   48368 
   48369 /*
   48370 ** Return the number of the wal-index page that contains the hash-table
   48371 ** and page-number array that contain entries corresponding to WAL frame
   48372 ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
   48373 ** are numbered starting from 0.
   48374 */
   48375 static int walFramePage(u32 iFrame){
   48376   int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
   48377   assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
   48378        && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
   48379        && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
   48380        && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
   48381        && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
   48382   );
   48383   return iHash;
   48384 }
   48385 
   48386 /*
   48387 ** Return the page number associated with frame iFrame in this WAL.
   48388 */
   48389 static u32 walFramePgno(Wal *pWal, u32 iFrame){
   48390   int iHash = walFramePage(iFrame);
   48391   if( iHash==0 ){
   48392     return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
   48393   }
   48394   return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
   48395 }
   48396 
   48397 /*
   48398 ** Remove entries from the hash table that point to WAL slots greater
   48399 ** than pWal->hdr.mxFrame.
   48400 **
   48401 ** This function is called whenever pWal->hdr.mxFrame is decreased due
   48402 ** to a rollback or savepoint.
   48403 **
   48404 ** At most only the hash table containing pWal->hdr.mxFrame needs to be
   48405 ** updated.  Any later hash tables will be automatically cleared when
   48406 ** pWal->hdr.mxFrame advances to the point where those hash tables are
   48407 ** actually needed.
   48408 */
   48409 static void walCleanupHash(Wal *pWal){
   48410   volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
   48411   volatile u32 *aPgno = 0;        /* Page number array for hash table */
   48412   u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
   48413   int iLimit = 0;                 /* Zero values greater than this */
   48414   int nByte;                      /* Number of bytes to zero in aPgno[] */
   48415   int i;                          /* Used to iterate through aHash[] */
   48416 
   48417   assert( pWal->writeLock );
   48418   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
   48419   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
   48420   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
   48421 
   48422   if( pWal->hdr.mxFrame==0 ) return;
   48423 
   48424   /* Obtain pointers to the hash-table and page-number array containing
   48425   ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
   48426   ** that the page said hash-table and array reside on is already mapped.
   48427   */
   48428   assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
   48429   assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
   48430   walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
   48431 
   48432   /* Zero all hash-table entries that correspond to frame numbers greater
   48433   ** than pWal->hdr.mxFrame.
   48434   */
   48435   iLimit = pWal->hdr.mxFrame - iZero;
   48436   assert( iLimit>0 );
   48437   for(i=0; i<HASHTABLE_NSLOT; i++){
   48438     if( aHash[i]>iLimit ){
   48439       aHash[i] = 0;
   48440     }
   48441   }
   48442 
   48443   /* Zero the entries in the aPgno array that correspond to frames with
   48444   ** frame numbers greater than pWal->hdr.mxFrame.
   48445   */
   48446   nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
   48447   memset((void *)&aPgno[iLimit+1], 0, nByte);
   48448 
   48449 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
   48450   /* Verify that the every entry in the mapping region is still reachable
   48451   ** via the hash table even after the cleanup.
   48452   */
   48453   if( iLimit ){
   48454     int i;           /* Loop counter */
   48455     int iKey;        /* Hash key */
   48456     for(i=1; i<=iLimit; i++){
   48457       for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
   48458         if( aHash[iKey]==i ) break;
   48459       }
   48460       assert( aHash[iKey]==i );
   48461     }
   48462   }
   48463 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
   48464 }
   48465 
   48466 
   48467 /*
   48468 ** Set an entry in the wal-index that will map database page number
   48469 ** pPage into WAL frame iFrame.
   48470 */
   48471 static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
   48472   int rc;                         /* Return code */
   48473   u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
   48474   volatile u32 *aPgno = 0;        /* Page number array */
   48475   volatile ht_slot *aHash = 0;    /* Hash table */
   48476 
   48477   rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
   48478 
   48479   /* Assuming the wal-index file was successfully mapped, populate the
   48480   ** page number array and hash table entry.
   48481   */
   48482   if( rc==SQLITE_OK ){
   48483     int iKey;                     /* Hash table key */
   48484     int idx;                      /* Value to write to hash-table slot */
   48485     int nCollide;                 /* Number of hash collisions */
   48486 
   48487     idx = iFrame - iZero;
   48488     assert( idx <= HASHTABLE_NSLOT/2 + 1 );
   48489 
   48490     /* If this is the first entry to be added to this hash-table, zero the
   48491     ** entire hash table and aPgno[] array before proceding.
   48492     */
   48493     if( idx==1 ){
   48494       int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
   48495       memset((void*)&aPgno[1], 0, nByte);
   48496     }
   48497 
   48498     /* If the entry in aPgno[] is already set, then the previous writer
   48499     ** must have exited unexpectedly in the middle of a transaction (after
   48500     ** writing one or more dirty pages to the WAL to free up memory).
   48501     ** Remove the remnants of that writers uncommitted transaction from
   48502     ** the hash-table before writing any new entries.
   48503     */
   48504     if( aPgno[idx] ){
   48505       walCleanupHash(pWal);
   48506       assert( !aPgno[idx] );
   48507     }
   48508 
   48509     /* Write the aPgno[] array entry and the hash-table slot. */
   48510     nCollide = idx;
   48511     for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
   48512       if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
   48513     }
   48514     aPgno[idx] = iPage;
   48515     aHash[iKey] = (ht_slot)idx;
   48516 
   48517 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
   48518     /* Verify that the number of entries in the hash table exactly equals
   48519     ** the number of entries in the mapping region.
   48520     */
   48521     {
   48522       int i;           /* Loop counter */
   48523       int nEntry = 0;  /* Number of entries in the hash table */
   48524       for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
   48525       assert( nEntry==idx );
   48526     }
   48527 
   48528     /* Verify that the every entry in the mapping region is reachable
   48529     ** via the hash table.  This turns out to be a really, really expensive
   48530     ** thing to check, so only do this occasionally - not on every
   48531     ** iteration.
   48532     */
   48533     if( (idx&0x3ff)==0 ){
   48534       int i;           /* Loop counter */
   48535       for(i=1; i<=idx; i++){
   48536         for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
   48537           if( aHash[iKey]==i ) break;
   48538         }
   48539         assert( aHash[iKey]==i );
   48540       }
   48541     }
   48542 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
   48543   }
   48544 
   48545 
   48546   return rc;
   48547 }
   48548 
   48549 
   48550 /*
   48551 ** Recover the wal-index by reading the write-ahead log file.
   48552 **
   48553 ** This routine first tries to establish an exclusive lock on the
   48554 ** wal-index to prevent other threads/processes from doing anything
   48555 ** with the WAL or wal-index while recovery is running.  The
   48556 ** WAL_RECOVER_LOCK is also held so that other threads will know
   48557 ** that this thread is running recovery.  If unable to establish
   48558 ** the necessary locks, this routine returns SQLITE_BUSY.
   48559 */
   48560 static int walIndexRecover(Wal *pWal){
   48561   int rc;                         /* Return Code */
   48562   i64 nSize;                      /* Size of log file */
   48563   u32 aFrameCksum[2] = {0, 0};
   48564   int iLock;                      /* Lock offset to lock for checkpoint */
   48565   int nLock;                      /* Number of locks to hold */
   48566 
   48567   /* Obtain an exclusive lock on all byte in the locking range not already
   48568   ** locked by the caller. The caller is guaranteed to have locked the
   48569   ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
   48570   ** If successful, the same bytes that are locked here are unlocked before
   48571   ** this function returns.
   48572   */
   48573   assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
   48574   assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
   48575   assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
   48576   assert( pWal->writeLock );
   48577   iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
   48578   nLock = SQLITE_SHM_NLOCK - iLock;
   48579   rc = walLockExclusive(pWal, iLock, nLock);
   48580   if( rc ){
   48581     return rc;
   48582   }
   48583   WALTRACE(("WAL%p: recovery begin...\n", pWal));
   48584 
   48585   memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
   48586 
   48587   rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
   48588   if( rc!=SQLITE_OK ){
   48589     goto recovery_error;
   48590   }
   48591 
   48592   if( nSize>WAL_HDRSIZE ){
   48593     u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
   48594     u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
   48595     int szFrame;                  /* Number of bytes in buffer aFrame[] */
   48596     u8 *aData;                    /* Pointer to data part of aFrame buffer */
   48597     int iFrame;                   /* Index of last frame read */
   48598     i64 iOffset;                  /* Next offset to read from log file */
   48599     int szPage;                   /* Page size according to the log */
   48600     u32 magic;                    /* Magic value read from WAL header */
   48601     u32 version;                  /* Magic value read from WAL header */
   48602     int isValid;                  /* True if this frame is valid */
   48603 
   48604     /* Read in the WAL header. */
   48605     rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
   48606     if( rc!=SQLITE_OK ){
   48607       goto recovery_error;
   48608     }
   48609 
   48610     /* If the database page size is not a power of two, or is greater than
   48611     ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
   48612     ** data. Similarly, if the 'magic' value is invalid, ignore the whole
   48613     ** WAL file.
   48614     */
   48615     magic = sqlite3Get4byte(&aBuf[0]);
   48616     szPage = sqlite3Get4byte(&aBuf[8]);
   48617     if( (magic&0xFFFFFFFE)!=WAL_MAGIC
   48618      || szPage&(szPage-1)
   48619      || szPage>SQLITE_MAX_PAGE_SIZE
   48620      || szPage<512
   48621     ){
   48622       goto finished;
   48623     }
   48624     pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
   48625     pWal->szPage = szPage;
   48626     pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
   48627     memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
   48628 
   48629     /* Verify that the WAL header checksum is correct */
   48630     walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
   48631         aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
   48632     );
   48633     if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
   48634      || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
   48635     ){
   48636       goto finished;
   48637     }
   48638 
   48639     /* Verify that the version number on the WAL format is one that
   48640     ** are able to understand */
   48641     version = sqlite3Get4byte(&aBuf[4]);
   48642     if( version!=WAL_MAX_VERSION ){
   48643       rc = SQLITE_CANTOPEN_BKPT;
   48644       goto finished;
   48645     }
   48646 
   48647     /* Malloc a buffer to read frames into. */
   48648     szFrame = szPage + WAL_FRAME_HDRSIZE;
   48649     aFrame = (u8 *)sqlite3_malloc(szFrame);
   48650     if( !aFrame ){
   48651       rc = SQLITE_NOMEM;
   48652       goto recovery_error;
   48653     }
   48654     aData = &aFrame[WAL_FRAME_HDRSIZE];
   48655 
   48656     /* Read all frames from the log file. */
   48657     iFrame = 0;
   48658     for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
   48659       u32 pgno;                   /* Database page number for frame */
   48660       u32 nTruncate;              /* dbsize field from frame header */
   48661 
   48662       /* Read and decode the next log frame. */
   48663       iFrame++;
   48664       rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
   48665       if( rc!=SQLITE_OK ) break;
   48666       isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
   48667       if( !isValid ) break;
   48668       rc = walIndexAppend(pWal, iFrame, pgno);
   48669       if( rc!=SQLITE_OK ) break;
   48670 
   48671       /* If nTruncate is non-zero, this is a commit record. */
   48672       if( nTruncate ){
   48673         pWal->hdr.mxFrame = iFrame;
   48674         pWal->hdr.nPage = nTruncate;
   48675         pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
   48676         testcase( szPage<=32768 );
   48677         testcase( szPage>=65536 );
   48678         aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
   48679         aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
   48680       }
   48681     }
   48682 
   48683     sqlite3_free(aFrame);
   48684   }
   48685 
   48686 finished:
   48687   if( rc==SQLITE_OK ){
   48688     volatile WalCkptInfo *pInfo;
   48689     int i;
   48690     pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
   48691     pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
   48692     walIndexWriteHdr(pWal);
   48693 
   48694     /* Reset the checkpoint-header. This is safe because this thread is
   48695     ** currently holding locks that exclude all other readers, writers and
   48696     ** checkpointers.
   48697     */
   48698     pInfo = walCkptInfo(pWal);
   48699     pInfo->nBackfill = 0;
   48700     pInfo->aReadMark[0] = 0;
   48701     for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
   48702     if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
   48703 
   48704     /* If more than one frame was recovered from the log file, report an
   48705     ** event via sqlite3_log(). This is to help with identifying performance
   48706     ** problems caused by applications routinely shutting down without
   48707     ** checkpointing the log file.
   48708     */
   48709     if( pWal->hdr.nPage ){
   48710       sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
   48711           "recovered %d frames from WAL file %s",
   48712           pWal->hdr.mxFrame, pWal->zWalName
   48713       );
   48714     }
   48715   }
   48716 
   48717 recovery_error:
   48718   WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
   48719   walUnlockExclusive(pWal, iLock, nLock);
   48720   return rc;
   48721 }
   48722 
   48723 /*
   48724 ** Close an open wal-index.
   48725 */
   48726 static void walIndexClose(Wal *pWal, int isDelete){
   48727   if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
   48728     int i;
   48729     for(i=0; i<pWal->nWiData; i++){
   48730       sqlite3_free((void *)pWal->apWiData[i]);
   48731       pWal->apWiData[i] = 0;
   48732     }
   48733   }else{
   48734     sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
   48735   }
   48736 }
   48737 
   48738 /*
   48739 ** Open a connection to the WAL file zWalName. The database file must
   48740 ** already be opened on connection pDbFd. The buffer that zWalName points
   48741 ** to must remain valid for the lifetime of the returned Wal* handle.
   48742 **
   48743 ** A SHARED lock should be held on the database file when this function
   48744 ** is called. The purpose of this SHARED lock is to prevent any other
   48745 ** client from unlinking the WAL or wal-index file. If another process
   48746 ** were to do this just after this client opened one of these files, the
   48747 ** system would be badly broken.
   48748 **
   48749 ** If the log file is successfully opened, SQLITE_OK is returned and
   48750 ** *ppWal is set to point to a new WAL handle. If an error occurs,
   48751 ** an SQLite error code is returned and *ppWal is left unmodified.
   48752 */
   48753 SQLITE_PRIVATE int sqlite3WalOpen(
   48754   sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
   48755   sqlite3_file *pDbFd,            /* The open database file */
   48756   const char *zWalName,           /* Name of the WAL file */
   48757   int bNoShm,                     /* True to run in heap-memory mode */
   48758   i64 mxWalSize,                  /* Truncate WAL to this size on reset */
   48759   Wal **ppWal                     /* OUT: Allocated Wal handle */
   48760 ){
   48761   int rc;                         /* Return Code */
   48762   Wal *pRet;                      /* Object to allocate and return */
   48763   int flags;                      /* Flags passed to OsOpen() */
   48764 
   48765   assert( zWalName && zWalName[0] );
   48766   assert( pDbFd );
   48767 
   48768   /* In the amalgamation, the os_unix.c and os_win.c source files come before
   48769   ** this source file.  Verify that the #defines of the locking byte offsets
   48770   ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
   48771   */
   48772 #ifdef WIN_SHM_BASE
   48773   assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
   48774 #endif
   48775 #ifdef UNIX_SHM_BASE
   48776   assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
   48777 #endif
   48778 
   48779 
   48780   /* Allocate an instance of struct Wal to return. */
   48781   *ppWal = 0;
   48782   pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
   48783   if( !pRet ){
   48784     return SQLITE_NOMEM;
   48785   }
   48786 
   48787   pRet->pVfs = pVfs;
   48788   pRet->pWalFd = (sqlite3_file *)&pRet[1];
   48789   pRet->pDbFd = pDbFd;
   48790   pRet->readLock = -1;
   48791   pRet->mxWalSize = mxWalSize;
   48792   pRet->zWalName = zWalName;
   48793   pRet->syncHeader = 1;
   48794   pRet->padToSectorBoundary = 1;
   48795   pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
   48796 
   48797   /* Open file handle on the write-ahead log file. */
   48798   flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
   48799   rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
   48800   if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
   48801     pRet->readOnly = WAL_RDONLY;
   48802   }
   48803 
   48804   if( rc!=SQLITE_OK ){
   48805     walIndexClose(pRet, 0);
   48806     sqlite3OsClose(pRet->pWalFd);
   48807     sqlite3_free(pRet);
   48808   }else{
   48809     int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
   48810     if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
   48811     if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
   48812       pRet->padToSectorBoundary = 0;
   48813     }
   48814     *ppWal = pRet;
   48815     WALTRACE(("WAL%d: opened\n", pRet));
   48816   }
   48817   return rc;
   48818 }
   48819 
   48820 /*
   48821 ** Change the size to which the WAL file is trucated on each reset.
   48822 */
   48823 SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
   48824   if( pWal ) pWal->mxWalSize = iLimit;
   48825 }
   48826 
   48827 /*
   48828 ** Find the smallest page number out of all pages held in the WAL that
   48829 ** has not been returned by any prior invocation of this method on the
   48830 ** same WalIterator object.   Write into *piFrame the frame index where
   48831 ** that page was last written into the WAL.  Write into *piPage the page
   48832 ** number.
   48833 **
   48834 ** Return 0 on success.  If there are no pages in the WAL with a page
   48835 ** number larger than *piPage, then return 1.
   48836 */
   48837 static int walIteratorNext(
   48838   WalIterator *p,               /* Iterator */
   48839   u32 *piPage,                  /* OUT: The page number of the next page */
   48840   u32 *piFrame                  /* OUT: Wal frame index of next page */
   48841 ){
   48842   u32 iMin;                     /* Result pgno must be greater than iMin */
   48843   u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
   48844   int i;                        /* For looping through segments */
   48845 
   48846   iMin = p->iPrior;
   48847   assert( iMin<0xffffffff );
   48848   for(i=p->nSegment-1; i>=0; i--){
   48849     struct WalSegment *pSegment = &p->aSegment[i];
   48850     while( pSegment->iNext<pSegment->nEntry ){
   48851       u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
   48852       if( iPg>iMin ){
   48853         if( iPg<iRet ){
   48854           iRet = iPg;
   48855           *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
   48856         }
   48857         break;
   48858       }
   48859       pSegment->iNext++;
   48860     }
   48861   }
   48862 
   48863   *piPage = p->iPrior = iRet;
   48864   return (iRet==0xFFFFFFFF);
   48865 }
   48866 
   48867 /*
   48868 ** This function merges two sorted lists into a single sorted list.
   48869 **
   48870 ** aLeft[] and aRight[] are arrays of indices.  The sort key is
   48871 ** aContent[aLeft[]] and aContent[aRight[]].  Upon entry, the following
   48872 ** is guaranteed for all J<K:
   48873 **
   48874 **        aContent[aLeft[J]] < aContent[aLeft[K]]
   48875 **        aContent[aRight[J]] < aContent[aRight[K]]
   48876 **
   48877 ** This routine overwrites aRight[] with a new (probably longer) sequence
   48878 ** of indices such that the aRight[] contains every index that appears in
   48879 ** either aLeft[] or the old aRight[] and such that the second condition
   48880 ** above is still met.
   48881 **
   48882 ** The aContent[aLeft[X]] values will be unique for all X.  And the
   48883 ** aContent[aRight[X]] values will be unique too.  But there might be
   48884 ** one or more combinations of X and Y such that
   48885 **
   48886 **      aLeft[X]!=aRight[Y]  &&  aContent[aLeft[X]] == aContent[aRight[Y]]
   48887 **
   48888 ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
   48889 */
   48890 static void walMerge(
   48891   const u32 *aContent,            /* Pages in wal - keys for the sort */
   48892   ht_slot *aLeft,                 /* IN: Left hand input list */
   48893   int nLeft,                      /* IN: Elements in array *paLeft */
   48894   ht_slot **paRight,              /* IN/OUT: Right hand input list */
   48895   int *pnRight,                   /* IN/OUT: Elements in *paRight */
   48896   ht_slot *aTmp                   /* Temporary buffer */
   48897 ){
   48898   int iLeft = 0;                  /* Current index in aLeft */
   48899   int iRight = 0;                 /* Current index in aRight */
   48900   int iOut = 0;                   /* Current index in output buffer */
   48901   int nRight = *pnRight;
   48902   ht_slot *aRight = *paRight;
   48903 
   48904   assert( nLeft>0 && nRight>0 );
   48905   while( iRight<nRight || iLeft<nLeft ){
   48906     ht_slot logpage;
   48907     Pgno dbpage;
   48908 
   48909     if( (iLeft<nLeft)
   48910      && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
   48911     ){
   48912       logpage = aLeft[iLeft++];
   48913     }else{
   48914       logpage = aRight[iRight++];
   48915     }
   48916     dbpage = aContent[logpage];
   48917 
   48918     aTmp[iOut++] = logpage;
   48919     if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
   48920 
   48921     assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
   48922     assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
   48923   }
   48924 
   48925   *paRight = aLeft;
   48926   *pnRight = iOut;
   48927   memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
   48928 }
   48929 
   48930 /*
   48931 ** Sort the elements in list aList using aContent[] as the sort key.
   48932 ** Remove elements with duplicate keys, preferring to keep the
   48933 ** larger aList[] values.
   48934 **
   48935 ** The aList[] entries are indices into aContent[].  The values in
   48936 ** aList[] are to be sorted so that for all J<K:
   48937 **
   48938 **      aContent[aList[J]] < aContent[aList[K]]
   48939 **
   48940 ** For any X and Y such that
   48941 **
   48942 **      aContent[aList[X]] == aContent[aList[Y]]
   48943 **
   48944 ** Keep the larger of the two values aList[X] and aList[Y] and discard
   48945 ** the smaller.
   48946 */
   48947 static void walMergesort(
   48948   const u32 *aContent,            /* Pages in wal */
   48949   ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
   48950   ht_slot *aList,                 /* IN/OUT: List to sort */
   48951   int *pnList                     /* IN/OUT: Number of elements in aList[] */
   48952 ){
   48953   struct Sublist {
   48954     int nList;                    /* Number of elements in aList */
   48955     ht_slot *aList;               /* Pointer to sub-list content */
   48956   };
   48957 
   48958   const int nList = *pnList;      /* Size of input list */
   48959   int nMerge = 0;                 /* Number of elements in list aMerge */
   48960   ht_slot *aMerge = 0;            /* List to be merged */
   48961   int iList;                      /* Index into input list */
   48962   int iSub = 0;                   /* Index into aSub array */
   48963   struct Sublist aSub[13];        /* Array of sub-lists */
   48964 
   48965   memset(aSub, 0, sizeof(aSub));
   48966   assert( nList<=HASHTABLE_NPAGE && nList>0 );
   48967   assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
   48968 
   48969   for(iList=0; iList<nList; iList++){
   48970     nMerge = 1;
   48971     aMerge = &aList[iList];
   48972     for(iSub=0; iList & (1<<iSub); iSub++){
   48973       struct Sublist *p = &aSub[iSub];
   48974       assert( p->aList && p->nList<=(1<<iSub) );
   48975       assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
   48976       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
   48977     }
   48978     aSub[iSub].aList = aMerge;
   48979     aSub[iSub].nList = nMerge;
   48980   }
   48981 
   48982   for(iSub++; iSub<ArraySize(aSub); iSub++){
   48983     if( nList & (1<<iSub) ){
   48984       struct Sublist *p = &aSub[iSub];
   48985       assert( p->nList<=(1<<iSub) );
   48986       assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
   48987       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
   48988     }
   48989   }
   48990   assert( aMerge==aList );
   48991   *pnList = nMerge;
   48992 
   48993 #ifdef SQLITE_DEBUG
   48994   {
   48995     int i;
   48996     for(i=1; i<*pnList; i++){
   48997       assert( aContent[aList[i]] > aContent[aList[i-1]] );
   48998     }
   48999   }
   49000 #endif
   49001 }
   49002 
   49003 /*
   49004 ** Free an iterator allocated by walIteratorInit().
   49005 */
   49006 static void walIteratorFree(WalIterator *p){
   49007   sqlite3ScratchFree(p);
   49008 }
   49009 
   49010 /*
   49011 ** Construct a WalInterator object that can be used to loop over all
   49012 ** pages in the WAL in ascending order. The caller must hold the checkpoint
   49013 ** lock.
   49014 **
   49015 ** On success, make *pp point to the newly allocated WalInterator object
   49016 ** return SQLITE_OK. Otherwise, return an error code. If this routine
   49017 ** returns an error, the value of *pp is undefined.
   49018 **
   49019 ** The calling routine should invoke walIteratorFree() to destroy the
   49020 ** WalIterator object when it has finished with it.
   49021 */
   49022 static int walIteratorInit(Wal *pWal, WalIterator **pp){
   49023   WalIterator *p;                 /* Return value */
   49024   int nSegment;                   /* Number of segments to merge */
   49025   u32 iLast;                      /* Last frame in log */
   49026   int nByte;                      /* Number of bytes to allocate */
   49027   int i;                          /* Iterator variable */
   49028   ht_slot *aTmp;                  /* Temp space used by merge-sort */
   49029   int rc = SQLITE_OK;             /* Return Code */
   49030 
   49031   /* This routine only runs while holding the checkpoint lock. And
   49032   ** it only runs if there is actually content in the log (mxFrame>0).
   49033   */
   49034   assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
   49035   iLast = pWal->hdr.mxFrame;
   49036 
   49037   /* Allocate space for the WalIterator object. */
   49038   nSegment = walFramePage(iLast) + 1;
   49039   nByte = sizeof(WalIterator)
   49040         + (nSegment-1)*sizeof(struct WalSegment)
   49041         + iLast*sizeof(ht_slot);
   49042   p = (WalIterator *)sqlite3ScratchMalloc(nByte);
   49043   if( !p ){
   49044     return SQLITE_NOMEM;
   49045   }
   49046   memset(p, 0, nByte);
   49047   p->nSegment = nSegment;
   49048 
   49049   /* Allocate temporary space used by the merge-sort routine. This block
   49050   ** of memory will be freed before this function returns.
   49051   */
   49052   aTmp = (ht_slot *)sqlite3ScratchMalloc(
   49053       sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
   49054   );
   49055   if( !aTmp ){
   49056     rc = SQLITE_NOMEM;
   49057   }
   49058 
   49059   for(i=0; rc==SQLITE_OK && i<nSegment; i++){
   49060     volatile ht_slot *aHash;
   49061     u32 iZero;
   49062     volatile u32 *aPgno;
   49063 
   49064     rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
   49065     if( rc==SQLITE_OK ){
   49066       int j;                      /* Counter variable */
   49067       int nEntry;                 /* Number of entries in this segment */
   49068       ht_slot *aIndex;            /* Sorted index for this segment */
   49069 
   49070       aPgno++;
   49071       if( (i+1)==nSegment ){
   49072         nEntry = (int)(iLast - iZero);
   49073       }else{
   49074         nEntry = (int)((u32*)aHash - (u32*)aPgno);
   49075       }
   49076       aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
   49077       iZero++;
   49078 
   49079       for(j=0; j<nEntry; j++){
   49080         aIndex[j] = (ht_slot)j;
   49081       }
   49082       walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
   49083       p->aSegment[i].iZero = iZero;
   49084       p->aSegment[i].nEntry = nEntry;
   49085       p->aSegment[i].aIndex = aIndex;
   49086       p->aSegment[i].aPgno = (u32 *)aPgno;
   49087     }
   49088   }
   49089   sqlite3ScratchFree(aTmp);
   49090 
   49091   if( rc!=SQLITE_OK ){
   49092     walIteratorFree(p);
   49093   }
   49094   *pp = p;
   49095   return rc;
   49096 }
   49097 
   49098 /*
   49099 ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
   49100 ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
   49101 ** busy-handler function. Invoke it and retry the lock until either the
   49102 ** lock is successfully obtained or the busy-handler returns 0.
   49103 */
   49104 static int walBusyLock(
   49105   Wal *pWal,                      /* WAL connection */
   49106   int (*xBusy)(void*),            /* Function to call when busy */
   49107   void *pBusyArg,                 /* Context argument for xBusyHandler */
   49108   int lockIdx,                    /* Offset of first byte to lock */
   49109   int n                           /* Number of bytes to lock */
   49110 ){
   49111   int rc;
   49112   do {
   49113     rc = walLockExclusive(pWal, lockIdx, n);
   49114   }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
   49115   return rc;
   49116 }
   49117 
   49118 /*
   49119 ** The cache of the wal-index header must be valid to call this function.
   49120 ** Return the page-size in bytes used by the database.
   49121 */
   49122 static int walPagesize(Wal *pWal){
   49123   return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
   49124 }
   49125 
   49126 /*
   49127 ** Copy as much content as we can from the WAL back into the database file
   49128 ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
   49129 **
   49130 ** The amount of information copies from WAL to database might be limited
   49131 ** by active readers.  This routine will never overwrite a database page
   49132 ** that a concurrent reader might be using.
   49133 **
   49134 ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
   49135 ** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if
   49136 ** checkpoints are always run by a background thread or background
   49137 ** process, foreground threads will never block on a lengthy fsync call.
   49138 **
   49139 ** Fsync is called on the WAL before writing content out of the WAL and
   49140 ** into the database.  This ensures that if the new content is persistent
   49141 ** in the WAL and can be recovered following a power-loss or hard reset.
   49142 **
   49143 ** Fsync is also called on the database file if (and only if) the entire
   49144 ** WAL content is copied into the database file.  This second fsync makes
   49145 ** it safe to delete the WAL since the new content will persist in the
   49146 ** database file.
   49147 **
   49148 ** This routine uses and updates the nBackfill field of the wal-index header.
   49149 ** This is the only routine tha will increase the value of nBackfill.
   49150 ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
   49151 ** its value.)
   49152 **
   49153 ** The caller must be holding sufficient locks to ensure that no other
   49154 ** checkpoint is running (in any other thread or process) at the same
   49155 ** time.
   49156 */
   49157 static int walCheckpoint(
   49158   Wal *pWal,                      /* Wal connection */
   49159   int eMode,                      /* One of PASSIVE, FULL or RESTART */
   49160   int (*xBusyCall)(void*),        /* Function to call when busy */
   49161   void *pBusyArg,                 /* Context argument for xBusyHandler */
   49162   int sync_flags,                 /* Flags for OsSync() (or 0) */
   49163   u8 *zBuf                        /* Temporary buffer to use */
   49164 ){
   49165   int rc;                         /* Return code */
   49166   int szPage;                     /* Database page-size */
   49167   WalIterator *pIter = 0;         /* Wal iterator context */
   49168   u32 iDbpage = 0;                /* Next database page to write */
   49169   u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
   49170   u32 mxSafeFrame;                /* Max frame that can be backfilled */
   49171   u32 mxPage;                     /* Max database page to write */
   49172   int i;                          /* Loop counter */
   49173   volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
   49174   int (*xBusy)(void*) = 0;        /* Function to call when waiting for locks */
   49175 
   49176   szPage = walPagesize(pWal);
   49177   testcase( szPage<=32768 );
   49178   testcase( szPage>=65536 );
   49179   pInfo = walCkptInfo(pWal);
   49180   if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK;
   49181 
   49182   /* Allocate the iterator */
   49183   rc = walIteratorInit(pWal, &pIter);
   49184   if( rc!=SQLITE_OK ){
   49185     return rc;
   49186   }
   49187   assert( pIter );
   49188 
   49189   if( eMode!=SQLITE_CHECKPOINT_PASSIVE ) xBusy = xBusyCall;
   49190 
   49191   /* Compute in mxSafeFrame the index of the last frame of the WAL that is
   49192   ** safe to write into the database.  Frames beyond mxSafeFrame might
   49193   ** overwrite database pages that are in use by active readers and thus
   49194   ** cannot be backfilled from the WAL.
   49195   */
   49196   mxSafeFrame = pWal->hdr.mxFrame;
   49197   mxPage = pWal->hdr.nPage;
   49198   for(i=1; i<WAL_NREADER; i++){
   49199     u32 y = pInfo->aReadMark[i];
   49200     if( mxSafeFrame>y ){
   49201       assert( y<=pWal->hdr.mxFrame );
   49202       rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
   49203       if( rc==SQLITE_OK ){
   49204         pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
   49205         walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
   49206       }else if( rc==SQLITE_BUSY ){
   49207         mxSafeFrame = y;
   49208         xBusy = 0;
   49209       }else{
   49210         goto walcheckpoint_out;
   49211       }
   49212     }
   49213   }
   49214 
   49215   if( pInfo->nBackfill<mxSafeFrame
   49216    && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0), 1))==SQLITE_OK
   49217   ){
   49218     i64 nSize;                    /* Current size of database file */
   49219     u32 nBackfill = pInfo->nBackfill;
   49220 
   49221     /* Sync the WAL to disk */
   49222     if( sync_flags ){
   49223       rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
   49224     }
   49225 
   49226     /* If the database may grow as a result of this checkpoint, hint
   49227     ** about the eventual size of the db file to the VFS layer.
   49228     */
   49229     if( rc==SQLITE_OK ){
   49230       i64 nReq = ((i64)mxPage * szPage);
   49231       rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
   49232       if( rc==SQLITE_OK && nSize<nReq ){
   49233         sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
   49234       }
   49235     }
   49236 
   49237 
   49238     /* Iterate through the contents of the WAL, copying data to the db file. */
   49239     while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
   49240       i64 iOffset;
   49241       assert( walFramePgno(pWal, iFrame)==iDbpage );
   49242       if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
   49243       iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
   49244       /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
   49245       rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
   49246       if( rc!=SQLITE_OK ) break;
   49247       iOffset = (iDbpage-1)*(i64)szPage;
   49248       testcase( IS_BIG_INT(iOffset) );
   49249       rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
   49250       if( rc!=SQLITE_OK ) break;
   49251     }
   49252 
   49253     /* If work was actually accomplished... */
   49254     if( rc==SQLITE_OK ){
   49255       if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
   49256         i64 szDb = pWal->hdr.nPage*(i64)szPage;
   49257         testcase( IS_BIG_INT(szDb) );
   49258         rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
   49259         if( rc==SQLITE_OK && sync_flags ){
   49260           rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
   49261         }
   49262       }
   49263       if( rc==SQLITE_OK ){
   49264         pInfo->nBackfill = mxSafeFrame;
   49265       }
   49266     }
   49267 
   49268     /* Release the reader lock held while backfilling */
   49269     walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
   49270   }
   49271 
   49272   if( rc==SQLITE_BUSY ){
   49273     /* Reset the return code so as not to report a checkpoint failure
   49274     ** just because there are active readers.  */
   49275     rc = SQLITE_OK;
   49276   }
   49277 
   49278   /* If this is an SQLITE_CHECKPOINT_RESTART operation, and the entire wal
   49279   ** file has been copied into the database file, then block until all
   49280   ** readers have finished using the wal file. This ensures that the next
   49281   ** process to write to the database restarts the wal file.
   49282   */
   49283   if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
   49284     assert( pWal->writeLock );
   49285     if( pInfo->nBackfill<pWal->hdr.mxFrame ){
   49286       rc = SQLITE_BUSY;
   49287     }else if( eMode==SQLITE_CHECKPOINT_RESTART ){
   49288       assert( mxSafeFrame==pWal->hdr.mxFrame );
   49289       rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
   49290       if( rc==SQLITE_OK ){
   49291         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
   49292       }
   49293     }
   49294   }
   49295 
   49296  walcheckpoint_out:
   49297   walIteratorFree(pIter);
   49298   return rc;
   49299 }
   49300 
   49301 /*
   49302 ** If the WAL file is currently larger than nMax bytes in size, truncate
   49303 ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
   49304 */
   49305 static void walLimitSize(Wal *pWal, i64 nMax){
   49306   i64 sz;
   49307   int rx;
   49308   sqlite3BeginBenignMalloc();
   49309   rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
   49310   if( rx==SQLITE_OK && (sz > nMax ) ){
   49311     rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
   49312   }
   49313   sqlite3EndBenignMalloc();
   49314   if( rx ){
   49315     sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
   49316   }
   49317 }
   49318 
   49319 /*
   49320 ** Close a connection to a log file.
   49321 */
   49322 SQLITE_PRIVATE int sqlite3WalClose(
   49323   Wal *pWal,                      /* Wal to close */
   49324   int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
   49325   int nBuf,
   49326   u8 *zBuf                        /* Buffer of at least nBuf bytes */
   49327 ){
   49328   int rc = SQLITE_OK;
   49329   if( pWal ){
   49330     int isDelete = 0;             /* True to unlink wal and wal-index files */
   49331 
   49332     /* If an EXCLUSIVE lock can be obtained on the database file (using the
   49333     ** ordinary, rollback-mode locking methods, this guarantees that the
   49334     ** connection associated with this log file is the only connection to
   49335     ** the database. In this case checkpoint the database and unlink both
   49336     ** the wal and wal-index files.
   49337     **
   49338     ** The EXCLUSIVE lock is not released before returning.
   49339     */
   49340     rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
   49341     if( rc==SQLITE_OK ){
   49342       if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
   49343         pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
   49344       }
   49345       rc = sqlite3WalCheckpoint(
   49346           pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
   49347       );
   49348       if( rc==SQLITE_OK ){
   49349         int bPersist = -1;
   49350         sqlite3OsFileControlHint(
   49351             pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
   49352         );
   49353         if( bPersist!=1 ){
   49354           /* Try to delete the WAL file if the checkpoint completed and
   49355           ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
   49356           ** mode (!bPersist) */
   49357           isDelete = 1;
   49358         }else if( pWal->mxWalSize>=0 ){
   49359           /* Try to truncate the WAL file to zero bytes if the checkpoint
   49360           ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
   49361           ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
   49362           ** non-negative value (pWal->mxWalSize>=0).  Note that we truncate
   49363           ** to zero bytes as truncating to the journal_size_limit might
   49364           ** leave a corrupt WAL file on disk. */
   49365           walLimitSize(pWal, 0);
   49366         }
   49367       }
   49368     }
   49369 
   49370     walIndexClose(pWal, isDelete);
   49371     sqlite3OsClose(pWal->pWalFd);
   49372     if( isDelete ){
   49373       sqlite3BeginBenignMalloc();
   49374       sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
   49375       sqlite3EndBenignMalloc();
   49376     }
   49377     WALTRACE(("WAL%p: closed\n", pWal));
   49378     sqlite3_free((void *)pWal->apWiData);
   49379     sqlite3_free(pWal);
   49380   }
   49381   return rc;
   49382 }
   49383 
   49384 /*
   49385 ** Try to read the wal-index header.  Return 0 on success and 1 if
   49386 ** there is a problem.
   49387 **
   49388 ** The wal-index is in shared memory.  Another thread or process might
   49389 ** be writing the header at the same time this procedure is trying to
   49390 ** read it, which might result in inconsistency.  A dirty read is detected
   49391 ** by verifying that both copies of the header are the same and also by
   49392 ** a checksum on the header.
   49393 **
   49394 ** If and only if the read is consistent and the header is different from
   49395 ** pWal->hdr, then pWal->hdr is updated to the content of the new header
   49396 ** and *pChanged is set to 1.
   49397 **
   49398 ** If the checksum cannot be verified return non-zero. If the header
   49399 ** is read successfully and the checksum verified, return zero.
   49400 */
   49401 static int walIndexTryHdr(Wal *pWal, int *pChanged){
   49402   u32 aCksum[2];                  /* Checksum on the header content */
   49403   WalIndexHdr h1, h2;             /* Two copies of the header content */
   49404   WalIndexHdr volatile *aHdr;     /* Header in shared memory */
   49405 
   49406   /* The first page of the wal-index must be mapped at this point. */
   49407   assert( pWal->nWiData>0 && pWal->apWiData[0] );
   49408 
   49409   /* Read the header. This might happen concurrently with a write to the
   49410   ** same area of shared memory on a different CPU in a SMP,
   49411   ** meaning it is possible that an inconsistent snapshot is read
   49412   ** from the file. If this happens, return non-zero.
   49413   **
   49414   ** There are two copies of the header at the beginning of the wal-index.
   49415   ** When reading, read [0] first then [1].  Writes are in the reverse order.
   49416   ** Memory barriers are used to prevent the compiler or the hardware from
   49417   ** reordering the reads and writes.
   49418   */
   49419   aHdr = walIndexHdr(pWal);
   49420   memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
   49421   walShmBarrier(pWal);
   49422   memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
   49423 
   49424   if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
   49425     return 1;   /* Dirty read */
   49426   }
   49427   if( h1.isInit==0 ){
   49428     return 1;   /* Malformed header - probably all zeros */
   49429   }
   49430   walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
   49431   if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
   49432     return 1;   /* Checksum does not match */
   49433   }
   49434 
   49435   if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
   49436     *pChanged = 1;
   49437     memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
   49438     pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
   49439     testcase( pWal->szPage<=32768 );
   49440     testcase( pWal->szPage>=65536 );
   49441   }
   49442 
   49443   /* The header was successfully read. Return zero. */
   49444   return 0;
   49445 }
   49446 
   49447 /*
   49448 ** Read the wal-index header from the wal-index and into pWal->hdr.
   49449 ** If the wal-header appears to be corrupt, try to reconstruct the
   49450 ** wal-index from the WAL before returning.
   49451 **
   49452 ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
   49453 ** changed by this opertion.  If pWal->hdr is unchanged, set *pChanged
   49454 ** to 0.
   49455 **
   49456 ** If the wal-index header is successfully read, return SQLITE_OK.
   49457 ** Otherwise an SQLite error code.
   49458 */
   49459 static int walIndexReadHdr(Wal *pWal, int *pChanged){
   49460   int rc;                         /* Return code */
   49461   int badHdr;                     /* True if a header read failed */
   49462   volatile u32 *page0;            /* Chunk of wal-index containing header */
   49463 
   49464   /* Ensure that page 0 of the wal-index (the page that contains the
   49465   ** wal-index header) is mapped. Return early if an error occurs here.
   49466   */
   49467   assert( pChanged );
   49468   rc = walIndexPage(pWal, 0, &page0);
   49469   if( rc!=SQLITE_OK ){
   49470     return rc;
   49471   };
   49472   assert( page0 || pWal->writeLock==0 );
   49473 
   49474   /* If the first page of the wal-index has been mapped, try to read the
   49475   ** wal-index header immediately, without holding any lock. This usually
   49476   ** works, but may fail if the wal-index header is corrupt or currently
   49477   ** being modified by another thread or process.
   49478   */
   49479   badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
   49480 
   49481   /* If the first attempt failed, it might have been due to a race
   49482   ** with a writer.  So get a WRITE lock and try again.
   49483   */
   49484   assert( badHdr==0 || pWal->writeLock==0 );
   49485   if( badHdr ){
   49486     if( pWal->readOnly & WAL_SHM_RDONLY ){
   49487       if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
   49488         walUnlockShared(pWal, WAL_WRITE_LOCK);
   49489         rc = SQLITE_READONLY_RECOVERY;
   49490       }
   49491     }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
   49492       pWal->writeLock = 1;
   49493       if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
   49494         badHdr = walIndexTryHdr(pWal, pChanged);
   49495         if( badHdr ){
   49496           /* If the wal-index header is still malformed even while holding
   49497           ** a WRITE lock, it can only mean that the header is corrupted and
   49498           ** needs to be reconstructed.  So run recovery to do exactly that.
   49499           */
   49500           rc = walIndexRecover(pWal);
   49501           *pChanged = 1;
   49502         }
   49503       }
   49504       pWal->writeLock = 0;
   49505       walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
   49506     }
   49507   }
   49508 
   49509   /* If the header is read successfully, check the version number to make
   49510   ** sure the wal-index was not constructed with some future format that
   49511   ** this version of SQLite cannot understand.
   49512   */
   49513   if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
   49514     rc = SQLITE_CANTOPEN_BKPT;
   49515   }
   49516 
   49517   return rc;
   49518 }
   49519 
   49520 /*
   49521 ** This is the value that walTryBeginRead returns when it needs to
   49522 ** be retried.
   49523 */
   49524 #define WAL_RETRY  (-1)
   49525 
   49526 /*
   49527 ** Attempt to start a read transaction.  This might fail due to a race or
   49528 ** other transient condition.  When that happens, it returns WAL_RETRY to
   49529 ** indicate to the caller that it is safe to retry immediately.
   49530 **
   49531 ** On success return SQLITE_OK.  On a permanent failure (such an
   49532 ** I/O error or an SQLITE_BUSY because another process is running
   49533 ** recovery) return a positive error code.
   49534 **
   49535 ** The useWal parameter is true to force the use of the WAL and disable
   49536 ** the case where the WAL is bypassed because it has been completely
   49537 ** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr()
   49538 ** to make a copy of the wal-index header into pWal->hdr.  If the
   49539 ** wal-index header has changed, *pChanged is set to 1 (as an indication
   49540 ** to the caller that the local paget cache is obsolete and needs to be
   49541 ** flushed.)  When useWal==1, the wal-index header is assumed to already
   49542 ** be loaded and the pChanged parameter is unused.
   49543 **
   49544 ** The caller must set the cnt parameter to the number of prior calls to
   49545 ** this routine during the current read attempt that returned WAL_RETRY.
   49546 ** This routine will start taking more aggressive measures to clear the
   49547 ** race conditions after multiple WAL_RETRY returns, and after an excessive
   49548 ** number of errors will ultimately return SQLITE_PROTOCOL.  The
   49549 ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
   49550 ** and is not honoring the locking protocol.  There is a vanishingly small
   49551 ** chance that SQLITE_PROTOCOL could be returned because of a run of really
   49552 ** bad luck when there is lots of contention for the wal-index, but that
   49553 ** possibility is so small that it can be safely neglected, we believe.
   49554 **
   49555 ** On success, this routine obtains a read lock on
   49556 ** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
   49557 ** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
   49558 ** that means the Wal does not hold any read lock.  The reader must not
   49559 ** access any database page that is modified by a WAL frame up to and
   49560 ** including frame number aReadMark[pWal->readLock].  The reader will
   49561 ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
   49562 ** Or if pWal->readLock==0, then the reader will ignore the WAL
   49563 ** completely and get all content directly from the database file.
   49564 ** If the useWal parameter is 1 then the WAL will never be ignored and
   49565 ** this routine will always set pWal->readLock>0 on success.
   49566 ** When the read transaction is completed, the caller must release the
   49567 ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
   49568 **
   49569 ** This routine uses the nBackfill and aReadMark[] fields of the header
   49570 ** to select a particular WAL_READ_LOCK() that strives to let the
   49571 ** checkpoint process do as much work as possible.  This routine might
   49572 ** update values of the aReadMark[] array in the header, but if it does
   49573 ** so it takes care to hold an exclusive lock on the corresponding
   49574 ** WAL_READ_LOCK() while changing values.
   49575 */
   49576 static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
   49577   volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
   49578   u32 mxReadMark;                 /* Largest aReadMark[] value */
   49579   int mxI;                        /* Index of largest aReadMark[] value */
   49580   int i;                          /* Loop counter */
   49581   int rc = SQLITE_OK;             /* Return code  */
   49582 
   49583   assert( pWal->readLock<0 );     /* Not currently locked */
   49584 
   49585   /* Take steps to avoid spinning forever if there is a protocol error.
   49586   **
   49587   ** Circumstances that cause a RETRY should only last for the briefest
   49588   ** instances of time.  No I/O or other system calls are done while the
   49589   ** locks are held, so the locks should not be held for very long. But
   49590   ** if we are unlucky, another process that is holding a lock might get
   49591   ** paged out or take a page-fault that is time-consuming to resolve,
   49592   ** during the few nanoseconds that it is holding the lock.  In that case,
   49593   ** it might take longer than normal for the lock to free.
   49594   **
   49595   ** After 5 RETRYs, we begin calling sqlite3OsSleep().  The first few
   49596   ** calls to sqlite3OsSleep() have a delay of 1 microsecond.  Really this
   49597   ** is more of a scheduler yield than an actual delay.  But on the 10th
   49598   ** an subsequent retries, the delays start becoming longer and longer,
   49599   ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
   49600   ** The total delay time before giving up is less than 10 seconds.
   49601   */
   49602   if( cnt>5 ){
   49603     int nDelay = 1;                      /* Pause time in microseconds */
   49604     if( cnt>100 ){
   49605       VVA_ONLY( pWal->lockError = 1; )
   49606       return SQLITE_PROTOCOL;
   49607     }
   49608     if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
   49609     sqlite3OsSleep(pWal->pVfs, nDelay);
   49610   }
   49611 
   49612   if( !useWal ){
   49613     rc = walIndexReadHdr(pWal, pChanged);
   49614     if( rc==SQLITE_BUSY ){
   49615       /* If there is not a recovery running in another thread or process
   49616       ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
   49617       ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
   49618       ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
   49619       ** would be technically correct.  But the race is benign since with
   49620       ** WAL_RETRY this routine will be called again and will probably be
   49621       ** right on the second iteration.
   49622       */
   49623       if( pWal->apWiData[0]==0 ){
   49624         /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
   49625         ** We assume this is a transient condition, so return WAL_RETRY. The
   49626         ** xShmMap() implementation used by the default unix and win32 VFS
   49627         ** modules may return SQLITE_BUSY due to a race condition in the
   49628         ** code that determines whether or not the shared-memory region
   49629         ** must be zeroed before the requested page is returned.
   49630         */
   49631         rc = WAL_RETRY;
   49632       }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
   49633         walUnlockShared(pWal, WAL_RECOVER_LOCK);
   49634         rc = WAL_RETRY;
   49635       }else if( rc==SQLITE_BUSY ){
   49636         rc = SQLITE_BUSY_RECOVERY;
   49637       }
   49638     }
   49639     if( rc!=SQLITE_OK ){
   49640       return rc;
   49641     }
   49642   }
   49643 
   49644   pInfo = walCkptInfo(pWal);
   49645   if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
   49646     /* The WAL has been completely backfilled (or it is empty).
   49647     ** and can be safely ignored.
   49648     */
   49649     rc = walLockShared(pWal, WAL_READ_LOCK(0));
   49650     walShmBarrier(pWal);
   49651     if( rc==SQLITE_OK ){
   49652       if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
   49653         /* It is not safe to allow the reader to continue here if frames
   49654         ** may have been appended to the log before READ_LOCK(0) was obtained.
   49655         ** When holding READ_LOCK(0), the reader ignores the entire log file,
   49656         ** which implies that the database file contains a trustworthy
   49657         ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
   49658         ** happening, this is usually correct.
   49659         **
   49660         ** However, if frames have been appended to the log (or if the log
   49661         ** is wrapped and written for that matter) before the READ_LOCK(0)
   49662         ** is obtained, that is not necessarily true. A checkpointer may
   49663         ** have started to backfill the appended frames but crashed before
   49664         ** it finished. Leaving a corrupt image in the database file.
   49665         */
   49666         walUnlockShared(pWal, WAL_READ_LOCK(0));
   49667         return WAL_RETRY;
   49668       }
   49669       pWal->readLock = 0;
   49670       return SQLITE_OK;
   49671     }else if( rc!=SQLITE_BUSY ){
   49672       return rc;
   49673     }
   49674   }
   49675 
   49676   /* If we get this far, it means that the reader will want to use
   49677   ** the WAL to get at content from recent commits.  The job now is
   49678   ** to select one of the aReadMark[] entries that is closest to
   49679   ** but not exceeding pWal->hdr.mxFrame and lock that entry.
   49680   */
   49681   mxReadMark = 0;
   49682   mxI = 0;
   49683   for(i=1; i<WAL_NREADER; i++){
   49684     u32 thisMark = pInfo->aReadMark[i];
   49685     if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
   49686       assert( thisMark!=READMARK_NOT_USED );
   49687       mxReadMark = thisMark;
   49688       mxI = i;
   49689     }
   49690   }
   49691   /* There was once an "if" here. The extra "{" is to preserve indentation. */
   49692   {
   49693     if( (pWal->readOnly & WAL_SHM_RDONLY)==0
   49694      && (mxReadMark<pWal->hdr.mxFrame || mxI==0)
   49695     ){
   49696       for(i=1; i<WAL_NREADER; i++){
   49697         rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
   49698         if( rc==SQLITE_OK ){
   49699           mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
   49700           mxI = i;
   49701           walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
   49702           break;
   49703         }else if( rc!=SQLITE_BUSY ){
   49704           return rc;
   49705         }
   49706       }
   49707     }
   49708     if( mxI==0 ){
   49709       assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
   49710       return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
   49711     }
   49712 
   49713     rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
   49714     if( rc ){
   49715       return rc==SQLITE_BUSY ? WAL_RETRY : rc;
   49716     }
   49717     /* Now that the read-lock has been obtained, check that neither the
   49718     ** value in the aReadMark[] array or the contents of the wal-index
   49719     ** header have changed.
   49720     **
   49721     ** It is necessary to check that the wal-index header did not change
   49722     ** between the time it was read and when the shared-lock was obtained
   49723     ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
   49724     ** that the log file may have been wrapped by a writer, or that frames
   49725     ** that occur later in the log than pWal->hdr.mxFrame may have been
   49726     ** copied into the database by a checkpointer. If either of these things
   49727     ** happened, then reading the database with the current value of
   49728     ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
   49729     ** instead.
   49730     **
   49731     ** This does not guarantee that the copy of the wal-index header is up to
   49732     ** date before proceeding. That would not be possible without somehow
   49733     ** blocking writers. It only guarantees that a dangerous checkpoint or
   49734     ** log-wrap (either of which would require an exclusive lock on
   49735     ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
   49736     */
   49737     walShmBarrier(pWal);
   49738     if( pInfo->aReadMark[mxI]!=mxReadMark
   49739      || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
   49740     ){
   49741       walUnlockShared(pWal, WAL_READ_LOCK(mxI));
   49742       return WAL_RETRY;
   49743     }else{
   49744       assert( mxReadMark<=pWal->hdr.mxFrame );
   49745       pWal->readLock = (i16)mxI;
   49746     }
   49747   }
   49748   return rc;
   49749 }
   49750 
   49751 /*
   49752 ** Begin a read transaction on the database.
   49753 **
   49754 ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
   49755 ** it takes a snapshot of the state of the WAL and wal-index for the current
   49756 ** instant in time.  The current thread will continue to use this snapshot.
   49757 ** Other threads might append new content to the WAL and wal-index but
   49758 ** that extra content is ignored by the current thread.
   49759 **
   49760 ** If the database contents have changes since the previous read
   49761 ** transaction, then *pChanged is set to 1 before returning.  The
   49762 ** Pager layer will use this to know that is cache is stale and
   49763 ** needs to be flushed.
   49764 */
   49765 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
   49766   int rc;                         /* Return code */
   49767   int cnt = 0;                    /* Number of TryBeginRead attempts */
   49768 
   49769   do{
   49770     rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
   49771   }while( rc==WAL_RETRY );
   49772   testcase( (rc&0xff)==SQLITE_BUSY );
   49773   testcase( (rc&0xff)==SQLITE_IOERR );
   49774   testcase( rc==SQLITE_PROTOCOL );
   49775   testcase( rc==SQLITE_OK );
   49776   return rc;
   49777 }
   49778 
   49779 /*
   49780 ** Finish with a read transaction.  All this does is release the
   49781 ** read-lock.
   49782 */
   49783 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
   49784   sqlite3WalEndWriteTransaction(pWal);
   49785   if( pWal->readLock>=0 ){
   49786     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
   49787     pWal->readLock = -1;
   49788   }
   49789 }
   49790 
   49791 /*
   49792 ** Search the wal file for page pgno. If found, set *piRead to the frame that
   49793 ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
   49794 ** to zero.
   49795 **
   49796 ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
   49797 ** error does occur, the final value of *piRead is undefined.
   49798 */
   49799 SQLITE_PRIVATE int sqlite3WalFindFrame(
   49800   Wal *pWal,                      /* WAL handle */
   49801   Pgno pgno,                      /* Database page number to read data for */
   49802   u32 *piRead                     /* OUT: Frame number (or zero) */
   49803 ){
   49804   u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
   49805   u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
   49806   int iHash;                      /* Used to loop through N hash tables */
   49807 
   49808   /* This routine is only be called from within a read transaction. */
   49809   assert( pWal->readLock>=0 || pWal->lockError );
   49810 
   49811   /* If the "last page" field of the wal-index header snapshot is 0, then
   49812   ** no data will be read from the wal under any circumstances. Return early
   49813   ** in this case as an optimization.  Likewise, if pWal->readLock==0,
   49814   ** then the WAL is ignored by the reader so return early, as if the
   49815   ** WAL were empty.
   49816   */
   49817   if( iLast==0 || pWal->readLock==0 ){
   49818     *piRead = 0;
   49819     return SQLITE_OK;
   49820   }
   49821 
   49822   /* Search the hash table or tables for an entry matching page number
   49823   ** pgno. Each iteration of the following for() loop searches one
   49824   ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
   49825   **
   49826   ** This code might run concurrently to the code in walIndexAppend()
   49827   ** that adds entries to the wal-index (and possibly to this hash
   49828   ** table). This means the value just read from the hash
   49829   ** slot (aHash[iKey]) may have been added before or after the
   49830   ** current read transaction was opened. Values added after the
   49831   ** read transaction was opened may have been written incorrectly -
   49832   ** i.e. these slots may contain garbage data. However, we assume
   49833   ** that any slots written before the current read transaction was
   49834   ** opened remain unmodified.
   49835   **
   49836   ** For the reasons above, the if(...) condition featured in the inner
   49837   ** loop of the following block is more stringent that would be required
   49838   ** if we had exclusive access to the hash-table:
   49839   **
   49840   **   (aPgno[iFrame]==pgno):
   49841   **     This condition filters out normal hash-table collisions.
   49842   **
   49843   **   (iFrame<=iLast):
   49844   **     This condition filters out entries that were added to the hash
   49845   **     table after the current read-transaction had started.
   49846   */
   49847   for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
   49848     volatile ht_slot *aHash;      /* Pointer to hash table */
   49849     volatile u32 *aPgno;          /* Pointer to array of page numbers */
   49850     u32 iZero;                    /* Frame number corresponding to aPgno[0] */
   49851     int iKey;                     /* Hash slot index */
   49852     int nCollide;                 /* Number of hash collisions remaining */
   49853     int rc;                       /* Error code */
   49854 
   49855     rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
   49856     if( rc!=SQLITE_OK ){
   49857       return rc;
   49858     }
   49859     nCollide = HASHTABLE_NSLOT;
   49860     for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
   49861       u32 iFrame = aHash[iKey] + iZero;
   49862       if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
   49863         /* assert( iFrame>iRead ); -- not true if there is corruption */
   49864         iRead = iFrame;
   49865       }
   49866       if( (nCollide--)==0 ){
   49867         return SQLITE_CORRUPT_BKPT;
   49868       }
   49869     }
   49870   }
   49871 
   49872 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
   49873   /* If expensive assert() statements are available, do a linear search
   49874   ** of the wal-index file content. Make sure the results agree with the
   49875   ** result obtained using the hash indexes above.  */
   49876   {
   49877     u32 iRead2 = 0;
   49878     u32 iTest;
   49879     for(iTest=iLast; iTest>0; iTest--){
   49880       if( walFramePgno(pWal, iTest)==pgno ){
   49881         iRead2 = iTest;
   49882         break;
   49883       }
   49884     }
   49885     assert( iRead==iRead2 );
   49886   }
   49887 #endif
   49888 
   49889   *piRead = iRead;
   49890   return SQLITE_OK;
   49891 }
   49892 
   49893 /*
   49894 ** Read the contents of frame iRead from the wal file into buffer pOut
   49895 ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
   49896 ** error code otherwise.
   49897 */
   49898 SQLITE_PRIVATE int sqlite3WalReadFrame(
   49899   Wal *pWal,                      /* WAL handle */
   49900   u32 iRead,                      /* Frame to read */
   49901   int nOut,                       /* Size of buffer pOut in bytes */
   49902   u8 *pOut                        /* Buffer to write page data to */
   49903 ){
   49904   int sz;
   49905   i64 iOffset;
   49906   sz = pWal->hdr.szPage;
   49907   sz = (sz&0xfe00) + ((sz&0x0001)<<16);
   49908   testcase( sz<=32768 );
   49909   testcase( sz>=65536 );
   49910   iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
   49911   /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
   49912   return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
   49913 }
   49914 
   49915 /*
   49916 ** Return the size of the database in pages (or zero, if unknown).
   49917 */
   49918 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
   49919   if( pWal && ALWAYS(pWal->readLock>=0) ){
   49920     return pWal->hdr.nPage;
   49921   }
   49922   return 0;
   49923 }
   49924 
   49925 
   49926 /*
   49927 ** This function starts a write transaction on the WAL.
   49928 **
   49929 ** A read transaction must have already been started by a prior call
   49930 ** to sqlite3WalBeginReadTransaction().
   49931 **
   49932 ** If another thread or process has written into the database since
   49933 ** the read transaction was started, then it is not possible for this
   49934 ** thread to write as doing so would cause a fork.  So this routine
   49935 ** returns SQLITE_BUSY in that case and no write transaction is started.
   49936 **
   49937 ** There can only be a single writer active at a time.
   49938 */
   49939 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
   49940   int rc;
   49941 
   49942   /* Cannot start a write transaction without first holding a read
   49943   ** transaction. */
   49944   assert( pWal->readLock>=0 );
   49945 
   49946   if( pWal->readOnly ){
   49947     return SQLITE_READONLY;
   49948   }
   49949 
   49950   /* Only one writer allowed at a time.  Get the write lock.  Return
   49951   ** SQLITE_BUSY if unable.
   49952   */
   49953   rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
   49954   if( rc ){
   49955     return rc;
   49956   }
   49957   pWal->writeLock = 1;
   49958 
   49959   /* If another connection has written to the database file since the
   49960   ** time the read transaction on this connection was started, then
   49961   ** the write is disallowed.
   49962   */
   49963   if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
   49964     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
   49965     pWal->writeLock = 0;
   49966     rc = SQLITE_BUSY_SNAPSHOT;
   49967   }
   49968 
   49969   return rc;
   49970 }
   49971 
   49972 /*
   49973 ** End a write transaction.  The commit has already been done.  This
   49974 ** routine merely releases the lock.
   49975 */
   49976 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
   49977   if( pWal->writeLock ){
   49978     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
   49979     pWal->writeLock = 0;
   49980     pWal->truncateOnCommit = 0;
   49981   }
   49982   return SQLITE_OK;
   49983 }
   49984 
   49985 /*
   49986 ** If any data has been written (but not committed) to the log file, this
   49987 ** function moves the write-pointer back to the start of the transaction.
   49988 **
   49989 ** Additionally, the callback function is invoked for each frame written
   49990 ** to the WAL since the start of the transaction. If the callback returns
   49991 ** other than SQLITE_OK, it is not invoked again and the error code is
   49992 ** returned to the caller.
   49993 **
   49994 ** Otherwise, if the callback function does not return an error, this
   49995 ** function returns SQLITE_OK.
   49996 */
   49997 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
   49998   int rc = SQLITE_OK;
   49999   if( ALWAYS(pWal->writeLock) ){
   50000     Pgno iMax = pWal->hdr.mxFrame;
   50001     Pgno iFrame;
   50002 
   50003     /* Restore the clients cache of the wal-index header to the state it
   50004     ** was in before the client began writing to the database.
   50005     */
   50006     memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
   50007 
   50008     for(iFrame=pWal->hdr.mxFrame+1;
   50009         ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
   50010         iFrame++
   50011     ){
   50012       /* This call cannot fail. Unless the page for which the page number
   50013       ** is passed as the second argument is (a) in the cache and
   50014       ** (b) has an outstanding reference, then xUndo is either a no-op
   50015       ** (if (a) is false) or simply expels the page from the cache (if (b)
   50016       ** is false).
   50017       **
   50018       ** If the upper layer is doing a rollback, it is guaranteed that there
   50019       ** are no outstanding references to any page other than page 1. And
   50020       ** page 1 is never written to the log until the transaction is
   50021       ** committed. As a result, the call to xUndo may not fail.
   50022       */
   50023       assert( walFramePgno(pWal, iFrame)!=1 );
   50024       rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
   50025     }
   50026     if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
   50027   }
   50028   assert( rc==SQLITE_OK );
   50029   return rc;
   50030 }
   50031 
   50032 /*
   50033 ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
   50034 ** values. This function populates the array with values required to
   50035 ** "rollback" the write position of the WAL handle back to the current
   50036 ** point in the event of a savepoint rollback (via WalSavepointUndo()).
   50037 */
   50038 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
   50039   assert( pWal->writeLock );
   50040   aWalData[0] = pWal->hdr.mxFrame;
   50041   aWalData[1] = pWal->hdr.aFrameCksum[0];
   50042   aWalData[2] = pWal->hdr.aFrameCksum[1];
   50043   aWalData[3] = pWal->nCkpt;
   50044 }
   50045 
   50046 /*
   50047 ** Move the write position of the WAL back to the point identified by
   50048 ** the values in the aWalData[] array. aWalData must point to an array
   50049 ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
   50050 ** by a call to WalSavepoint().
   50051 */
   50052 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
   50053   int rc = SQLITE_OK;
   50054 
   50055   assert( pWal->writeLock );
   50056   assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
   50057 
   50058   if( aWalData[3]!=pWal->nCkpt ){
   50059     /* This savepoint was opened immediately after the write-transaction
   50060     ** was started. Right after that, the writer decided to wrap around
   50061     ** to the start of the log. Update the savepoint values to match.
   50062     */
   50063     aWalData[0] = 0;
   50064     aWalData[3] = pWal->nCkpt;
   50065   }
   50066 
   50067   if( aWalData[0]<pWal->hdr.mxFrame ){
   50068     pWal->hdr.mxFrame = aWalData[0];
   50069     pWal->hdr.aFrameCksum[0] = aWalData[1];
   50070     pWal->hdr.aFrameCksum[1] = aWalData[2];
   50071     walCleanupHash(pWal);
   50072   }
   50073 
   50074   return rc;
   50075 }
   50076 
   50077 
   50078 /*
   50079 ** This function is called just before writing a set of frames to the log
   50080 ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
   50081 ** to the current log file, it is possible to overwrite the start of the
   50082 ** existing log file with the new frames (i.e. "reset" the log). If so,
   50083 ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
   50084 ** unchanged.
   50085 **
   50086 ** SQLITE_OK is returned if no error is encountered (regardless of whether
   50087 ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
   50088 ** if an error occurs.
   50089 */
   50090 static int walRestartLog(Wal *pWal){
   50091   int rc = SQLITE_OK;
   50092   int cnt;
   50093 
   50094   if( pWal->readLock==0 ){
   50095     volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
   50096     assert( pInfo->nBackfill==pWal->hdr.mxFrame );
   50097     if( pInfo->nBackfill>0 ){
   50098       u32 salt1;
   50099       sqlite3_randomness(4, &salt1);
   50100       rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
   50101       if( rc==SQLITE_OK ){
   50102         /* If all readers are using WAL_READ_LOCK(0) (in other words if no
   50103         ** readers are currently using the WAL), then the transactions
   50104         ** frames will overwrite the start of the existing log. Update the
   50105         ** wal-index header to reflect this.
   50106         **
   50107         ** In theory it would be Ok to update the cache of the header only
   50108         ** at this point. But updating the actual wal-index header is also
   50109         ** safe and means there is no special case for sqlite3WalUndo()
   50110         ** to handle if this transaction is rolled back.
   50111         */
   50112         int i;                    /* Loop counter */
   50113         u32 *aSalt = pWal->hdr.aSalt;       /* Big-endian salt values */
   50114 
   50115         pWal->nCkpt++;
   50116         pWal->hdr.mxFrame = 0;
   50117         sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
   50118         aSalt[1] = salt1;
   50119         walIndexWriteHdr(pWal);
   50120         pInfo->nBackfill = 0;
   50121         pInfo->aReadMark[1] = 0;
   50122         for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
   50123         assert( pInfo->aReadMark[0]==0 );
   50124         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
   50125       }else if( rc!=SQLITE_BUSY ){
   50126         return rc;
   50127       }
   50128     }
   50129     walUnlockShared(pWal, WAL_READ_LOCK(0));
   50130     pWal->readLock = -1;
   50131     cnt = 0;
   50132     do{
   50133       int notUsed;
   50134       rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
   50135     }while( rc==WAL_RETRY );
   50136     assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
   50137     testcase( (rc&0xff)==SQLITE_IOERR );
   50138     testcase( rc==SQLITE_PROTOCOL );
   50139     testcase( rc==SQLITE_OK );
   50140   }
   50141   return rc;
   50142 }
   50143 
   50144 /*
   50145 ** Information about the current state of the WAL file and where
   50146 ** the next fsync should occur - passed from sqlite3WalFrames() into
   50147 ** walWriteToLog().
   50148 */
   50149 typedef struct WalWriter {
   50150   Wal *pWal;                   /* The complete WAL information */
   50151   sqlite3_file *pFd;           /* The WAL file to which we write */
   50152   sqlite3_int64 iSyncPoint;    /* Fsync at this offset */
   50153   int syncFlags;               /* Flags for the fsync */
   50154   int szPage;                  /* Size of one page */
   50155 } WalWriter;
   50156 
   50157 /*
   50158 ** Write iAmt bytes of content into the WAL file beginning at iOffset.
   50159 ** Do a sync when crossing the p->iSyncPoint boundary.
   50160 **
   50161 ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
   50162 ** first write the part before iSyncPoint, then sync, then write the
   50163 ** rest.
   50164 */
   50165 static int walWriteToLog(
   50166   WalWriter *p,              /* WAL to write to */
   50167   void *pContent,            /* Content to be written */
   50168   int iAmt,                  /* Number of bytes to write */
   50169   sqlite3_int64 iOffset      /* Start writing at this offset */
   50170 ){
   50171   int rc;
   50172   if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
   50173     int iFirstAmt = (int)(p->iSyncPoint - iOffset);
   50174     rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
   50175     if( rc ) return rc;
   50176     iOffset += iFirstAmt;
   50177     iAmt -= iFirstAmt;
   50178     pContent = (void*)(iFirstAmt + (char*)pContent);
   50179     assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
   50180     rc = sqlite3OsSync(p->pFd, p->syncFlags & SQLITE_SYNC_MASK);
   50181     if( iAmt==0 || rc ) return rc;
   50182   }
   50183   rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
   50184   return rc;
   50185 }
   50186 
   50187 /*
   50188 ** Write out a single frame of the WAL
   50189 */
   50190 static int walWriteOneFrame(
   50191   WalWriter *p,               /* Where to write the frame */
   50192   PgHdr *pPage,               /* The page of the frame to be written */
   50193   int nTruncate,              /* The commit flag.  Usually 0.  >0 for commit */
   50194   sqlite3_int64 iOffset       /* Byte offset at which to write */
   50195 ){
   50196   int rc;                         /* Result code from subfunctions */
   50197   void *pData;                    /* Data actually written */
   50198   u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
   50199 #if defined(SQLITE_HAS_CODEC)
   50200   if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM;
   50201 #else
   50202   pData = pPage->pData;
   50203 #endif
   50204   walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
   50205   rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
   50206   if( rc ) return rc;
   50207   /* Write the page data */
   50208   rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
   50209   return rc;
   50210 }
   50211 
   50212 /*
   50213 ** Write a set of frames to the log. The caller must hold the write-lock
   50214 ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
   50215 */
   50216 SQLITE_PRIVATE int sqlite3WalFrames(
   50217   Wal *pWal,                      /* Wal handle to write to */
   50218   int szPage,                     /* Database page-size in bytes */
   50219   PgHdr *pList,                   /* List of dirty pages to write */
   50220   Pgno nTruncate,                 /* Database size after this commit */
   50221   int isCommit,                   /* True if this is a commit */
   50222   int sync_flags                  /* Flags to pass to OsSync() (or 0) */
   50223 ){
   50224   int rc;                         /* Used to catch return codes */
   50225   u32 iFrame;                     /* Next frame address */
   50226   PgHdr *p;                       /* Iterator to run through pList with. */
   50227   PgHdr *pLast = 0;               /* Last frame in list */
   50228   int nExtra = 0;                 /* Number of extra copies of last page */
   50229   int szFrame;                    /* The size of a single frame */
   50230   i64 iOffset;                    /* Next byte to write in WAL file */
   50231   WalWriter w;                    /* The writer */
   50232 
   50233   assert( pList );
   50234   assert( pWal->writeLock );
   50235 
   50236   /* If this frame set completes a transaction, then nTruncate>0.  If
   50237   ** nTruncate==0 then this frame set does not complete the transaction. */
   50238   assert( (isCommit!=0)==(nTruncate!=0) );
   50239 
   50240 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
   50241   { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
   50242     WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
   50243               pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
   50244   }
   50245 #endif
   50246 
   50247   /* See if it is possible to write these frames into the start of the
   50248   ** log file, instead of appending to it at pWal->hdr.mxFrame.
   50249   */
   50250   if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
   50251     return rc;
   50252   }
   50253 
   50254   /* If this is the first frame written into the log, write the WAL
   50255   ** header to the start of the WAL file. See comments at the top of
   50256   ** this source file for a description of the WAL header format.
   50257   */
   50258   iFrame = pWal->hdr.mxFrame;
   50259   if( iFrame==0 ){
   50260     u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
   50261     u32 aCksum[2];                /* Checksum for wal-header */
   50262 
   50263     sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
   50264     sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
   50265     sqlite3Put4byte(&aWalHdr[8], szPage);
   50266     sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
   50267     if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
   50268     memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
   50269     walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
   50270     sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
   50271     sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
   50272 
   50273     pWal->szPage = szPage;
   50274     pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
   50275     pWal->hdr.aFrameCksum[0] = aCksum[0];
   50276     pWal->hdr.aFrameCksum[1] = aCksum[1];
   50277     pWal->truncateOnCommit = 1;
   50278 
   50279     rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
   50280     WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
   50281     if( rc!=SQLITE_OK ){
   50282       return rc;
   50283     }
   50284 
   50285     /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
   50286     ** all syncing is turned off by PRAGMA synchronous=OFF).  Otherwise
   50287     ** an out-of-order write following a WAL restart could result in
   50288     ** database corruption.  See the ticket:
   50289     **
   50290     **     http://localhost:591/sqlite/info/ff5be73dee
   50291     */
   50292     if( pWal->syncHeader && sync_flags ){
   50293       rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
   50294       if( rc ) return rc;
   50295     }
   50296   }
   50297   assert( (int)pWal->szPage==szPage );
   50298 
   50299   /* Setup information needed to write frames into the WAL */
   50300   w.pWal = pWal;
   50301   w.pFd = pWal->pWalFd;
   50302   w.iSyncPoint = 0;
   50303   w.syncFlags = sync_flags;
   50304   w.szPage = szPage;
   50305   iOffset = walFrameOffset(iFrame+1, szPage);
   50306   szFrame = szPage + WAL_FRAME_HDRSIZE;
   50307 
   50308   /* Write all frames into the log file exactly once */
   50309   for(p=pList; p; p=p->pDirty){
   50310     int nDbSize;   /* 0 normally.  Positive == commit flag */
   50311     iFrame++;
   50312     assert( iOffset==walFrameOffset(iFrame, szPage) );
   50313     nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
   50314     rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
   50315     if( rc ) return rc;
   50316     pLast = p;
   50317     iOffset += szFrame;
   50318   }
   50319 
   50320   /* If this is the end of a transaction, then we might need to pad
   50321   ** the transaction and/or sync the WAL file.
   50322   **
   50323   ** Padding and syncing only occur if this set of frames complete a
   50324   ** transaction and if PRAGMA synchronous=FULL.  If synchronous==NORMAL
   50325   ** or synchonous==OFF, then no padding or syncing are needed.
   50326   **
   50327   ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
   50328   ** needed and only the sync is done.  If padding is needed, then the
   50329   ** final frame is repeated (with its commit mark) until the next sector
   50330   ** boundary is crossed.  Only the part of the WAL prior to the last
   50331   ** sector boundary is synced; the part of the last frame that extends
   50332   ** past the sector boundary is written after the sync.
   50333   */
   50334   if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
   50335     if( pWal->padToSectorBoundary ){
   50336       int sectorSize = sqlite3SectorSize(pWal->pWalFd);
   50337       w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
   50338       while( iOffset<w.iSyncPoint ){
   50339         rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
   50340         if( rc ) return rc;
   50341         iOffset += szFrame;
   50342         nExtra++;
   50343       }
   50344     }else{
   50345       rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
   50346     }
   50347   }
   50348 
   50349   /* If this frame set completes the first transaction in the WAL and
   50350   ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
   50351   ** journal size limit, if possible.
   50352   */
   50353   if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
   50354     i64 sz = pWal->mxWalSize;
   50355     if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
   50356       sz = walFrameOffset(iFrame+nExtra+1, szPage);
   50357     }
   50358     walLimitSize(pWal, sz);
   50359     pWal->truncateOnCommit = 0;
   50360   }
   50361 
   50362   /* Append data to the wal-index. It is not necessary to lock the
   50363   ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
   50364   ** guarantees that there are no other writers, and no data that may
   50365   ** be in use by existing readers is being overwritten.
   50366   */
   50367   iFrame = pWal->hdr.mxFrame;
   50368   for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
   50369     iFrame++;
   50370     rc = walIndexAppend(pWal, iFrame, p->pgno);
   50371   }
   50372   while( rc==SQLITE_OK && nExtra>0 ){
   50373     iFrame++;
   50374     nExtra--;
   50375     rc = walIndexAppend(pWal, iFrame, pLast->pgno);
   50376   }
   50377 
   50378   if( rc==SQLITE_OK ){
   50379     /* Update the private copy of the header. */
   50380     pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
   50381     testcase( szPage<=32768 );
   50382     testcase( szPage>=65536 );
   50383     pWal->hdr.mxFrame = iFrame;
   50384     if( isCommit ){
   50385       pWal->hdr.iChange++;
   50386       pWal->hdr.nPage = nTruncate;
   50387     }
   50388     /* If this is a commit, update the wal-index header too. */
   50389     if( isCommit ){
   50390       walIndexWriteHdr(pWal);
   50391       pWal->iCallback = iFrame;
   50392     }
   50393   }
   50394 
   50395   WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
   50396   return rc;
   50397 }
   50398 
   50399 /*
   50400 ** This routine is called to implement sqlite3_wal_checkpoint() and
   50401 ** related interfaces.
   50402 **
   50403 ** Obtain a CHECKPOINT lock and then backfill as much information as
   50404 ** we can from WAL into the database.
   50405 **
   50406 ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
   50407 ** callback. In this case this function runs a blocking checkpoint.
   50408 */
   50409 SQLITE_PRIVATE int sqlite3WalCheckpoint(
   50410   Wal *pWal,                      /* Wal connection */
   50411   int eMode,                      /* PASSIVE, FULL or RESTART */
   50412   int (*xBusy)(void*),            /* Function to call when busy */
   50413   void *pBusyArg,                 /* Context argument for xBusyHandler */
   50414   int sync_flags,                 /* Flags to sync db file with (or 0) */
   50415   int nBuf,                       /* Size of temporary buffer */
   50416   u8 *zBuf,                       /* Temporary buffer to use */
   50417   int *pnLog,                     /* OUT: Number of frames in WAL */
   50418   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
   50419 ){
   50420   int rc;                         /* Return code */
   50421   int isChanged = 0;              /* True if a new wal-index header is loaded */
   50422   int eMode2 = eMode;             /* Mode to pass to walCheckpoint() */
   50423 
   50424   assert( pWal->ckptLock==0 );
   50425   assert( pWal->writeLock==0 );
   50426 
   50427   if( pWal->readOnly ) return SQLITE_READONLY;
   50428   WALTRACE(("WAL%p: checkpoint begins\n", pWal));
   50429   rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
   50430   if( rc ){
   50431     /* Usually this is SQLITE_BUSY meaning that another thread or process
   50432     ** is already running a checkpoint, or maybe a recovery.  But it might
   50433     ** also be SQLITE_IOERR. */
   50434     return rc;
   50435   }
   50436   pWal->ckptLock = 1;
   50437 
   50438   /* If this is a blocking-checkpoint, then obtain the write-lock as well
   50439   ** to prevent any writers from running while the checkpoint is underway.
   50440   ** This has to be done before the call to walIndexReadHdr() below.
   50441   **
   50442   ** If the writer lock cannot be obtained, then a passive checkpoint is
   50443   ** run instead. Since the checkpointer is not holding the writer lock,
   50444   ** there is no point in blocking waiting for any readers. Assuming no
   50445   ** other error occurs, this function will return SQLITE_BUSY to the caller.
   50446   */
   50447   if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
   50448     rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
   50449     if( rc==SQLITE_OK ){
   50450       pWal->writeLock = 1;
   50451     }else if( rc==SQLITE_BUSY ){
   50452       eMode2 = SQLITE_CHECKPOINT_PASSIVE;
   50453       rc = SQLITE_OK;
   50454     }
   50455   }
   50456 
   50457   /* Read the wal-index header. */
   50458   if( rc==SQLITE_OK ){
   50459     rc = walIndexReadHdr(pWal, &isChanged);
   50460     if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
   50461       sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
   50462     }
   50463   }
   50464 
   50465   /* Copy data from the log to the database file. */
   50466   if( rc==SQLITE_OK ){
   50467     if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
   50468       rc = SQLITE_CORRUPT_BKPT;
   50469     }else{
   50470       rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf);
   50471     }
   50472 
   50473     /* If no error occurred, set the output variables. */
   50474     if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
   50475       if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
   50476       if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
   50477     }
   50478   }
   50479 
   50480   if( isChanged ){
   50481     /* If a new wal-index header was loaded before the checkpoint was
   50482     ** performed, then the pager-cache associated with pWal is now
   50483     ** out of date. So zero the cached wal-index header to ensure that
   50484     ** next time the pager opens a snapshot on this database it knows that
   50485     ** the cache needs to be reset.
   50486     */
   50487     memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
   50488   }
   50489 
   50490   /* Release the locks. */
   50491   sqlite3WalEndWriteTransaction(pWal);
   50492   walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
   50493   pWal->ckptLock = 0;
   50494   WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
   50495   return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
   50496 }
   50497 
   50498 /* Return the value to pass to a sqlite3_wal_hook callback, the
   50499 ** number of frames in the WAL at the point of the last commit since
   50500 ** sqlite3WalCallback() was called.  If no commits have occurred since
   50501 ** the last call, then return 0.
   50502 */
   50503 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
   50504   u32 ret = 0;
   50505   if( pWal ){
   50506     ret = pWal->iCallback;
   50507     pWal->iCallback = 0;
   50508   }
   50509   return (int)ret;
   50510 }
   50511 
   50512 /*
   50513 ** This function is called to change the WAL subsystem into or out
   50514 ** of locking_mode=EXCLUSIVE.
   50515 **
   50516 ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
   50517 ** into locking_mode=NORMAL.  This means that we must acquire a lock
   50518 ** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
   50519 ** or if the acquisition of the lock fails, then return 0.  If the
   50520 ** transition out of exclusive-mode is successful, return 1.  This
   50521 ** operation must occur while the pager is still holding the exclusive
   50522 ** lock on the main database file.
   50523 **
   50524 ** If op is one, then change from locking_mode=NORMAL into
   50525 ** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
   50526 ** be released.  Return 1 if the transition is made and 0 if the
   50527 ** WAL is already in exclusive-locking mode - meaning that this
   50528 ** routine is a no-op.  The pager must already hold the exclusive lock
   50529 ** on the main database file before invoking this operation.
   50530 **
   50531 ** If op is negative, then do a dry-run of the op==1 case but do
   50532 ** not actually change anything. The pager uses this to see if it
   50533 ** should acquire the database exclusive lock prior to invoking
   50534 ** the op==1 case.
   50535 */
   50536 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
   50537   int rc;
   50538   assert( pWal->writeLock==0 );
   50539   assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
   50540 
   50541   /* pWal->readLock is usually set, but might be -1 if there was a
   50542   ** prior error while attempting to acquire are read-lock. This cannot
   50543   ** happen if the connection is actually in exclusive mode (as no xShmLock
   50544   ** locks are taken in this case). Nor should the pager attempt to
   50545   ** upgrade to exclusive-mode following such an error.
   50546   */
   50547   assert( pWal->readLock>=0 || pWal->lockError );
   50548   assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
   50549 
   50550   if( op==0 ){
   50551     if( pWal->exclusiveMode ){
   50552       pWal->exclusiveMode = 0;
   50553       if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
   50554         pWal->exclusiveMode = 1;
   50555       }
   50556       rc = pWal->exclusiveMode==0;
   50557     }else{
   50558       /* Already in locking_mode=NORMAL */
   50559       rc = 0;
   50560     }
   50561   }else if( op>0 ){
   50562     assert( pWal->exclusiveMode==0 );
   50563     assert( pWal->readLock>=0 );
   50564     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
   50565     pWal->exclusiveMode = 1;
   50566     rc = 1;
   50567   }else{
   50568     rc = pWal->exclusiveMode==0;
   50569   }
   50570   return rc;
   50571 }
   50572 
   50573 /*
   50574 ** Return true if the argument is non-NULL and the WAL module is using
   50575 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
   50576 ** WAL module is using shared-memory, return false.
   50577 */
   50578 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
   50579   return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
   50580 }
   50581 
   50582 #ifdef SQLITE_ENABLE_ZIPVFS
   50583 /*
   50584 ** If the argument is not NULL, it points to a Wal object that holds a
   50585 ** read-lock. This function returns the database page-size if it is known,
   50586 ** or zero if it is not (or if pWal is NULL).
   50587 */
   50588 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
   50589   assert( pWal==0 || pWal->readLock>=0 );
   50590   return (pWal ? pWal->szPage : 0);
   50591 }
   50592 #endif
   50593 
   50594 #endif /* #ifndef SQLITE_OMIT_WAL */
   50595 
   50596 /************** End of wal.c *************************************************/
   50597 /************** Begin file btmutex.c *****************************************/
   50598 /*
   50599 ** 2007 August 27
   50600 **
   50601 ** The author disclaims copyright to this source code.  In place of
   50602 ** a legal notice, here is a blessing:
   50603 **
   50604 **    May you do good and not evil.
   50605 **    May you find forgiveness for yourself and forgive others.
   50606 **    May you share freely, never taking more than you give.
   50607 **
   50608 *************************************************************************
   50609 **
   50610 ** This file contains code used to implement mutexes on Btree objects.
   50611 ** This code really belongs in btree.c.  But btree.c is getting too
   50612 ** big and we want to break it down some.  This packaged seemed like
   50613 ** a good breakout.
   50614 */
   50615 /************** Include btreeInt.h in the middle of btmutex.c ****************/
   50616 /************** Begin file btreeInt.h ****************************************/
   50617 /*
   50618 ** 2004 April 6
   50619 **
   50620 ** The author disclaims copyright to this source code.  In place of
   50621 ** a legal notice, here is a blessing:
   50622 **
   50623 **    May you do good and not evil.
   50624 **    May you find forgiveness for yourself and forgive others.
   50625 **    May you share freely, never taking more than you give.
   50626 **
   50627 *************************************************************************
   50628 ** This file implements a external (disk-based) database using BTrees.
   50629 ** For a detailed discussion of BTrees, refer to
   50630 **
   50631 **     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
   50632 **     "Sorting And Searching", pages 473-480. Addison-Wesley
   50633 **     Publishing Company, Reading, Massachusetts.
   50634 **
   50635 ** The basic idea is that each page of the file contains N database
   50636 ** entries and N+1 pointers to subpages.
   50637 **
   50638 **   ----------------------------------------------------------------
   50639 **   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
   50640 **   ----------------------------------------------------------------
   50641 **
   50642 ** All of the keys on the page that Ptr(0) points to have values less
   50643 ** than Key(0).  All of the keys on page Ptr(1) and its subpages have
   50644 ** values greater than Key(0) and less than Key(1).  All of the keys
   50645 ** on Ptr(N) and its subpages have values greater than Key(N-1).  And
   50646 ** so forth.
   50647 **
   50648 ** Finding a particular key requires reading O(log(M)) pages from the
   50649 ** disk where M is the number of entries in the tree.
   50650 **
   50651 ** In this implementation, a single file can hold one or more separate
   50652 ** BTrees.  Each BTree is identified by the index of its root page.  The
   50653 ** key and data for any entry are combined to form the "payload".  A
   50654 ** fixed amount of payload can be carried directly on the database
   50655 ** page.  If the payload is larger than the preset amount then surplus
   50656 ** bytes are stored on overflow pages.  The payload for an entry
   50657 ** and the preceding pointer are combined to form a "Cell".  Each
   50658 ** page has a small header which contains the Ptr(N) pointer and other
   50659 ** information such as the size of key and data.
   50660 **
   50661 ** FORMAT DETAILS
   50662 **
   50663 ** The file is divided into pages.  The first page is called page 1,
   50664 ** the second is page 2, and so forth.  A page number of zero indicates
   50665 ** "no such page".  The page size can be any power of 2 between 512 and 65536.
   50666 ** Each page can be either a btree page, a freelist page, an overflow
   50667 ** page, or a pointer-map page.
   50668 **
   50669 ** The first page is always a btree page.  The first 100 bytes of the first
   50670 ** page contain a special header (the "file header") that describes the file.
   50671 ** The format of the file header is as follows:
   50672 **
   50673 **   OFFSET   SIZE    DESCRIPTION
   50674 **      0      16     Header string: "SQLite format 3\000"
   50675 **     16       2     Page size in bytes.  (1 means 65536)
   50676 **     18       1     File format write version
   50677 **     19       1     File format read version
   50678 **     20       1     Bytes of unused space at the end of each page
   50679 **     21       1     Max embedded payload fraction (must be 64)
   50680 **     22       1     Min embedded payload fraction (must be 32)
   50681 **     23       1     Min leaf payload fraction (must be 32)
   50682 **     24       4     File change counter
   50683 **     28       4     Reserved for future use
   50684 **     32       4     First freelist page
   50685 **     36       4     Number of freelist pages in the file
   50686 **     40      60     15 4-byte meta values passed to higher layers
   50687 **
   50688 **     40       4     Schema cookie
   50689 **     44       4     File format of schema layer
   50690 **     48       4     Size of page cache
   50691 **     52       4     Largest root-page (auto/incr_vacuum)
   50692 **     56       4     1=UTF-8 2=UTF16le 3=UTF16be
   50693 **     60       4     User version
   50694 **     64       4     Incremental vacuum mode
   50695 **     68       4     Application-ID
   50696 **     72      20     unused
   50697 **     92       4     The version-valid-for number
   50698 **     96       4     SQLITE_VERSION_NUMBER
   50699 **
   50700 ** All of the integer values are big-endian (most significant byte first).
   50701 **
   50702 ** The file change counter is incremented when the database is changed
   50703 ** This counter allows other processes to know when the file has changed
   50704 ** and thus when they need to flush their cache.
   50705 **
   50706 ** The max embedded payload fraction is the amount of the total usable
   50707 ** space in a page that can be consumed by a single cell for standard
   50708 ** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
   50709 ** is to limit the maximum cell size so that at least 4 cells will fit
   50710 ** on one page.  Thus the default max embedded payload fraction is 64.
   50711 **
   50712 ** If the payload for a cell is larger than the max payload, then extra
   50713 ** payload is spilled to overflow pages.  Once an overflow page is allocated,
   50714 ** as many bytes as possible are moved into the overflow pages without letting
   50715 ** the cell size drop below the min embedded payload fraction.
   50716 **
   50717 ** The min leaf payload fraction is like the min embedded payload fraction
   50718 ** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
   50719 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
   50720 ** not specified in the header.
   50721 **
   50722 ** Each btree pages is divided into three sections:  The header, the
   50723 ** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
   50724 ** file header that occurs before the page header.
   50725 **
   50726 **      |----------------|
   50727 **      | file header    |   100 bytes.  Page 1 only.
   50728 **      |----------------|
   50729 **      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
   50730 **      |----------------|
   50731 **      | cell pointer   |   |  2 bytes per cell.  Sorted order.
   50732 **      | array          |   |  Grows downward
   50733 **      |                |   v
   50734 **      |----------------|
   50735 **      | unallocated    |
   50736 **      | space          |
   50737 **      |----------------|   ^  Grows upwards
   50738 **      | cell content   |   |  Arbitrary order interspersed with freeblocks.
   50739 **      | area           |   |  and free space fragments.
   50740 **      |----------------|
   50741 **
   50742 ** The page headers looks like this:
   50743 **
   50744 **   OFFSET   SIZE     DESCRIPTION
   50745 **      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
   50746 **      1       2      byte offset to the first freeblock
   50747 **      3       2      number of cells on this page
   50748 **      5       2      first byte of the cell content area
   50749 **      7       1      number of fragmented free bytes
   50750 **      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
   50751 **
   50752 ** The flags define the format of this btree page.  The leaf flag means that
   50753 ** this page has no children.  The zerodata flag means that this page carries
   50754 ** only keys and no data.  The intkey flag means that the key is a integer
   50755 ** which is stored in the key size entry of the cell header rather than in
   50756 ** the payload area.
   50757 **
   50758 ** The cell pointer array begins on the first byte after the page header.
   50759 ** The cell pointer array contains zero or more 2-byte numbers which are
   50760 ** offsets from the beginning of the page to the cell content in the cell
   50761 ** content area.  The cell pointers occur in sorted order.  The system strives
   50762 ** to keep free space after the last cell pointer so that new cells can
   50763 ** be easily added without having to defragment the page.
   50764 **
   50765 ** Cell content is stored at the very end of the page and grows toward the
   50766 ** beginning of the page.
   50767 **
   50768 ** Unused space within the cell content area is collected into a linked list of
   50769 ** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
   50770 ** to the first freeblock is given in the header.  Freeblocks occur in
   50771 ** increasing order.  Because a freeblock must be at least 4 bytes in size,
   50772 ** any group of 3 or fewer unused bytes in the cell content area cannot
   50773 ** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
   50774 ** a fragment.  The total number of bytes in all fragments is recorded.
   50775 ** in the page header at offset 7.
   50776 **
   50777 **    SIZE    DESCRIPTION
   50778 **      2     Byte offset of the next freeblock
   50779 **      2     Bytes in this freeblock
   50780 **
   50781 ** Cells are of variable length.  Cells are stored in the cell content area at
   50782 ** the end of the page.  Pointers to the cells are in the cell pointer array
   50783 ** that immediately follows the page header.  Cells is not necessarily
   50784 ** contiguous or in order, but cell pointers are contiguous and in order.
   50785 **
   50786 ** Cell content makes use of variable length integers.  A variable
   50787 ** length integer is 1 to 9 bytes where the lower 7 bits of each
   50788 ** byte are used.  The integer consists of all bytes that have bit 8 set and
   50789 ** the first byte with bit 8 clear.  The most significant byte of the integer
   50790 ** appears first.  A variable-length integer may not be more than 9 bytes long.
   50791 ** As a special case, all 8 bytes of the 9th byte are used as data.  This
   50792 ** allows a 64-bit integer to be encoded in 9 bytes.
   50793 **
   50794 **    0x00                      becomes  0x00000000
   50795 **    0x7f                      becomes  0x0000007f
   50796 **    0x81 0x00                 becomes  0x00000080
   50797 **    0x82 0x00                 becomes  0x00000100
   50798 **    0x80 0x7f                 becomes  0x0000007f
   50799 **    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
   50800 **    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
   50801 **
   50802 ** Variable length integers are used for rowids and to hold the number of
   50803 ** bytes of key and data in a btree cell.
   50804 **
   50805 ** The content of a cell looks like this:
   50806 **
   50807 **    SIZE    DESCRIPTION
   50808 **      4     Page number of the left child. Omitted if leaf flag is set.
   50809 **     var    Number of bytes of data. Omitted if the zerodata flag is set.
   50810 **     var    Number of bytes of key. Or the key itself if intkey flag is set.
   50811 **      *     Payload
   50812 **      4     First page of the overflow chain.  Omitted if no overflow
   50813 **
   50814 ** Overflow pages form a linked list.  Each page except the last is completely
   50815 ** filled with data (pagesize - 4 bytes).  The last page can have as little
   50816 ** as 1 byte of data.
   50817 **
   50818 **    SIZE    DESCRIPTION
   50819 **      4     Page number of next overflow page
   50820 **      *     Data
   50821 **
   50822 ** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
   50823 ** file header points to the first in a linked list of trunk page.  Each trunk
   50824 ** page points to multiple leaf pages.  The content of a leaf page is
   50825 ** unspecified.  A trunk page looks like this:
   50826 **
   50827 **    SIZE    DESCRIPTION
   50828 **      4     Page number of next trunk page
   50829 **      4     Number of leaf pointers on this page
   50830 **      *     zero or more pages numbers of leaves
   50831 */
   50832 
   50833 
   50834 /* The following value is the maximum cell size assuming a maximum page
   50835 ** size give above.
   50836 */
   50837 #define MX_CELL_SIZE(pBt)  ((int)(pBt->pageSize-8))
   50838 
   50839 /* The maximum number of cells on a single page of the database.  This
   50840 ** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
   50841 ** plus 2 bytes for the index to the cell in the page header).  Such
   50842 ** small cells will be rare, but they are possible.
   50843 */
   50844 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
   50845 
   50846 /* Forward declarations */
   50847 typedef struct MemPage MemPage;
   50848 typedef struct BtLock BtLock;
   50849 
   50850 /*
   50851 ** This is a magic string that appears at the beginning of every
   50852 ** SQLite database in order to identify the file as a real database.
   50853 **
   50854 ** You can change this value at compile-time by specifying a
   50855 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
   50856 ** header must be exactly 16 bytes including the zero-terminator so
   50857 ** the string itself should be 15 characters long.  If you change
   50858 ** the header, then your custom library will not be able to read
   50859 ** databases generated by the standard tools and the standard tools
   50860 ** will not be able to read databases created by your custom library.
   50861 */
   50862 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
   50863 #  define SQLITE_FILE_HEADER "SQLite format 3"
   50864 #endif
   50865 
   50866 /*
   50867 ** Page type flags.  An ORed combination of these flags appear as the
   50868 ** first byte of on-disk image of every BTree page.
   50869 */
   50870 #define PTF_INTKEY    0x01
   50871 #define PTF_ZERODATA  0x02
   50872 #define PTF_LEAFDATA  0x04
   50873 #define PTF_LEAF      0x08
   50874 
   50875 /*
   50876 ** As each page of the file is loaded into memory, an instance of the following
   50877 ** structure is appended and initialized to zero.  This structure stores
   50878 ** information about the page that is decoded from the raw file page.
   50879 **
   50880 ** The pParent field points back to the parent page.  This allows us to
   50881 ** walk up the BTree from any leaf to the root.  Care must be taken to
   50882 ** unref() the parent page pointer when this page is no longer referenced.
   50883 ** The pageDestructor() routine handles that chore.
   50884 **
   50885 ** Access to all fields of this structure is controlled by the mutex
   50886 ** stored in MemPage.pBt->mutex.
   50887 */
   50888 struct MemPage {
   50889   u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
   50890   u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
   50891   u8 intKey;           /* True if intkey flag is set */
   50892   u8 leaf;             /* True if leaf flag is set */
   50893   u8 hasData;          /* True if this page stores data */
   50894   u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
   50895   u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
   50896   u8 max1bytePayload;  /* min(maxLocal,127) */
   50897   u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
   50898   u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
   50899   u16 cellOffset;      /* Index in aData of first cell pointer */
   50900   u16 nFree;           /* Number of free bytes on the page */
   50901   u16 nCell;           /* Number of cells on this page, local and ovfl */
   50902   u16 maskPage;        /* Mask for page offset */
   50903   u16 aiOvfl[5];       /* Insert the i-th overflow cell before the aiOvfl-th
   50904                        ** non-overflow cell */
   50905   u8 *apOvfl[5];       /* Pointers to the body of overflow cells */
   50906   BtShared *pBt;       /* Pointer to BtShared that this page is part of */
   50907   u8 *aData;           /* Pointer to disk image of the page data */
   50908   u8 *aDataEnd;        /* One byte past the end of usable data */
   50909   u8 *aCellIdx;        /* The cell index area */
   50910   DbPage *pDbPage;     /* Pager page handle */
   50911   Pgno pgno;           /* Page number for this page */
   50912 };
   50913 
   50914 /*
   50915 ** The in-memory image of a disk page has the auxiliary information appended
   50916 ** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
   50917 ** that extra information.
   50918 */
   50919 #define EXTRA_SIZE sizeof(MemPage)
   50920 
   50921 /*
   50922 ** A linked list of the following structures is stored at BtShared.pLock.
   50923 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
   50924 ** is opened on the table with root page BtShared.iTable. Locks are removed
   50925 ** from this list when a transaction is committed or rolled back, or when
   50926 ** a btree handle is closed.
   50927 */
   50928 struct BtLock {
   50929   Btree *pBtree;        /* Btree handle holding this lock */
   50930   Pgno iTable;          /* Root page of table */
   50931   u8 eLock;             /* READ_LOCK or WRITE_LOCK */
   50932   BtLock *pNext;        /* Next in BtShared.pLock list */
   50933 };
   50934 
   50935 /* Candidate values for BtLock.eLock */
   50936 #define READ_LOCK     1
   50937 #define WRITE_LOCK    2
   50938 
   50939 /* A Btree handle
   50940 **
   50941 ** A database connection contains a pointer to an instance of
   50942 ** this object for every database file that it has open.  This structure
   50943 ** is opaque to the database connection.  The database connection cannot
   50944 ** see the internals of this structure and only deals with pointers to
   50945 ** this structure.
   50946 **
   50947 ** For some database files, the same underlying database cache might be
   50948 ** shared between multiple connections.  In that case, each connection
   50949 ** has it own instance of this object.  But each instance of this object
   50950 ** points to the same BtShared object.  The database cache and the
   50951 ** schema associated with the database file are all contained within
   50952 ** the BtShared object.
   50953 **
   50954 ** All fields in this structure are accessed under sqlite3.mutex.
   50955 ** The pBt pointer itself may not be changed while there exists cursors
   50956 ** in the referenced BtShared that point back to this Btree since those
   50957 ** cursors have to go through this Btree to find their BtShared and
   50958 ** they often do so without holding sqlite3.mutex.
   50959 */
   50960 struct Btree {
   50961   sqlite3 *db;       /* The database connection holding this btree */
   50962   BtShared *pBt;     /* Sharable content of this btree */
   50963   u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
   50964   u8 sharable;       /* True if we can share pBt with another db */
   50965   u8 locked;         /* True if db currently has pBt locked */
   50966   int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
   50967   int nBackup;       /* Number of backup operations reading this btree */
   50968   Btree *pNext;      /* List of other sharable Btrees from the same db */
   50969   Btree *pPrev;      /* Back pointer of the same list */
   50970 #ifndef SQLITE_OMIT_SHARED_CACHE
   50971   BtLock lock;       /* Object used to lock page 1 */
   50972 #endif
   50973 };
   50974 
   50975 /*
   50976 ** Btree.inTrans may take one of the following values.
   50977 **
   50978 ** If the shared-data extension is enabled, there may be multiple users
   50979 ** of the Btree structure. At most one of these may open a write transaction,
   50980 ** but any number may have active read transactions.
   50981 */
   50982 #define TRANS_NONE  0
   50983 #define TRANS_READ  1
   50984 #define TRANS_WRITE 2
   50985 
   50986 /*
   50987 ** An instance of this object represents a single database file.
   50988 **
   50989 ** A single database file can be in use at the same time by two
   50990 ** or more database connections.  When two or more connections are
   50991 ** sharing the same database file, each connection has it own
   50992 ** private Btree object for the file and each of those Btrees points
   50993 ** to this one BtShared object.  BtShared.nRef is the number of
   50994 ** connections currently sharing this database file.
   50995 **
   50996 ** Fields in this structure are accessed under the BtShared.mutex
   50997 ** mutex, except for nRef and pNext which are accessed under the
   50998 ** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
   50999 ** may not be modified once it is initially set as long as nRef>0.
   51000 ** The pSchema field may be set once under BtShared.mutex and
   51001 ** thereafter is unchanged as long as nRef>0.
   51002 **
   51003 ** isPending:
   51004 **
   51005 **   If a BtShared client fails to obtain a write-lock on a database
   51006 **   table (because there exists one or more read-locks on the table),
   51007 **   the shared-cache enters 'pending-lock' state and isPending is
   51008 **   set to true.
   51009 **
   51010 **   The shared-cache leaves the 'pending lock' state when either of
   51011 **   the following occur:
   51012 **
   51013 **     1) The current writer (BtShared.pWriter) concludes its transaction, OR
   51014 **     2) The number of locks held by other connections drops to zero.
   51015 **
   51016 **   while in the 'pending-lock' state, no connection may start a new
   51017 **   transaction.
   51018 **
   51019 **   This feature is included to help prevent writer-starvation.
   51020 */
   51021 struct BtShared {
   51022   Pager *pPager;        /* The page cache */
   51023   sqlite3 *db;          /* Database connection currently using this Btree */
   51024   BtCursor *pCursor;    /* A list of all open cursors */
   51025   MemPage *pPage1;      /* First page of the database */
   51026   u8 openFlags;         /* Flags to sqlite3BtreeOpen() */
   51027 #ifndef SQLITE_OMIT_AUTOVACUUM
   51028   u8 autoVacuum;        /* True if auto-vacuum is enabled */
   51029   u8 incrVacuum;        /* True if incr-vacuum is enabled */
   51030   u8 bDoTruncate;       /* True to truncate db on commit */
   51031 #endif
   51032   u8 inTransaction;     /* Transaction state */
   51033   u8 max1bytePayload;   /* Maximum first byte of cell for a 1-byte payload */
   51034   u16 btsFlags;         /* Boolean parameters.  See BTS_* macros below */
   51035   u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
   51036   u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
   51037   u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
   51038   u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
   51039   u32 pageSize;         /* Total number of bytes on a page */
   51040   u32 usableSize;       /* Number of usable bytes on each page */
   51041   int nTransaction;     /* Number of open transactions (read + write) */
   51042   u32 nPage;            /* Number of pages in the database */
   51043   void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
   51044   void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
   51045   sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
   51046   Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
   51047 #ifndef SQLITE_OMIT_SHARED_CACHE
   51048   int nRef;             /* Number of references to this structure */
   51049   BtShared *pNext;      /* Next on a list of sharable BtShared structs */
   51050   BtLock *pLock;        /* List of locks held on this shared-btree struct */
   51051   Btree *pWriter;       /* Btree with currently open write transaction */
   51052 #endif
   51053   u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
   51054 };
   51055 
   51056 /*
   51057 ** Allowed values for BtShared.btsFlags
   51058 */
   51059 #define BTS_READ_ONLY        0x0001   /* Underlying file is readonly */
   51060 #define BTS_PAGESIZE_FIXED   0x0002   /* Page size can no longer be changed */
   51061 #define BTS_SECURE_DELETE    0x0004   /* PRAGMA secure_delete is enabled */
   51062 #define BTS_INITIALLY_EMPTY  0x0008   /* Database was empty at trans start */
   51063 #define BTS_NO_WAL           0x0010   /* Do not open write-ahead-log files */
   51064 #define BTS_EXCLUSIVE        0x0020   /* pWriter has an exclusive lock */
   51065 #define BTS_PENDING          0x0040   /* Waiting for read-locks to clear */
   51066 
   51067 /*
   51068 ** An instance of the following structure is used to hold information
   51069 ** about a cell.  The parseCellPtr() function fills in this structure
   51070 ** based on information extract from the raw disk page.
   51071 */
   51072 typedef struct CellInfo CellInfo;
   51073 struct CellInfo {
   51074   i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
   51075   u8 *pCell;     /* Pointer to the start of cell content */
   51076   u32 nData;     /* Number of bytes of data */
   51077   u32 nPayload;  /* Total amount of payload */
   51078   u16 nHeader;   /* Size of the cell content header in bytes */
   51079   u16 nLocal;    /* Amount of payload held locally */
   51080   u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
   51081   u16 nSize;     /* Size of the cell content on the main b-tree page */
   51082 };
   51083 
   51084 /*
   51085 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
   51086 ** this will be declared corrupt. This value is calculated based on a
   51087 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
   51088 ** root-node and 3 for all other internal nodes.
   51089 **
   51090 ** If a tree that appears to be taller than this is encountered, it is
   51091 ** assumed that the database is corrupt.
   51092 */
   51093 #define BTCURSOR_MAX_DEPTH 20
   51094 
   51095 /*
   51096 ** A cursor is a pointer to a particular entry within a particular
   51097 ** b-tree within a database file.
   51098 **
   51099 ** The entry is identified by its MemPage and the index in
   51100 ** MemPage.aCell[] of the entry.
   51101 **
   51102 ** A single database file can be shared by two more database connections,
   51103 ** but cursors cannot be shared.  Each cursor is associated with a
   51104 ** particular database connection identified BtCursor.pBtree.db.
   51105 **
   51106 ** Fields in this structure are accessed under the BtShared.mutex
   51107 ** found at self->pBt->mutex.
   51108 */
   51109 struct BtCursor {
   51110   Btree *pBtree;            /* The Btree to which this cursor belongs */
   51111   BtShared *pBt;            /* The BtShared this cursor points to */
   51112   BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
   51113   struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
   51114   Pgno *aOverflow;          /* Cache of overflow page locations */
   51115   CellInfo info;            /* A parse of the cell we are pointing at */
   51116   i64 nKey;                 /* Size of pKey, or last integer key */
   51117   void *pKey;               /* Saved key that was cursor last known position */
   51118   Pgno pgnoRoot;            /* The root page of this tree */
   51119   int nOvflAlloc;           /* Allocated size of aOverflow[] array */
   51120   int skipNext;    /* Prev() is noop if negative. Next() is noop if positive */
   51121   u8 curFlags;              /* zero or more BTCF_* flags defined below */
   51122   u8 eState;                /* One of the CURSOR_XXX constants (see below) */
   51123   u8 hints;                             /* As configured by CursorSetHints() */
   51124   i16 iPage;                            /* Index of current page in apPage */
   51125   u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
   51126   MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
   51127 };
   51128 
   51129 /*
   51130 ** Legal values for BtCursor.curFlags
   51131 */
   51132 #define BTCF_WriteFlag    0x01   /* True if a write cursor */
   51133 #define BTCF_ValidNKey    0x02   /* True if info.nKey is valid */
   51134 #define BTCF_ValidOvfl    0x04   /* True if aOverflow is valid */
   51135 #define BTCF_AtLast       0x08   /* Cursor is pointing ot the last entry */
   51136 #define BTCF_Incrblob     0x10   /* True if an incremental I/O handle */
   51137 
   51138 /*
   51139 ** Potential values for BtCursor.eState.
   51140 **
   51141 ** CURSOR_INVALID:
   51142 **   Cursor does not point to a valid entry. This can happen (for example)
   51143 **   because the table is empty or because BtreeCursorFirst() has not been
   51144 **   called.
   51145 **
   51146 ** CURSOR_VALID:
   51147 **   Cursor points to a valid entry. getPayload() etc. may be called.
   51148 **
   51149 ** CURSOR_SKIPNEXT:
   51150 **   Cursor is valid except that the Cursor.skipNext field is non-zero
   51151 **   indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
   51152 **   operation should be a no-op.
   51153 **
   51154 ** CURSOR_REQUIRESEEK:
   51155 **   The table that this cursor was opened on still exists, but has been
   51156 **   modified since the cursor was last used. The cursor position is saved
   51157 **   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
   51158 **   this state, restoreCursorPosition() can be called to attempt to
   51159 **   seek the cursor to the saved position.
   51160 **
   51161 ** CURSOR_FAULT:
   51162 **   A unrecoverable error (an I/O error or a malloc failure) has occurred
   51163 **   on a different connection that shares the BtShared cache with this
   51164 **   cursor.  The error has left the cache in an inconsistent state.
   51165 **   Do nothing else with this cursor.  Any attempt to use the cursor
   51166 **   should return the error code stored in BtCursor.skip
   51167 */
   51168 #define CURSOR_INVALID           0
   51169 #define CURSOR_VALID             1
   51170 #define CURSOR_SKIPNEXT          2
   51171 #define CURSOR_REQUIRESEEK       3
   51172 #define CURSOR_FAULT             4
   51173 
   51174 /*
   51175 ** The database page the PENDING_BYTE occupies. This page is never used.
   51176 */
   51177 # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
   51178 
   51179 /*
   51180 ** These macros define the location of the pointer-map entry for a
   51181 ** database page. The first argument to each is the number of usable
   51182 ** bytes on each page of the database (often 1024). The second is the
   51183 ** page number to look up in the pointer map.
   51184 **
   51185 ** PTRMAP_PAGENO returns the database page number of the pointer-map
   51186 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
   51187 ** the offset of the requested map entry.
   51188 **
   51189 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
   51190 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
   51191 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
   51192 ** this test.
   51193 */
   51194 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
   51195 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
   51196 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
   51197 
   51198 /*
   51199 ** The pointer map is a lookup table that identifies the parent page for
   51200 ** each child page in the database file.  The parent page is the page that
   51201 ** contains a pointer to the child.  Every page in the database contains
   51202 ** 0 or 1 parent pages.  (In this context 'database page' refers
   51203 ** to any page that is not part of the pointer map itself.)  Each pointer map
   51204 ** entry consists of a single byte 'type' and a 4 byte parent page number.
   51205 ** The PTRMAP_XXX identifiers below are the valid types.
   51206 **
   51207 ** The purpose of the pointer map is to facility moving pages from one
   51208 ** position in the file to another as part of autovacuum.  When a page
   51209 ** is moved, the pointer in its parent must be updated to point to the
   51210 ** new location.  The pointer map is used to locate the parent page quickly.
   51211 **
   51212 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
   51213 **                  used in this case.
   51214 **
   51215 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
   51216 **                  is not used in this case.
   51217 **
   51218 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
   51219 **                   overflow pages. The page number identifies the page that
   51220 **                   contains the cell with a pointer to this overflow page.
   51221 **
   51222 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
   51223 **                   overflow pages. The page-number identifies the previous
   51224 **                   page in the overflow page list.
   51225 **
   51226 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
   51227 **               identifies the parent page in the btree.
   51228 */
   51229 #define PTRMAP_ROOTPAGE 1
   51230 #define PTRMAP_FREEPAGE 2
   51231 #define PTRMAP_OVERFLOW1 3
   51232 #define PTRMAP_OVERFLOW2 4
   51233 #define PTRMAP_BTREE 5
   51234 
   51235 /* A bunch of assert() statements to check the transaction state variables
   51236 ** of handle p (type Btree*) are internally consistent.
   51237 */
   51238 #define btreeIntegrity(p) \
   51239   assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
   51240   assert( p->pBt->inTransaction>=p->inTrans );
   51241 
   51242 
   51243 /*
   51244 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
   51245 ** if the database supports auto-vacuum or not. Because it is used
   51246 ** within an expression that is an argument to another macro
   51247 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
   51248 ** So, this macro is defined instead.
   51249 */
   51250 #ifndef SQLITE_OMIT_AUTOVACUUM
   51251 #define ISAUTOVACUUM (pBt->autoVacuum)
   51252 #else
   51253 #define ISAUTOVACUUM 0
   51254 #endif
   51255 
   51256 
   51257 /*
   51258 ** This structure is passed around through all the sanity checking routines
   51259 ** in order to keep track of some global state information.
   51260 **
   51261 ** The aRef[] array is allocated so that there is 1 bit for each page in
   51262 ** the database. As the integrity-check proceeds, for each page used in
   51263 ** the database the corresponding bit is set. This allows integrity-check to
   51264 ** detect pages that are used twice and orphaned pages (both of which
   51265 ** indicate corruption).
   51266 */
   51267 typedef struct IntegrityCk IntegrityCk;
   51268 struct IntegrityCk {
   51269   BtShared *pBt;    /* The tree being checked out */
   51270   Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
   51271   u8 *aPgRef;       /* 1 bit per page in the db (see above) */
   51272   Pgno nPage;       /* Number of pages in the database */
   51273   int mxErr;        /* Stop accumulating errors when this reaches zero */
   51274   int nErr;         /* Number of messages written to zErrMsg so far */
   51275   int mallocFailed; /* A memory allocation error has occurred */
   51276   StrAccum errMsg;  /* Accumulate the error message text here */
   51277 };
   51278 
   51279 /*
   51280 ** Routines to read or write a two- and four-byte big-endian integer values.
   51281 */
   51282 #define get2byte(x)   ((x)[0]<<8 | (x)[1])
   51283 #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
   51284 #define get4byte sqlite3Get4byte
   51285 #define put4byte sqlite3Put4byte
   51286 
   51287 /************** End of btreeInt.h ********************************************/
   51288 /************** Continuing where we left off in btmutex.c ********************/
   51289 #ifndef SQLITE_OMIT_SHARED_CACHE
   51290 #if SQLITE_THREADSAFE
   51291 
   51292 /*
   51293 ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
   51294 ** set BtShared.db to the database handle associated with p and the
   51295 ** p->locked boolean to true.
   51296 */
   51297 static void lockBtreeMutex(Btree *p){
   51298   assert( p->locked==0 );
   51299   assert( sqlite3_mutex_notheld(p->pBt->mutex) );
   51300   assert( sqlite3_mutex_held(p->db->mutex) );
   51301 
   51302   sqlite3_mutex_enter(p->pBt->mutex);
   51303   p->pBt->db = p->db;
   51304   p->locked = 1;
   51305 }
   51306 
   51307 /*
   51308 ** Release the BtShared mutex associated with B-Tree handle p and
   51309 ** clear the p->locked boolean.
   51310 */
   51311 static void unlockBtreeMutex(Btree *p){
   51312   BtShared *pBt = p->pBt;
   51313   assert( p->locked==1 );
   51314   assert( sqlite3_mutex_held(pBt->mutex) );
   51315   assert( sqlite3_mutex_held(p->db->mutex) );
   51316   assert( p->db==pBt->db );
   51317 
   51318   sqlite3_mutex_leave(pBt->mutex);
   51319   p->locked = 0;
   51320 }
   51321 
   51322 /*
   51323 ** Enter a mutex on the given BTree object.
   51324 **
   51325 ** If the object is not sharable, then no mutex is ever required
   51326 ** and this routine is a no-op.  The underlying mutex is non-recursive.
   51327 ** But we keep a reference count in Btree.wantToLock so the behavior
   51328 ** of this interface is recursive.
   51329 **
   51330 ** To avoid deadlocks, multiple Btrees are locked in the same order
   51331 ** by all database connections.  The p->pNext is a list of other
   51332 ** Btrees belonging to the same database connection as the p Btree
   51333 ** which need to be locked after p.  If we cannot get a lock on
   51334 ** p, then first unlock all of the others on p->pNext, then wait
   51335 ** for the lock to become available on p, then relock all of the
   51336 ** subsequent Btrees that desire a lock.
   51337 */
   51338 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
   51339   Btree *pLater;
   51340 
   51341   /* Some basic sanity checking on the Btree.  The list of Btrees
   51342   ** connected by pNext and pPrev should be in sorted order by
   51343   ** Btree.pBt value. All elements of the list should belong to
   51344   ** the same connection. Only shared Btrees are on the list. */
   51345   assert( p->pNext==0 || p->pNext->pBt>p->pBt );
   51346   assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
   51347   assert( p->pNext==0 || p->pNext->db==p->db );
   51348   assert( p->pPrev==0 || p->pPrev->db==p->db );
   51349   assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
   51350 
   51351   /* Check for locking consistency */
   51352   assert( !p->locked || p->wantToLock>0 );
   51353   assert( p->sharable || p->wantToLock==0 );
   51354 
   51355   /* We should already hold a lock on the database connection */
   51356   assert( sqlite3_mutex_held(p->db->mutex) );
   51357 
   51358   /* Unless the database is sharable and unlocked, then BtShared.db
   51359   ** should already be set correctly. */
   51360   assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
   51361 
   51362   if( !p->sharable ) return;
   51363   p->wantToLock++;
   51364   if( p->locked ) return;
   51365 
   51366   /* In most cases, we should be able to acquire the lock we
   51367   ** want without having to go throught the ascending lock
   51368   ** procedure that follows.  Just be sure not to block.
   51369   */
   51370   if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
   51371     p->pBt->db = p->db;
   51372     p->locked = 1;
   51373     return;
   51374   }
   51375 
   51376   /* To avoid deadlock, first release all locks with a larger
   51377   ** BtShared address.  Then acquire our lock.  Then reacquire
   51378   ** the other BtShared locks that we used to hold in ascending
   51379   ** order.
   51380   */
   51381   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
   51382     assert( pLater->sharable );
   51383     assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
   51384     assert( !pLater->locked || pLater->wantToLock>0 );
   51385     if( pLater->locked ){
   51386       unlockBtreeMutex(pLater);
   51387     }
   51388   }
   51389   lockBtreeMutex(p);
   51390   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
   51391     if( pLater->wantToLock ){
   51392       lockBtreeMutex(pLater);
   51393     }
   51394   }
   51395 }
   51396 
   51397 /*
   51398 ** Exit the recursive mutex on a Btree.
   51399 */
   51400 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
   51401   if( p->sharable ){
   51402     assert( p->wantToLock>0 );
   51403     p->wantToLock--;
   51404     if( p->wantToLock==0 ){
   51405       unlockBtreeMutex(p);
   51406     }
   51407   }
   51408 }
   51409 
   51410 #ifndef NDEBUG
   51411 /*
   51412 ** Return true if the BtShared mutex is held on the btree, or if the
   51413 ** B-Tree is not marked as sharable.
   51414 **
   51415 ** This routine is used only from within assert() statements.
   51416 */
   51417 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
   51418   assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
   51419   assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
   51420   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
   51421   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
   51422 
   51423   return (p->sharable==0 || p->locked);
   51424 }
   51425 #endif
   51426 
   51427 
   51428 #ifndef SQLITE_OMIT_INCRBLOB
   51429 /*
   51430 ** Enter and leave a mutex on a Btree given a cursor owned by that
   51431 ** Btree.  These entry points are used by incremental I/O and can be
   51432 ** omitted if that module is not used.
   51433 */
   51434 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
   51435   sqlite3BtreeEnter(pCur->pBtree);
   51436 }
   51437 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
   51438   sqlite3BtreeLeave(pCur->pBtree);
   51439 }
   51440 #endif /* SQLITE_OMIT_INCRBLOB */
   51441 
   51442 
   51443 /*
   51444 ** Enter the mutex on every Btree associated with a database
   51445 ** connection.  This is needed (for example) prior to parsing
   51446 ** a statement since we will be comparing table and column names
   51447 ** against all schemas and we do not want those schemas being
   51448 ** reset out from under us.
   51449 **
   51450 ** There is a corresponding leave-all procedures.
   51451 **
   51452 ** Enter the mutexes in accending order by BtShared pointer address
   51453 ** to avoid the possibility of deadlock when two threads with
   51454 ** two or more btrees in common both try to lock all their btrees
   51455 ** at the same instant.
   51456 */
   51457 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
   51458   int i;
   51459   Btree *p;
   51460   assert( sqlite3_mutex_held(db->mutex) );
   51461   for(i=0; i<db->nDb; i++){
   51462     p = db->aDb[i].pBt;
   51463     if( p ) sqlite3BtreeEnter(p);
   51464   }
   51465 }
   51466 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
   51467   int i;
   51468   Btree *p;
   51469   assert( sqlite3_mutex_held(db->mutex) );
   51470   for(i=0; i<db->nDb; i++){
   51471     p = db->aDb[i].pBt;
   51472     if( p ) sqlite3BtreeLeave(p);
   51473   }
   51474 }
   51475 
   51476 /*
   51477 ** Return true if a particular Btree requires a lock.  Return FALSE if
   51478 ** no lock is ever required since it is not sharable.
   51479 */
   51480 SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
   51481   return p->sharable;
   51482 }
   51483 
   51484 #ifndef NDEBUG
   51485 /*
   51486 ** Return true if the current thread holds the database connection
   51487 ** mutex and all required BtShared mutexes.
   51488 **
   51489 ** This routine is used inside assert() statements only.
   51490 */
   51491 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
   51492   int i;
   51493   if( !sqlite3_mutex_held(db->mutex) ){
   51494     return 0;
   51495   }
   51496   for(i=0; i<db->nDb; i++){
   51497     Btree *p;
   51498     p = db->aDb[i].pBt;
   51499     if( p && p->sharable &&
   51500          (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
   51501       return 0;
   51502     }
   51503   }
   51504   return 1;
   51505 }
   51506 #endif /* NDEBUG */
   51507 
   51508 #ifndef NDEBUG
   51509 /*
   51510 ** Return true if the correct mutexes are held for accessing the
   51511 ** db->aDb[iDb].pSchema structure.  The mutexes required for schema
   51512 ** access are:
   51513 **
   51514 **   (1) The mutex on db
   51515 **   (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
   51516 **
   51517 ** If pSchema is not NULL, then iDb is computed from pSchema and
   51518 ** db using sqlite3SchemaToIndex().
   51519 */
   51520 SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
   51521   Btree *p;
   51522   assert( db!=0 );
   51523   if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
   51524   assert( iDb>=0 && iDb<db->nDb );
   51525   if( !sqlite3_mutex_held(db->mutex) ) return 0;
   51526   if( iDb==1 ) return 1;
   51527   p = db->aDb[iDb].pBt;
   51528   assert( p!=0 );
   51529   return p->sharable==0 || p->locked==1;
   51530 }
   51531 #endif /* NDEBUG */
   51532 
   51533 #else /* SQLITE_THREADSAFE>0 above.  SQLITE_THREADSAFE==0 below */
   51534 /*
   51535 ** The following are special cases for mutex enter routines for use
   51536 ** in single threaded applications that use shared cache.  Except for
   51537 ** these two routines, all mutex operations are no-ops in that case and
   51538 ** are null #defines in btree.h.
   51539 **
   51540 ** If shared cache is disabled, then all btree mutex routines, including
   51541 ** the ones below, are no-ops and are null #defines in btree.h.
   51542 */
   51543 
   51544 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
   51545   p->pBt->db = p->db;
   51546 }
   51547 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
   51548   int i;
   51549   for(i=0; i<db->nDb; i++){
   51550     Btree *p = db->aDb[i].pBt;
   51551     if( p ){
   51552       p->pBt->db = p->db;
   51553     }
   51554   }
   51555 }
   51556 #endif /* if SQLITE_THREADSAFE */
   51557 #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
   51558 
   51559 /************** End of btmutex.c *********************************************/
   51560 /************** Begin file btree.c *******************************************/
   51561 /*
   51562 ** 2004 April 6
   51563 **
   51564 ** The author disclaims copyright to this source code.  In place of
   51565 ** a legal notice, here is a blessing:
   51566 **
   51567 **    May you do good and not evil.
   51568 **    May you find forgiveness for yourself and forgive others.
   51569 **    May you share freely, never taking more than you give.
   51570 **
   51571 *************************************************************************
   51572 ** This file implements a external (disk-based) database using BTrees.
   51573 ** See the header comment on "btreeInt.h" for additional information.
   51574 ** Including a description of file format and an overview of operation.
   51575 */
   51576 
   51577 /*
   51578 ** The header string that appears at the beginning of every
   51579 ** SQLite database.
   51580 */
   51581 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
   51582 
   51583 /*
   51584 ** Set this global variable to 1 to enable tracing using the TRACE
   51585 ** macro.
   51586 */
   51587 #if 0
   51588 int sqlite3BtreeTrace=1;  /* True to enable tracing */
   51589 # define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
   51590 #else
   51591 # define TRACE(X)
   51592 #endif
   51593 
   51594 /*
   51595 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
   51596 ** But if the value is zero, make it 65536.
   51597 **
   51598 ** This routine is used to extract the "offset to cell content area" value
   51599 ** from the header of a btree page.  If the page size is 65536 and the page
   51600 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
   51601 ** This routine makes the necessary adjustment to 65536.
   51602 */
   51603 #define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
   51604 
   51605 /*
   51606 ** Values passed as the 5th argument to allocateBtreePage()
   51607 */
   51608 #define BTALLOC_ANY   0           /* Allocate any page */
   51609 #define BTALLOC_EXACT 1           /* Allocate exact page if possible */
   51610 #define BTALLOC_LE    2           /* Allocate any page <= the parameter */
   51611 
   51612 /*
   51613 ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
   51614 ** defined, or 0 if it is. For example:
   51615 **
   51616 **   bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
   51617 */
   51618 #ifndef SQLITE_OMIT_AUTOVACUUM
   51619 #define IfNotOmitAV(expr) (expr)
   51620 #else
   51621 #define IfNotOmitAV(expr) 0
   51622 #endif
   51623 
   51624 #ifndef SQLITE_OMIT_SHARED_CACHE
   51625 /*
   51626 ** A list of BtShared objects that are eligible for participation
   51627 ** in shared cache.  This variable has file scope during normal builds,
   51628 ** but the test harness needs to access it so we make it global for
   51629 ** test builds.
   51630 **
   51631 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
   51632 */
   51633 #ifdef SQLITE_TEST
   51634 SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
   51635 #else
   51636 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
   51637 #endif
   51638 #endif /* SQLITE_OMIT_SHARED_CACHE */
   51639 
   51640 #ifndef SQLITE_OMIT_SHARED_CACHE
   51641 /*
   51642 ** Enable or disable the shared pager and schema features.
   51643 **
   51644 ** This routine has no effect on existing database connections.
   51645 ** The shared cache setting effects only future calls to
   51646 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
   51647 */
   51648 SQLITE_API int sqlite3_enable_shared_cache(int enable){
   51649   sqlite3GlobalConfig.sharedCacheEnabled = enable;
   51650   return SQLITE_OK;
   51651 }
   51652 #endif
   51653 
   51654 
   51655 
   51656 #ifdef SQLITE_OMIT_SHARED_CACHE
   51657   /*
   51658   ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
   51659   ** and clearAllSharedCacheTableLocks()
   51660   ** manipulate entries in the BtShared.pLock linked list used to store
   51661   ** shared-cache table level locks. If the library is compiled with the
   51662   ** shared-cache feature disabled, then there is only ever one user
   51663   ** of each BtShared structure and so this locking is not necessary.
   51664   ** So define the lock related functions as no-ops.
   51665   */
   51666   #define querySharedCacheTableLock(a,b,c) SQLITE_OK
   51667   #define setSharedCacheTableLock(a,b,c) SQLITE_OK
   51668   #define clearAllSharedCacheTableLocks(a)
   51669   #define downgradeAllSharedCacheTableLocks(a)
   51670   #define hasSharedCacheTableLock(a,b,c,d) 1
   51671   #define hasReadConflicts(a, b) 0
   51672 #endif
   51673 
   51674 #ifndef SQLITE_OMIT_SHARED_CACHE
   51675 
   51676 #ifdef SQLITE_DEBUG
   51677 /*
   51678 **** This function is only used as part of an assert() statement. ***
   51679 **
   51680 ** Check to see if pBtree holds the required locks to read or write to the
   51681 ** table with root page iRoot.   Return 1 if it does and 0 if not.
   51682 **
   51683 ** For example, when writing to a table with root-page iRoot via
   51684 ** Btree connection pBtree:
   51685 **
   51686 **    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
   51687 **
   51688 ** When writing to an index that resides in a sharable database, the
   51689 ** caller should have first obtained a lock specifying the root page of
   51690 ** the corresponding table. This makes things a bit more complicated,
   51691 ** as this module treats each table as a separate structure. To determine
   51692 ** the table corresponding to the index being written, this
   51693 ** function has to search through the database schema.
   51694 **
   51695 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
   51696 ** hold a write-lock on the schema table (root page 1). This is also
   51697 ** acceptable.
   51698 */
   51699 static int hasSharedCacheTableLock(
   51700   Btree *pBtree,         /* Handle that must hold lock */
   51701   Pgno iRoot,            /* Root page of b-tree */
   51702   int isIndex,           /* True if iRoot is the root of an index b-tree */
   51703   int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
   51704 ){
   51705   Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
   51706   Pgno iTab = 0;
   51707   BtLock *pLock;
   51708 
   51709   /* If this database is not shareable, or if the client is reading
   51710   ** and has the read-uncommitted flag set, then no lock is required.
   51711   ** Return true immediately.
   51712   */
   51713   if( (pBtree->sharable==0)
   51714    || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
   51715   ){
   51716     return 1;
   51717   }
   51718 
   51719   /* If the client is reading  or writing an index and the schema is
   51720   ** not loaded, then it is too difficult to actually check to see if
   51721   ** the correct locks are held.  So do not bother - just return true.
   51722   ** This case does not come up very often anyhow.
   51723   */
   51724   if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
   51725     return 1;
   51726   }
   51727 
   51728   /* Figure out the root-page that the lock should be held on. For table
   51729   ** b-trees, this is just the root page of the b-tree being read or
   51730   ** written. For index b-trees, it is the root page of the associated
   51731   ** table.  */
   51732   if( isIndex ){
   51733     HashElem *p;
   51734     for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
   51735       Index *pIdx = (Index *)sqliteHashData(p);
   51736       if( pIdx->tnum==(int)iRoot ){
   51737         iTab = pIdx->pTable->tnum;
   51738       }
   51739     }
   51740   }else{
   51741     iTab = iRoot;
   51742   }
   51743 
   51744   /* Search for the required lock. Either a write-lock on root-page iTab, a
   51745   ** write-lock on the schema table, or (if the client is reading) a
   51746   ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
   51747   for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
   51748     if( pLock->pBtree==pBtree
   51749      && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
   51750      && pLock->eLock>=eLockType
   51751     ){
   51752       return 1;
   51753     }
   51754   }
   51755 
   51756   /* Failed to find the required lock. */
   51757   return 0;
   51758 }
   51759 #endif /* SQLITE_DEBUG */
   51760 
   51761 #ifdef SQLITE_DEBUG
   51762 /*
   51763 **** This function may be used as part of assert() statements only. ****
   51764 **
   51765 ** Return true if it would be illegal for pBtree to write into the
   51766 ** table or index rooted at iRoot because other shared connections are
   51767 ** simultaneously reading that same table or index.
   51768 **
   51769 ** It is illegal for pBtree to write if some other Btree object that
   51770 ** shares the same BtShared object is currently reading or writing
   51771 ** the iRoot table.  Except, if the other Btree object has the
   51772 ** read-uncommitted flag set, then it is OK for the other object to
   51773 ** have a read cursor.
   51774 **
   51775 ** For example, before writing to any part of the table or index
   51776 ** rooted at page iRoot, one should call:
   51777 **
   51778 **    assert( !hasReadConflicts(pBtree, iRoot) );
   51779 */
   51780 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
   51781   BtCursor *p;
   51782   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
   51783     if( p->pgnoRoot==iRoot
   51784      && p->pBtree!=pBtree
   51785      && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
   51786     ){
   51787       return 1;
   51788     }
   51789   }
   51790   return 0;
   51791 }
   51792 #endif    /* #ifdef SQLITE_DEBUG */
   51793 
   51794 /*
   51795 ** Query to see if Btree handle p may obtain a lock of type eLock
   51796 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
   51797 ** SQLITE_OK if the lock may be obtained (by calling
   51798 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
   51799 */
   51800 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
   51801   BtShared *pBt = p->pBt;
   51802   BtLock *pIter;
   51803 
   51804   assert( sqlite3BtreeHoldsMutex(p) );
   51805   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
   51806   assert( p->db!=0 );
   51807   assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
   51808 
   51809   /* If requesting a write-lock, then the Btree must have an open write
   51810   ** transaction on this file. And, obviously, for this to be so there
   51811   ** must be an open write transaction on the file itself.
   51812   */
   51813   assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
   51814   assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
   51815 
   51816   /* This routine is a no-op if the shared-cache is not enabled */
   51817   if( !p->sharable ){
   51818     return SQLITE_OK;
   51819   }
   51820 
   51821   /* If some other connection is holding an exclusive lock, the
   51822   ** requested lock may not be obtained.
   51823   */
   51824   if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
   51825     sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
   51826     return SQLITE_LOCKED_SHAREDCACHE;
   51827   }
   51828 
   51829   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
   51830     /* The condition (pIter->eLock!=eLock) in the following if(...)
   51831     ** statement is a simplification of:
   51832     **
   51833     **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
   51834     **
   51835     ** since we know that if eLock==WRITE_LOCK, then no other connection
   51836     ** may hold a WRITE_LOCK on any table in this file (since there can
   51837     ** only be a single writer).
   51838     */
   51839     assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
   51840     assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
   51841     if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
   51842       sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
   51843       if( eLock==WRITE_LOCK ){
   51844         assert( p==pBt->pWriter );
   51845         pBt->btsFlags |= BTS_PENDING;
   51846       }
   51847       return SQLITE_LOCKED_SHAREDCACHE;
   51848     }
   51849   }
   51850   return SQLITE_OK;
   51851 }
   51852 #endif /* !SQLITE_OMIT_SHARED_CACHE */
   51853 
   51854 #ifndef SQLITE_OMIT_SHARED_CACHE
   51855 /*
   51856 ** Add a lock on the table with root-page iTable to the shared-btree used
   51857 ** by Btree handle p. Parameter eLock must be either READ_LOCK or
   51858 ** WRITE_LOCK.
   51859 **
   51860 ** This function assumes the following:
   51861 **
   51862 **   (a) The specified Btree object p is connected to a sharable
   51863 **       database (one with the BtShared.sharable flag set), and
   51864 **
   51865 **   (b) No other Btree objects hold a lock that conflicts
   51866 **       with the requested lock (i.e. querySharedCacheTableLock() has
   51867 **       already been called and returned SQLITE_OK).
   51868 **
   51869 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
   51870 ** is returned if a malloc attempt fails.
   51871 */
   51872 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
   51873   BtShared *pBt = p->pBt;
   51874   BtLock *pLock = 0;
   51875   BtLock *pIter;
   51876 
   51877   assert( sqlite3BtreeHoldsMutex(p) );
   51878   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
   51879   assert( p->db!=0 );
   51880 
   51881   /* A connection with the read-uncommitted flag set will never try to
   51882   ** obtain a read-lock using this function. The only read-lock obtained
   51883   ** by a connection in read-uncommitted mode is on the sqlite_master
   51884   ** table, and that lock is obtained in BtreeBeginTrans().  */
   51885   assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
   51886 
   51887   /* This function should only be called on a sharable b-tree after it
   51888   ** has been determined that no other b-tree holds a conflicting lock.  */
   51889   assert( p->sharable );
   51890   assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
   51891 
   51892   /* First search the list for an existing lock on this table. */
   51893   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
   51894     if( pIter->iTable==iTable && pIter->pBtree==p ){
   51895       pLock = pIter;
   51896       break;
   51897     }
   51898   }
   51899 
   51900   /* If the above search did not find a BtLock struct associating Btree p
   51901   ** with table iTable, allocate one and link it into the list.
   51902   */
   51903   if( !pLock ){
   51904     pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
   51905     if( !pLock ){
   51906       return SQLITE_NOMEM;
   51907     }
   51908     pLock->iTable = iTable;
   51909     pLock->pBtree = p;
   51910     pLock->pNext = pBt->pLock;
   51911     pBt->pLock = pLock;
   51912   }
   51913 
   51914   /* Set the BtLock.eLock variable to the maximum of the current lock
   51915   ** and the requested lock. This means if a write-lock was already held
   51916   ** and a read-lock requested, we don't incorrectly downgrade the lock.
   51917   */
   51918   assert( WRITE_LOCK>READ_LOCK );
   51919   if( eLock>pLock->eLock ){
   51920     pLock->eLock = eLock;
   51921   }
   51922 
   51923   return SQLITE_OK;
   51924 }
   51925 #endif /* !SQLITE_OMIT_SHARED_CACHE */
   51926 
   51927 #ifndef SQLITE_OMIT_SHARED_CACHE
   51928 /*
   51929 ** Release all the table locks (locks obtained via calls to
   51930 ** the setSharedCacheTableLock() procedure) held by Btree object p.
   51931 **
   51932 ** This function assumes that Btree p has an open read or write
   51933 ** transaction. If it does not, then the BTS_PENDING flag
   51934 ** may be incorrectly cleared.
   51935 */
   51936 static void clearAllSharedCacheTableLocks(Btree *p){
   51937   BtShared *pBt = p->pBt;
   51938   BtLock **ppIter = &pBt->pLock;
   51939 
   51940   assert( sqlite3BtreeHoldsMutex(p) );
   51941   assert( p->sharable || 0==*ppIter );
   51942   assert( p->inTrans>0 );
   51943 
   51944   while( *ppIter ){
   51945     BtLock *pLock = *ppIter;
   51946     assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
   51947     assert( pLock->pBtree->inTrans>=pLock->eLock );
   51948     if( pLock->pBtree==p ){
   51949       *ppIter = pLock->pNext;
   51950       assert( pLock->iTable!=1 || pLock==&p->lock );
   51951       if( pLock->iTable!=1 ){
   51952         sqlite3_free(pLock);
   51953       }
   51954     }else{
   51955       ppIter = &pLock->pNext;
   51956     }
   51957   }
   51958 
   51959   assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
   51960   if( pBt->pWriter==p ){
   51961     pBt->pWriter = 0;
   51962     pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
   51963   }else if( pBt->nTransaction==2 ){
   51964     /* This function is called when Btree p is concluding its
   51965     ** transaction. If there currently exists a writer, and p is not
   51966     ** that writer, then the number of locks held by connections other
   51967     ** than the writer must be about to drop to zero. In this case
   51968     ** set the BTS_PENDING flag to 0.
   51969     **
   51970     ** If there is not currently a writer, then BTS_PENDING must
   51971     ** be zero already. So this next line is harmless in that case.
   51972     */
   51973     pBt->btsFlags &= ~BTS_PENDING;
   51974   }
   51975 }
   51976 
   51977 /*
   51978 ** This function changes all write-locks held by Btree p into read-locks.
   51979 */
   51980 static void downgradeAllSharedCacheTableLocks(Btree *p){
   51981   BtShared *pBt = p->pBt;
   51982   if( pBt->pWriter==p ){
   51983     BtLock *pLock;
   51984     pBt->pWriter = 0;
   51985     pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
   51986     for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
   51987       assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
   51988       pLock->eLock = READ_LOCK;
   51989     }
   51990   }
   51991 }
   51992 
   51993 #endif /* SQLITE_OMIT_SHARED_CACHE */
   51994 
   51995 static void releasePage(MemPage *pPage);  /* Forward reference */
   51996 
   51997 /*
   51998 ***** This routine is used inside of assert() only ****
   51999 **
   52000 ** Verify that the cursor holds the mutex on its BtShared
   52001 */
   52002 #ifdef SQLITE_DEBUG
   52003 static int cursorHoldsMutex(BtCursor *p){
   52004   return sqlite3_mutex_held(p->pBt->mutex);
   52005 }
   52006 #endif
   52007 
   52008 /*
   52009 ** Invalidate the overflow cache of the cursor passed as the first argument.
   52010 ** on the shared btree structure pBt.
   52011 */
   52012 #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
   52013 
   52014 /*
   52015 ** Invalidate the overflow page-list cache for all cursors opened
   52016 ** on the shared btree structure pBt.
   52017 */
   52018 static void invalidateAllOverflowCache(BtShared *pBt){
   52019   BtCursor *p;
   52020   assert( sqlite3_mutex_held(pBt->mutex) );
   52021   for(p=pBt->pCursor; p; p=p->pNext){
   52022     invalidateOverflowCache(p);
   52023   }
   52024 }
   52025 
   52026 #ifndef SQLITE_OMIT_INCRBLOB
   52027 /*
   52028 ** This function is called before modifying the contents of a table
   52029 ** to invalidate any incrblob cursors that are open on the
   52030 ** row or one of the rows being modified.
   52031 **
   52032 ** If argument isClearTable is true, then the entire contents of the
   52033 ** table is about to be deleted. In this case invalidate all incrblob
   52034 ** cursors open on any row within the table with root-page pgnoRoot.
   52035 **
   52036 ** Otherwise, if argument isClearTable is false, then the row with
   52037 ** rowid iRow is being replaced or deleted. In this case invalidate
   52038 ** only those incrblob cursors open on that specific row.
   52039 */
   52040 static void invalidateIncrblobCursors(
   52041   Btree *pBtree,          /* The database file to check */
   52042   i64 iRow,               /* The rowid that might be changing */
   52043   int isClearTable        /* True if all rows are being deleted */
   52044 ){
   52045   BtCursor *p;
   52046   BtShared *pBt = pBtree->pBt;
   52047   assert( sqlite3BtreeHoldsMutex(pBtree) );
   52048   for(p=pBt->pCursor; p; p=p->pNext){
   52049     if( (p->curFlags & BTCF_Incrblob)!=0 && (isClearTable || p->info.nKey==iRow) ){
   52050       p->eState = CURSOR_INVALID;
   52051     }
   52052   }
   52053 }
   52054 
   52055 #else
   52056   /* Stub function when INCRBLOB is omitted */
   52057   #define invalidateIncrblobCursors(x,y,z)
   52058 #endif /* SQLITE_OMIT_INCRBLOB */
   52059 
   52060 /*
   52061 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
   52062 ** when a page that previously contained data becomes a free-list leaf
   52063 ** page.
   52064 **
   52065 ** The BtShared.pHasContent bitvec exists to work around an obscure
   52066 ** bug caused by the interaction of two useful IO optimizations surrounding
   52067 ** free-list leaf pages:
   52068 **
   52069 **   1) When all data is deleted from a page and the page becomes
   52070 **      a free-list leaf page, the page is not written to the database
   52071 **      (as free-list leaf pages contain no meaningful data). Sometimes
   52072 **      such a page is not even journalled (as it will not be modified,
   52073 **      why bother journalling it?).
   52074 **
   52075 **   2) When a free-list leaf page is reused, its content is not read
   52076 **      from the database or written to the journal file (why should it
   52077 **      be, if it is not at all meaningful?).
   52078 **
   52079 ** By themselves, these optimizations work fine and provide a handy
   52080 ** performance boost to bulk delete or insert operations. However, if
   52081 ** a page is moved to the free-list and then reused within the same
   52082 ** transaction, a problem comes up. If the page is not journalled when
   52083 ** it is moved to the free-list and it is also not journalled when it
   52084 ** is extracted from the free-list and reused, then the original data
   52085 ** may be lost. In the event of a rollback, it may not be possible
   52086 ** to restore the database to its original configuration.
   52087 **
   52088 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
   52089 ** moved to become a free-list leaf page, the corresponding bit is
   52090 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
   52091 ** optimization 2 above is omitted if the corresponding bit is already
   52092 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
   52093 ** at the end of every transaction.
   52094 */
   52095 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
   52096   int rc = SQLITE_OK;
   52097   if( !pBt->pHasContent ){
   52098     assert( pgno<=pBt->nPage );
   52099     pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
   52100     if( !pBt->pHasContent ){
   52101       rc = SQLITE_NOMEM;
   52102     }
   52103   }
   52104   if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
   52105     rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
   52106   }
   52107   return rc;
   52108 }
   52109 
   52110 /*
   52111 ** Query the BtShared.pHasContent vector.
   52112 **
   52113 ** This function is called when a free-list leaf page is removed from the
   52114 ** free-list for reuse. It returns false if it is safe to retrieve the
   52115 ** page from the pager layer with the 'no-content' flag set. True otherwise.
   52116 */
   52117 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
   52118   Bitvec *p = pBt->pHasContent;
   52119   return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
   52120 }
   52121 
   52122 /*
   52123 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
   52124 ** invoked at the conclusion of each write-transaction.
   52125 */
   52126 static void btreeClearHasContent(BtShared *pBt){
   52127   sqlite3BitvecDestroy(pBt->pHasContent);
   52128   pBt->pHasContent = 0;
   52129 }
   52130 
   52131 /*
   52132 ** Release all of the apPage[] pages for a cursor.
   52133 */
   52134 static void btreeReleaseAllCursorPages(BtCursor *pCur){
   52135   int i;
   52136   for(i=0; i<=pCur->iPage; i++){
   52137     releasePage(pCur->apPage[i]);
   52138     pCur->apPage[i] = 0;
   52139   }
   52140   pCur->iPage = -1;
   52141 }
   52142 
   52143 
   52144 /*
   52145 ** Save the current cursor position in the variables BtCursor.nKey
   52146 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
   52147 **
   52148 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
   52149 ** prior to calling this routine.
   52150 */
   52151 static int saveCursorPosition(BtCursor *pCur){
   52152   int rc;
   52153 
   52154   assert( CURSOR_VALID==pCur->eState );
   52155   assert( 0==pCur->pKey );
   52156   assert( cursorHoldsMutex(pCur) );
   52157 
   52158   rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
   52159   assert( rc==SQLITE_OK );  /* KeySize() cannot fail */
   52160 
   52161   /* If this is an intKey table, then the above call to BtreeKeySize()
   52162   ** stores the integer key in pCur->nKey. In this case this value is
   52163   ** all that is required. Otherwise, if pCur is not open on an intKey
   52164   ** table, then malloc space for and store the pCur->nKey bytes of key
   52165   ** data.
   52166   */
   52167   if( 0==pCur->apPage[0]->intKey ){
   52168     void *pKey = sqlite3Malloc( (int)pCur->nKey );
   52169     if( pKey ){
   52170       rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
   52171       if( rc==SQLITE_OK ){
   52172         pCur->pKey = pKey;
   52173       }else{
   52174         sqlite3_free(pKey);
   52175       }
   52176     }else{
   52177       rc = SQLITE_NOMEM;
   52178     }
   52179   }
   52180   assert( !pCur->apPage[0]->intKey || !pCur->pKey );
   52181 
   52182   if( rc==SQLITE_OK ){
   52183     btreeReleaseAllCursorPages(pCur);
   52184     pCur->eState = CURSOR_REQUIRESEEK;
   52185   }
   52186 
   52187   invalidateOverflowCache(pCur);
   52188   return rc;
   52189 }
   52190 
   52191 /*
   52192 ** Save the positions of all cursors (except pExcept) that are open on
   52193 ** the table  with root-page iRoot. Usually, this is called just before cursor
   52194 ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
   52195 */
   52196 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
   52197   BtCursor *p;
   52198   assert( sqlite3_mutex_held(pBt->mutex) );
   52199   assert( pExcept==0 || pExcept->pBt==pBt );
   52200   for(p=pBt->pCursor; p; p=p->pNext){
   52201     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
   52202       if( p->eState==CURSOR_VALID ){
   52203         int rc = saveCursorPosition(p);
   52204         if( SQLITE_OK!=rc ){
   52205           return rc;
   52206         }
   52207       }else{
   52208         testcase( p->iPage>0 );
   52209         btreeReleaseAllCursorPages(p);
   52210       }
   52211     }
   52212   }
   52213   return SQLITE_OK;
   52214 }
   52215 
   52216 /*
   52217 ** Clear the current cursor position.
   52218 */
   52219 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
   52220   assert( cursorHoldsMutex(pCur) );
   52221   sqlite3_free(pCur->pKey);
   52222   pCur->pKey = 0;
   52223   pCur->eState = CURSOR_INVALID;
   52224 }
   52225 
   52226 /*
   52227 ** In this version of BtreeMoveto, pKey is a packed index record
   52228 ** such as is generated by the OP_MakeRecord opcode.  Unpack the
   52229 ** record and then call BtreeMovetoUnpacked() to do the work.
   52230 */
   52231 static int btreeMoveto(
   52232   BtCursor *pCur,     /* Cursor open on the btree to be searched */
   52233   const void *pKey,   /* Packed key if the btree is an index */
   52234   i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
   52235   int bias,           /* Bias search to the high end */
   52236   int *pRes           /* Write search results here */
   52237 ){
   52238   int rc;                    /* Status code */
   52239   UnpackedRecord *pIdxKey;   /* Unpacked index key */
   52240   char aSpace[200];          /* Temp space for pIdxKey - to avoid a malloc */
   52241   char *pFree = 0;
   52242 
   52243   if( pKey ){
   52244     assert( nKey==(i64)(int)nKey );
   52245     pIdxKey = sqlite3VdbeAllocUnpackedRecord(
   52246         pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
   52247     );
   52248     if( pIdxKey==0 ) return SQLITE_NOMEM;
   52249     sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
   52250     if( pIdxKey->nField==0 ){
   52251       sqlite3DbFree(pCur->pKeyInfo->db, pFree);
   52252       return SQLITE_CORRUPT_BKPT;
   52253     }
   52254   }else{
   52255     pIdxKey = 0;
   52256   }
   52257   rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
   52258   if( pFree ){
   52259     sqlite3DbFree(pCur->pKeyInfo->db, pFree);
   52260   }
   52261   return rc;
   52262 }
   52263 
   52264 /*
   52265 ** Restore the cursor to the position it was in (or as close to as possible)
   52266 ** when saveCursorPosition() was called. Note that this call deletes the
   52267 ** saved position info stored by saveCursorPosition(), so there can be
   52268 ** at most one effective restoreCursorPosition() call after each
   52269 ** saveCursorPosition().
   52270 */
   52271 static int btreeRestoreCursorPosition(BtCursor *pCur){
   52272   int rc;
   52273   assert( cursorHoldsMutex(pCur) );
   52274   assert( pCur->eState>=CURSOR_REQUIRESEEK );
   52275   if( pCur->eState==CURSOR_FAULT ){
   52276     return pCur->skipNext;
   52277   }
   52278   pCur->eState = CURSOR_INVALID;
   52279   rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
   52280   if( rc==SQLITE_OK ){
   52281     sqlite3_free(pCur->pKey);
   52282     pCur->pKey = 0;
   52283     assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
   52284     if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
   52285       pCur->eState = CURSOR_SKIPNEXT;
   52286     }
   52287   }
   52288   return rc;
   52289 }
   52290 
   52291 #define restoreCursorPosition(p) \
   52292   (p->eState>=CURSOR_REQUIRESEEK ? \
   52293          btreeRestoreCursorPosition(p) : \
   52294          SQLITE_OK)
   52295 
   52296 /*
   52297 ** Determine whether or not a cursor has moved from the position it
   52298 ** was last placed at.  Cursors can move when the row they are pointing
   52299 ** at is deleted out from under them.
   52300 **
   52301 ** This routine returns an error code if something goes wrong.  The
   52302 ** integer *pHasMoved is set as follows:
   52303 **
   52304 **    0:   The cursor is unchanged
   52305 **    1:   The cursor is still pointing at the same row, but the pointers
   52306 **         returned by sqlite3BtreeKeyFetch() or sqlite3BtreeDataFetch()
   52307 **         might now be invalid because of a balance() or other change to the
   52308 **         b-tree.
   52309 **    2:   The cursor is no longer pointing to the row.  The row might have
   52310 **         been deleted out from under the cursor.
   52311 */
   52312 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
   52313   int rc;
   52314 
   52315   if( pCur->eState==CURSOR_VALID ){
   52316     *pHasMoved = 0;
   52317     return SQLITE_OK;
   52318   }
   52319   rc = restoreCursorPosition(pCur);
   52320   if( rc ){
   52321     *pHasMoved = 2;
   52322     return rc;
   52323   }
   52324   if( pCur->eState!=CURSOR_VALID || NEVER(pCur->skipNext!=0) ){
   52325     *pHasMoved = 2;
   52326   }else{
   52327     *pHasMoved = 1;
   52328   }
   52329   return SQLITE_OK;
   52330 }
   52331 
   52332 #ifndef SQLITE_OMIT_AUTOVACUUM
   52333 /*
   52334 ** Given a page number of a regular database page, return the page
   52335 ** number for the pointer-map page that contains the entry for the
   52336 ** input page number.
   52337 **
   52338 ** Return 0 (not a valid page) for pgno==1 since there is
   52339 ** no pointer map associated with page 1.  The integrity_check logic
   52340 ** requires that ptrmapPageno(*,1)!=1.
   52341 */
   52342 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
   52343   int nPagesPerMapPage;
   52344   Pgno iPtrMap, ret;
   52345   assert( sqlite3_mutex_held(pBt->mutex) );
   52346   if( pgno<2 ) return 0;
   52347   nPagesPerMapPage = (pBt->usableSize/5)+1;
   52348   iPtrMap = (pgno-2)/nPagesPerMapPage;
   52349   ret = (iPtrMap*nPagesPerMapPage) + 2;
   52350   if( ret==PENDING_BYTE_PAGE(pBt) ){
   52351     ret++;
   52352   }
   52353   return ret;
   52354 }
   52355 
   52356 /*
   52357 ** Write an entry into the pointer map.
   52358 **
   52359 ** This routine updates the pointer map entry for page number 'key'
   52360 ** so that it maps to type 'eType' and parent page number 'pgno'.
   52361 **
   52362 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
   52363 ** a no-op.  If an error occurs, the appropriate error code is written
   52364 ** into *pRC.
   52365 */
   52366 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
   52367   DbPage *pDbPage;  /* The pointer map page */
   52368   u8 *pPtrmap;      /* The pointer map data */
   52369   Pgno iPtrmap;     /* The pointer map page number */
   52370   int offset;       /* Offset in pointer map page */
   52371   int rc;           /* Return code from subfunctions */
   52372 
   52373   if( *pRC ) return;
   52374 
   52375   assert( sqlite3_mutex_held(pBt->mutex) );
   52376   /* The master-journal page number must never be used as a pointer map page */
   52377   assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
   52378 
   52379   assert( pBt->autoVacuum );
   52380   if( key==0 ){
   52381     *pRC = SQLITE_CORRUPT_BKPT;
   52382     return;
   52383   }
   52384   iPtrmap = PTRMAP_PAGENO(pBt, key);
   52385   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
   52386   if( rc!=SQLITE_OK ){
   52387     *pRC = rc;
   52388     return;
   52389   }
   52390   offset = PTRMAP_PTROFFSET(iPtrmap, key);
   52391   if( offset<0 ){
   52392     *pRC = SQLITE_CORRUPT_BKPT;
   52393     goto ptrmap_exit;
   52394   }
   52395   assert( offset <= (int)pBt->usableSize-5 );
   52396   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
   52397 
   52398   if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
   52399     TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
   52400     *pRC= rc = sqlite3PagerWrite(pDbPage);
   52401     if( rc==SQLITE_OK ){
   52402       pPtrmap[offset] = eType;
   52403       put4byte(&pPtrmap[offset+1], parent);
   52404     }
   52405   }
   52406 
   52407 ptrmap_exit:
   52408   sqlite3PagerUnref(pDbPage);
   52409 }
   52410 
   52411 /*
   52412 ** Read an entry from the pointer map.
   52413 **
   52414 ** This routine retrieves the pointer map entry for page 'key', writing
   52415 ** the type and parent page number to *pEType and *pPgno respectively.
   52416 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
   52417 */
   52418 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
   52419   DbPage *pDbPage;   /* The pointer map page */
   52420   int iPtrmap;       /* Pointer map page index */
   52421   u8 *pPtrmap;       /* Pointer map page data */
   52422   int offset;        /* Offset of entry in pointer map */
   52423   int rc;
   52424 
   52425   assert( sqlite3_mutex_held(pBt->mutex) );
   52426 
   52427   iPtrmap = PTRMAP_PAGENO(pBt, key);
   52428   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
   52429   if( rc!=0 ){
   52430     return rc;
   52431   }
   52432   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
   52433 
   52434   offset = PTRMAP_PTROFFSET(iPtrmap, key);
   52435   if( offset<0 ){
   52436     sqlite3PagerUnref(pDbPage);
   52437     return SQLITE_CORRUPT_BKPT;
   52438   }
   52439   assert( offset <= (int)pBt->usableSize-5 );
   52440   assert( pEType!=0 );
   52441   *pEType = pPtrmap[offset];
   52442   if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
   52443 
   52444   sqlite3PagerUnref(pDbPage);
   52445   if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
   52446   return SQLITE_OK;
   52447 }
   52448 
   52449 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
   52450   #define ptrmapPut(w,x,y,z,rc)
   52451   #define ptrmapGet(w,x,y,z) SQLITE_OK
   52452   #define ptrmapPutOvflPtr(x, y, rc)
   52453 #endif
   52454 
   52455 /*
   52456 ** Given a btree page and a cell index (0 means the first cell on
   52457 ** the page, 1 means the second cell, and so forth) return a pointer
   52458 ** to the cell content.
   52459 **
   52460 ** This routine works only for pages that do not contain overflow cells.
   52461 */
   52462 #define findCell(P,I) \
   52463   ((P)->aData + ((P)->maskPage & get2byte(&(P)->aCellIdx[2*(I)])))
   52464 #define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
   52465 
   52466 
   52467 /*
   52468 ** This a more complex version of findCell() that works for
   52469 ** pages that do contain overflow cells.
   52470 */
   52471 static u8 *findOverflowCell(MemPage *pPage, int iCell){
   52472   int i;
   52473   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   52474   for(i=pPage->nOverflow-1; i>=0; i--){
   52475     int k;
   52476     k = pPage->aiOvfl[i];
   52477     if( k<=iCell ){
   52478       if( k==iCell ){
   52479         return pPage->apOvfl[i];
   52480       }
   52481       iCell--;
   52482     }
   52483   }
   52484   return findCell(pPage, iCell);
   52485 }
   52486 
   52487 /*
   52488 ** Parse a cell content block and fill in the CellInfo structure.  There
   52489 ** are two versions of this function.  btreeParseCell() takes a
   52490 ** cell index as the second argument and btreeParseCellPtr()
   52491 ** takes a pointer to the body of the cell as its second argument.
   52492 **
   52493 ** Within this file, the parseCell() macro can be called instead of
   52494 ** btreeParseCellPtr(). Using some compilers, this will be faster.
   52495 */
   52496 static void btreeParseCellPtr(
   52497   MemPage *pPage,         /* Page containing the cell */
   52498   u8 *pCell,              /* Pointer to the cell text. */
   52499   CellInfo *pInfo         /* Fill in this structure */
   52500 ){
   52501   u16 n;                  /* Number bytes in cell content header */
   52502   u32 nPayload;           /* Number of bytes of cell payload */
   52503 
   52504   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   52505 
   52506   pInfo->pCell = pCell;
   52507   assert( pPage->leaf==0 || pPage->leaf==1 );
   52508   n = pPage->childPtrSize;
   52509   assert( n==4-4*pPage->leaf );
   52510   if( pPage->intKey ){
   52511     if( pPage->hasData ){
   52512       assert( n==0 );
   52513       n = getVarint32(pCell, nPayload);
   52514     }else{
   52515       nPayload = 0;
   52516     }
   52517     n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
   52518     pInfo->nData = nPayload;
   52519   }else{
   52520     pInfo->nData = 0;
   52521     n += getVarint32(&pCell[n], nPayload);
   52522     pInfo->nKey = nPayload;
   52523   }
   52524   pInfo->nPayload = nPayload;
   52525   pInfo->nHeader = n;
   52526   testcase( nPayload==pPage->maxLocal );
   52527   testcase( nPayload==pPage->maxLocal+1 );
   52528   if( likely(nPayload<=pPage->maxLocal) ){
   52529     /* This is the (easy) common case where the entire payload fits
   52530     ** on the local page.  No overflow is required.
   52531     */
   52532     if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4;
   52533     pInfo->nLocal = (u16)nPayload;
   52534     pInfo->iOverflow = 0;
   52535   }else{
   52536     /* If the payload will not fit completely on the local page, we have
   52537     ** to decide how much to store locally and how much to spill onto
   52538     ** overflow pages.  The strategy is to minimize the amount of unused
   52539     ** space on overflow pages while keeping the amount of local storage
   52540     ** in between minLocal and maxLocal.
   52541     **
   52542     ** Warning:  changing the way overflow payload is distributed in any
   52543     ** way will result in an incompatible file format.
   52544     */
   52545     int minLocal;  /* Minimum amount of payload held locally */
   52546     int maxLocal;  /* Maximum amount of payload held locally */
   52547     int surplus;   /* Overflow payload available for local storage */
   52548 
   52549     minLocal = pPage->minLocal;
   52550     maxLocal = pPage->maxLocal;
   52551     surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
   52552     testcase( surplus==maxLocal );
   52553     testcase( surplus==maxLocal+1 );
   52554     if( surplus <= maxLocal ){
   52555       pInfo->nLocal = (u16)surplus;
   52556     }else{
   52557       pInfo->nLocal = (u16)minLocal;
   52558     }
   52559     pInfo->iOverflow = (u16)(pInfo->nLocal + n);
   52560     pInfo->nSize = pInfo->iOverflow + 4;
   52561   }
   52562 }
   52563 #define parseCell(pPage, iCell, pInfo) \
   52564   btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
   52565 static void btreeParseCell(
   52566   MemPage *pPage,         /* Page containing the cell */
   52567   int iCell,              /* The cell index.  First cell is 0 */
   52568   CellInfo *pInfo         /* Fill in this structure */
   52569 ){
   52570   parseCell(pPage, iCell, pInfo);
   52571 }
   52572 
   52573 /*
   52574 ** Compute the total number of bytes that a Cell needs in the cell
   52575 ** data area of the btree-page.  The return number includes the cell
   52576 ** data header and the local payload, but not any overflow page or
   52577 ** the space used by the cell pointer.
   52578 */
   52579 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
   52580   u8 *pIter = &pCell[pPage->childPtrSize];
   52581   u32 nSize;
   52582 
   52583 #ifdef SQLITE_DEBUG
   52584   /* The value returned by this function should always be the same as
   52585   ** the (CellInfo.nSize) value found by doing a full parse of the
   52586   ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
   52587   ** this function verifies that this invariant is not violated. */
   52588   CellInfo debuginfo;
   52589   btreeParseCellPtr(pPage, pCell, &debuginfo);
   52590 #endif
   52591 
   52592   if( pPage->intKey ){
   52593     u8 *pEnd;
   52594     if( pPage->hasData ){
   52595       pIter += getVarint32(pIter, nSize);
   52596     }else{
   52597       nSize = 0;
   52598     }
   52599 
   52600     /* pIter now points at the 64-bit integer key value, a variable length
   52601     ** integer. The following block moves pIter to point at the first byte
   52602     ** past the end of the key value. */
   52603     pEnd = &pIter[9];
   52604     while( (*pIter++)&0x80 && pIter<pEnd );
   52605   }else{
   52606     pIter += getVarint32(pIter, nSize);
   52607   }
   52608 
   52609   testcase( nSize==pPage->maxLocal );
   52610   testcase( nSize==pPage->maxLocal+1 );
   52611   if( nSize>pPage->maxLocal ){
   52612     int minLocal = pPage->minLocal;
   52613     nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
   52614     testcase( nSize==pPage->maxLocal );
   52615     testcase( nSize==pPage->maxLocal+1 );
   52616     if( nSize>pPage->maxLocal ){
   52617       nSize = minLocal;
   52618     }
   52619     nSize += 4;
   52620   }
   52621   nSize += (u32)(pIter - pCell);
   52622 
   52623   /* The minimum size of any cell is 4 bytes. */
   52624   if( nSize<4 ){
   52625     nSize = 4;
   52626   }
   52627 
   52628   assert( nSize==debuginfo.nSize );
   52629   return (u16)nSize;
   52630 }
   52631 
   52632 #ifdef SQLITE_DEBUG
   52633 /* This variation on cellSizePtr() is used inside of assert() statements
   52634 ** only. */
   52635 static u16 cellSize(MemPage *pPage, int iCell){
   52636   return cellSizePtr(pPage, findCell(pPage, iCell));
   52637 }
   52638 #endif
   52639 
   52640 #ifndef SQLITE_OMIT_AUTOVACUUM
   52641 /*
   52642 ** If the cell pCell, part of page pPage contains a pointer
   52643 ** to an overflow page, insert an entry into the pointer-map
   52644 ** for the overflow page.
   52645 */
   52646 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
   52647   CellInfo info;
   52648   if( *pRC ) return;
   52649   assert( pCell!=0 );
   52650   btreeParseCellPtr(pPage, pCell, &info);
   52651   assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
   52652   if( info.iOverflow ){
   52653     Pgno ovfl = get4byte(&pCell[info.iOverflow]);
   52654     ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
   52655   }
   52656 }
   52657 #endif
   52658 
   52659 
   52660 /*
   52661 ** Defragment the page given.  All Cells are moved to the
   52662 ** end of the page and all free space is collected into one
   52663 ** big FreeBlk that occurs in between the header and cell
   52664 ** pointer array and the cell content area.
   52665 */
   52666 static int defragmentPage(MemPage *pPage){
   52667   int i;                     /* Loop counter */
   52668   int pc;                    /* Address of a i-th cell */
   52669   int hdr;                   /* Offset to the page header */
   52670   int size;                  /* Size of a cell */
   52671   int usableSize;            /* Number of usable bytes on a page */
   52672   int cellOffset;            /* Offset to the cell pointer array */
   52673   int cbrk;                  /* Offset to the cell content area */
   52674   int nCell;                 /* Number of cells on the page */
   52675   unsigned char *data;       /* The page data */
   52676   unsigned char *temp;       /* Temp area for cell content */
   52677   int iCellFirst;            /* First allowable cell index */
   52678   int iCellLast;             /* Last possible cell index */
   52679 
   52680 
   52681   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   52682   assert( pPage->pBt!=0 );
   52683   assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
   52684   assert( pPage->nOverflow==0 );
   52685   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   52686   temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
   52687   data = pPage->aData;
   52688   hdr = pPage->hdrOffset;
   52689   cellOffset = pPage->cellOffset;
   52690   nCell = pPage->nCell;
   52691   assert( nCell==get2byte(&data[hdr+3]) );
   52692   usableSize = pPage->pBt->usableSize;
   52693   cbrk = get2byte(&data[hdr+5]);
   52694   memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
   52695   cbrk = usableSize;
   52696   iCellFirst = cellOffset + 2*nCell;
   52697   iCellLast = usableSize - 4;
   52698   for(i=0; i<nCell; i++){
   52699     u8 *pAddr;     /* The i-th cell pointer */
   52700     pAddr = &data[cellOffset + i*2];
   52701     pc = get2byte(pAddr);
   52702     testcase( pc==iCellFirst );
   52703     testcase( pc==iCellLast );
   52704 #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
   52705     /* These conditions have already been verified in btreeInitPage()
   52706     ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
   52707     */
   52708     if( pc<iCellFirst || pc>iCellLast ){
   52709       return SQLITE_CORRUPT_BKPT;
   52710     }
   52711 #endif
   52712     assert( pc>=iCellFirst && pc<=iCellLast );
   52713     size = cellSizePtr(pPage, &temp[pc]);
   52714     cbrk -= size;
   52715 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
   52716     if( cbrk<iCellFirst ){
   52717       return SQLITE_CORRUPT_BKPT;
   52718     }
   52719 #else
   52720     if( cbrk<iCellFirst || pc+size>usableSize ){
   52721       return SQLITE_CORRUPT_BKPT;
   52722     }
   52723 #endif
   52724     assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
   52725     testcase( cbrk+size==usableSize );
   52726     testcase( pc+size==usableSize );
   52727     memcpy(&data[cbrk], &temp[pc], size);
   52728     put2byte(pAddr, cbrk);
   52729   }
   52730   assert( cbrk>=iCellFirst );
   52731   put2byte(&data[hdr+5], cbrk);
   52732   data[hdr+1] = 0;
   52733   data[hdr+2] = 0;
   52734   data[hdr+7] = 0;
   52735   memset(&data[iCellFirst], 0, cbrk-iCellFirst);
   52736   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   52737   if( cbrk-iCellFirst!=pPage->nFree ){
   52738     return SQLITE_CORRUPT_BKPT;
   52739   }
   52740   return SQLITE_OK;
   52741 }
   52742 
   52743 /*
   52744 ** Allocate nByte bytes of space from within the B-Tree page passed
   52745 ** as the first argument. Write into *pIdx the index into pPage->aData[]
   52746 ** of the first byte of allocated space. Return either SQLITE_OK or
   52747 ** an error code (usually SQLITE_CORRUPT).
   52748 **
   52749 ** The caller guarantees that there is sufficient space to make the
   52750 ** allocation.  This routine might need to defragment in order to bring
   52751 ** all the space together, however.  This routine will avoid using
   52752 ** the first two bytes past the cell pointer area since presumably this
   52753 ** allocation is being made in order to insert a new cell, so we will
   52754 ** also end up needing a new cell pointer.
   52755 */
   52756 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
   52757   const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
   52758   u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
   52759   int nFrag;                           /* Number of fragmented bytes on pPage */
   52760   int top;                             /* First byte of cell content area */
   52761   int gap;        /* First byte of gap between cell pointers and cell content */
   52762   int rc;         /* Integer return code */
   52763   int usableSize; /* Usable size of the page */
   52764 
   52765   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   52766   assert( pPage->pBt );
   52767   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   52768   assert( nByte>=0 );  /* Minimum cell size is 4 */
   52769   assert( pPage->nFree>=nByte );
   52770   assert( pPage->nOverflow==0 );
   52771   usableSize = pPage->pBt->usableSize;
   52772   assert( nByte < usableSize-8 );
   52773 
   52774   nFrag = data[hdr+7];
   52775   assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
   52776   gap = pPage->cellOffset + 2*pPage->nCell;
   52777   top = get2byteNotZero(&data[hdr+5]);
   52778   if( gap>top ) return SQLITE_CORRUPT_BKPT;
   52779   testcase( gap+2==top );
   52780   testcase( gap+1==top );
   52781   testcase( gap==top );
   52782 
   52783   if( nFrag>=60 ){
   52784     /* Always defragment highly fragmented pages */
   52785     rc = defragmentPage(pPage);
   52786     if( rc ) return rc;
   52787     top = get2byteNotZero(&data[hdr+5]);
   52788   }else if( gap+2<=top ){
   52789     /* Search the freelist looking for a free slot big enough to satisfy
   52790     ** the request. The allocation is made from the first free slot in
   52791     ** the list that is large enough to accommodate it.
   52792     */
   52793     int pc, addr;
   52794     for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
   52795       int size;            /* Size of the free slot */
   52796       if( pc>usableSize-4 || pc<addr+4 ){
   52797         return SQLITE_CORRUPT_BKPT;
   52798       }
   52799       size = get2byte(&data[pc+2]);
   52800       if( size>=nByte ){
   52801         int x = size - nByte;
   52802         testcase( x==4 );
   52803         testcase( x==3 );
   52804         if( x<4 ){
   52805           /* Remove the slot from the free-list. Update the number of
   52806           ** fragmented bytes within the page. */
   52807           memcpy(&data[addr], &data[pc], 2);
   52808           data[hdr+7] = (u8)(nFrag + x);
   52809         }else if( size+pc > usableSize ){
   52810           return SQLITE_CORRUPT_BKPT;
   52811         }else{
   52812           /* The slot remains on the free-list. Reduce its size to account
   52813           ** for the portion used by the new allocation. */
   52814           put2byte(&data[pc+2], x);
   52815         }
   52816         *pIdx = pc + x;
   52817         return SQLITE_OK;
   52818       }
   52819     }
   52820   }
   52821 
   52822   /* Check to make sure there is enough space in the gap to satisfy
   52823   ** the allocation.  If not, defragment.
   52824   */
   52825   testcase( gap+2+nByte==top );
   52826   if( gap+2+nByte>top ){
   52827     rc = defragmentPage(pPage);
   52828     if( rc ) return rc;
   52829     top = get2byteNotZero(&data[hdr+5]);
   52830     assert( gap+nByte<=top );
   52831   }
   52832 
   52833 
   52834   /* Allocate memory from the gap in between the cell pointer array
   52835   ** and the cell content area.  The btreeInitPage() call has already
   52836   ** validated the freelist.  Given that the freelist is valid, there
   52837   ** is no way that the allocation can extend off the end of the page.
   52838   ** The assert() below verifies the previous sentence.
   52839   */
   52840   top -= nByte;
   52841   put2byte(&data[hdr+5], top);
   52842   assert( top+nByte <= (int)pPage->pBt->usableSize );
   52843   *pIdx = top;
   52844   return SQLITE_OK;
   52845 }
   52846 
   52847 /*
   52848 ** Return a section of the pPage->aData to the freelist.
   52849 ** The first byte of the new free block is pPage->aDisk[start]
   52850 ** and the size of the block is "size" bytes.
   52851 **
   52852 ** Most of the effort here is involved in coalesing adjacent
   52853 ** free blocks into a single big free block.
   52854 */
   52855 static int freeSpace(MemPage *pPage, int start, int size){
   52856   int addr, pbegin, hdr;
   52857   int iLast;                        /* Largest possible freeblock offset */
   52858   unsigned char *data = pPage->aData;
   52859 
   52860   assert( pPage->pBt!=0 );
   52861   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   52862   assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
   52863   assert( (start + size) <= (int)pPage->pBt->usableSize );
   52864   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   52865   assert( size>=0 );   /* Minimum cell size is 4 */
   52866 
   52867   if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
   52868     /* Overwrite deleted information with zeros when the secure_delete
   52869     ** option is enabled */
   52870     memset(&data[start], 0, size);
   52871   }
   52872 
   52873   /* Add the space back into the linked list of freeblocks.  Note that
   52874   ** even though the freeblock list was checked by btreeInitPage(),
   52875   ** btreeInitPage() did not detect overlapping cells or
   52876   ** freeblocks that overlapped cells.   Nor does it detect when the
   52877   ** cell content area exceeds the value in the page header.  If these
   52878   ** situations arise, then subsequent insert operations might corrupt
   52879   ** the freelist.  So we do need to check for corruption while scanning
   52880   ** the freelist.
   52881   */
   52882   hdr = pPage->hdrOffset;
   52883   addr = hdr + 1;
   52884   iLast = pPage->pBt->usableSize - 4;
   52885   assert( start<=iLast );
   52886   while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
   52887     if( pbegin<addr+4 ){
   52888       return SQLITE_CORRUPT_BKPT;
   52889     }
   52890     addr = pbegin;
   52891   }
   52892   if( pbegin>iLast ){
   52893     return SQLITE_CORRUPT_BKPT;
   52894   }
   52895   assert( pbegin>addr || pbegin==0 );
   52896   put2byte(&data[addr], start);
   52897   put2byte(&data[start], pbegin);
   52898   put2byte(&data[start+2], size);
   52899   pPage->nFree = pPage->nFree + (u16)size;
   52900 
   52901   /* Coalesce adjacent free blocks */
   52902   addr = hdr + 1;
   52903   while( (pbegin = get2byte(&data[addr]))>0 ){
   52904     int pnext, psize, x;
   52905     assert( pbegin>addr );
   52906     assert( pbegin <= (int)pPage->pBt->usableSize-4 );
   52907     pnext = get2byte(&data[pbegin]);
   52908     psize = get2byte(&data[pbegin+2]);
   52909     if( pbegin + psize + 3 >= pnext && pnext>0 ){
   52910       int frag = pnext - (pbegin+psize);
   52911       if( (frag<0) || (frag>(int)data[hdr+7]) ){
   52912         return SQLITE_CORRUPT_BKPT;
   52913       }
   52914       data[hdr+7] -= (u8)frag;
   52915       x = get2byte(&data[pnext]);
   52916       put2byte(&data[pbegin], x);
   52917       x = pnext + get2byte(&data[pnext+2]) - pbegin;
   52918       put2byte(&data[pbegin+2], x);
   52919     }else{
   52920       addr = pbegin;
   52921     }
   52922   }
   52923 
   52924   /* If the cell content area begins with a freeblock, remove it. */
   52925   if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
   52926     int top;
   52927     pbegin = get2byte(&data[hdr+1]);
   52928     memcpy(&data[hdr+1], &data[pbegin], 2);
   52929     top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
   52930     put2byte(&data[hdr+5], top);
   52931   }
   52932   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   52933   return SQLITE_OK;
   52934 }
   52935 
   52936 /*
   52937 ** Decode the flags byte (the first byte of the header) for a page
   52938 ** and initialize fields of the MemPage structure accordingly.
   52939 **
   52940 ** Only the following combinations are supported.  Anything different
   52941 ** indicates a corrupt database files:
   52942 **
   52943 **         PTF_ZERODATA
   52944 **         PTF_ZERODATA | PTF_LEAF
   52945 **         PTF_LEAFDATA | PTF_INTKEY
   52946 **         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
   52947 */
   52948 static int decodeFlags(MemPage *pPage, int flagByte){
   52949   BtShared *pBt;     /* A copy of pPage->pBt */
   52950 
   52951   assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
   52952   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   52953   pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
   52954   flagByte &= ~PTF_LEAF;
   52955   pPage->childPtrSize = 4-4*pPage->leaf;
   52956   pBt = pPage->pBt;
   52957   if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
   52958     pPage->intKey = 1;
   52959     pPage->hasData = pPage->leaf;
   52960     pPage->maxLocal = pBt->maxLeaf;
   52961     pPage->minLocal = pBt->minLeaf;
   52962   }else if( flagByte==PTF_ZERODATA ){
   52963     pPage->intKey = 0;
   52964     pPage->hasData = 0;
   52965     pPage->maxLocal = pBt->maxLocal;
   52966     pPage->minLocal = pBt->minLocal;
   52967   }else{
   52968     return SQLITE_CORRUPT_BKPT;
   52969   }
   52970   pPage->max1bytePayload = pBt->max1bytePayload;
   52971   return SQLITE_OK;
   52972 }
   52973 
   52974 /*
   52975 ** Initialize the auxiliary information for a disk block.
   52976 **
   52977 ** Return SQLITE_OK on success.  If we see that the page does
   52978 ** not contain a well-formed database page, then return
   52979 ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
   52980 ** guarantee that the page is well-formed.  It only shows that
   52981 ** we failed to detect any corruption.
   52982 */
   52983 static int btreeInitPage(MemPage *pPage){
   52984 
   52985   assert( pPage->pBt!=0 );
   52986   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   52987   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
   52988   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
   52989   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
   52990 
   52991   if( !pPage->isInit ){
   52992     u16 pc;            /* Address of a freeblock within pPage->aData[] */
   52993     u8 hdr;            /* Offset to beginning of page header */
   52994     u8 *data;          /* Equal to pPage->aData */
   52995     BtShared *pBt;        /* The main btree structure */
   52996     int usableSize;    /* Amount of usable space on each page */
   52997     u16 cellOffset;    /* Offset from start of page to first cell pointer */
   52998     int nFree;         /* Number of unused bytes on the page */
   52999     int top;           /* First byte of the cell content area */
   53000     int iCellFirst;    /* First allowable cell or freeblock offset */
   53001     int iCellLast;     /* Last possible cell or freeblock offset */
   53002 
   53003     pBt = pPage->pBt;
   53004 
   53005     hdr = pPage->hdrOffset;
   53006     data = pPage->aData;
   53007     if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
   53008     assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
   53009     pPage->maskPage = (u16)(pBt->pageSize - 1);
   53010     pPage->nOverflow = 0;
   53011     usableSize = pBt->usableSize;
   53012     pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
   53013     pPage->aDataEnd = &data[usableSize];
   53014     pPage->aCellIdx = &data[cellOffset];
   53015     top = get2byteNotZero(&data[hdr+5]);
   53016     pPage->nCell = get2byte(&data[hdr+3]);
   53017     if( pPage->nCell>MX_CELL(pBt) ){
   53018       /* To many cells for a single page.  The page must be corrupt */
   53019       return SQLITE_CORRUPT_BKPT;
   53020     }
   53021     testcase( pPage->nCell==MX_CELL(pBt) );
   53022 
   53023     /* A malformed database page might cause us to read past the end
   53024     ** of page when parsing a cell.
   53025     **
   53026     ** The following block of code checks early to see if a cell extends
   53027     ** past the end of a page boundary and causes SQLITE_CORRUPT to be
   53028     ** returned if it does.
   53029     */
   53030     iCellFirst = cellOffset + 2*pPage->nCell;
   53031     iCellLast = usableSize - 4;
   53032 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
   53033     {
   53034       int i;            /* Index into the cell pointer array */
   53035       int sz;           /* Size of a cell */
   53036 
   53037       if( !pPage->leaf ) iCellLast--;
   53038       for(i=0; i<pPage->nCell; i++){
   53039         pc = get2byte(&data[cellOffset+i*2]);
   53040         testcase( pc==iCellFirst );
   53041         testcase( pc==iCellLast );
   53042         if( pc<iCellFirst || pc>iCellLast ){
   53043           return SQLITE_CORRUPT_BKPT;
   53044         }
   53045         sz = cellSizePtr(pPage, &data[pc]);
   53046         testcase( pc+sz==usableSize );
   53047         if( pc+sz>usableSize ){
   53048           return SQLITE_CORRUPT_BKPT;
   53049         }
   53050       }
   53051       if( !pPage->leaf ) iCellLast++;
   53052     }
   53053 #endif
   53054 
   53055     /* Compute the total free space on the page */
   53056     pc = get2byte(&data[hdr+1]);
   53057     nFree = data[hdr+7] + top;
   53058     while( pc>0 ){
   53059       u16 next, size;
   53060       if( pc<iCellFirst || pc>iCellLast ){
   53061         /* Start of free block is off the page */
   53062         return SQLITE_CORRUPT_BKPT;
   53063       }
   53064       next = get2byte(&data[pc]);
   53065       size = get2byte(&data[pc+2]);
   53066       if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
   53067         /* Free blocks must be in ascending order. And the last byte of
   53068         ** the free-block must lie on the database page.  */
   53069         return SQLITE_CORRUPT_BKPT;
   53070       }
   53071       nFree = nFree + size;
   53072       pc = next;
   53073     }
   53074 
   53075     /* At this point, nFree contains the sum of the offset to the start
   53076     ** of the cell-content area plus the number of free bytes within
   53077     ** the cell-content area. If this is greater than the usable-size
   53078     ** of the page, then the page must be corrupted. This check also
   53079     ** serves to verify that the offset to the start of the cell-content
   53080     ** area, according to the page header, lies within the page.
   53081     */
   53082     if( nFree>usableSize ){
   53083       return SQLITE_CORRUPT_BKPT;
   53084     }
   53085     pPage->nFree = (u16)(nFree - iCellFirst);
   53086     pPage->isInit = 1;
   53087   }
   53088   return SQLITE_OK;
   53089 }
   53090 
   53091 /*
   53092 ** Set up a raw page so that it looks like a database page holding
   53093 ** no entries.
   53094 */
   53095 static void zeroPage(MemPage *pPage, int flags){
   53096   unsigned char *data = pPage->aData;
   53097   BtShared *pBt = pPage->pBt;
   53098   u8 hdr = pPage->hdrOffset;
   53099   u16 first;
   53100 
   53101   assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
   53102   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
   53103   assert( sqlite3PagerGetData(pPage->pDbPage) == data );
   53104   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   53105   assert( sqlite3_mutex_held(pBt->mutex) );
   53106   if( pBt->btsFlags & BTS_SECURE_DELETE ){
   53107     memset(&data[hdr], 0, pBt->usableSize - hdr);
   53108   }
   53109   data[hdr] = (char)flags;
   53110   first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
   53111   memset(&data[hdr+1], 0, 4);
   53112   data[hdr+7] = 0;
   53113   put2byte(&data[hdr+5], pBt->usableSize);
   53114   pPage->nFree = (u16)(pBt->usableSize - first);
   53115   decodeFlags(pPage, flags);
   53116   pPage->cellOffset = first;
   53117   pPage->aDataEnd = &data[pBt->usableSize];
   53118   pPage->aCellIdx = &data[first];
   53119   pPage->nOverflow = 0;
   53120   assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
   53121   pPage->maskPage = (u16)(pBt->pageSize - 1);
   53122   pPage->nCell = 0;
   53123   pPage->isInit = 1;
   53124 }
   53125 
   53126 
   53127 /*
   53128 ** Convert a DbPage obtained from the pager into a MemPage used by
   53129 ** the btree layer.
   53130 */
   53131 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
   53132   MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
   53133   pPage->aData = sqlite3PagerGetData(pDbPage);
   53134   pPage->pDbPage = pDbPage;
   53135   pPage->pBt = pBt;
   53136   pPage->pgno = pgno;
   53137   pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
   53138   return pPage;
   53139 }
   53140 
   53141 /*
   53142 ** Get a page from the pager.  Initialize the MemPage.pBt and
   53143 ** MemPage.aData elements if needed.
   53144 **
   53145 ** If the noContent flag is set, it means that we do not care about
   53146 ** the content of the page at this time.  So do not go to the disk
   53147 ** to fetch the content.  Just fill in the content with zeros for now.
   53148 ** If in the future we call sqlite3PagerWrite() on this page, that
   53149 ** means we have started to be concerned about content and the disk
   53150 ** read should occur at that point.
   53151 */
   53152 static int btreeGetPage(
   53153   BtShared *pBt,       /* The btree */
   53154   Pgno pgno,           /* Number of the page to fetch */
   53155   MemPage **ppPage,    /* Return the page in this parameter */
   53156   int flags            /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
   53157 ){
   53158   int rc;
   53159   DbPage *pDbPage;
   53160 
   53161   assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
   53162   assert( sqlite3_mutex_held(pBt->mutex) );
   53163   rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
   53164   if( rc ) return rc;
   53165   *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
   53166   return SQLITE_OK;
   53167 }
   53168 
   53169 /*
   53170 ** Retrieve a page from the pager cache. If the requested page is not
   53171 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
   53172 ** MemPage.aData elements if needed.
   53173 */
   53174 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
   53175   DbPage *pDbPage;
   53176   assert( sqlite3_mutex_held(pBt->mutex) );
   53177   pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
   53178   if( pDbPage ){
   53179     return btreePageFromDbPage(pDbPage, pgno, pBt);
   53180   }
   53181   return 0;
   53182 }
   53183 
   53184 /*
   53185 ** Return the size of the database file in pages. If there is any kind of
   53186 ** error, return ((unsigned int)-1).
   53187 */
   53188 static Pgno btreePagecount(BtShared *pBt){
   53189   return pBt->nPage;
   53190 }
   53191 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
   53192   assert( sqlite3BtreeHoldsMutex(p) );
   53193   assert( ((p->pBt->nPage)&0x8000000)==0 );
   53194   return btreePagecount(p->pBt);
   53195 }
   53196 
   53197 /*
   53198 ** Get a page from the pager and initialize it.  This routine is just a
   53199 ** convenience wrapper around separate calls to btreeGetPage() and
   53200 ** btreeInitPage().
   53201 **
   53202 ** If an error occurs, then the value *ppPage is set to is undefined. It
   53203 ** may remain unchanged, or it may be set to an invalid value.
   53204 */
   53205 static int getAndInitPage(
   53206   BtShared *pBt,                  /* The database file */
   53207   Pgno pgno,                      /* Number of the page to get */
   53208   MemPage **ppPage,               /* Write the page pointer here */
   53209   int bReadonly                   /* PAGER_GET_READONLY or 0 */
   53210 ){
   53211   int rc;
   53212   assert( sqlite3_mutex_held(pBt->mutex) );
   53213   assert( bReadonly==PAGER_GET_READONLY || bReadonly==0 );
   53214 
   53215   if( pgno>btreePagecount(pBt) ){
   53216     rc = SQLITE_CORRUPT_BKPT;
   53217   }else{
   53218     rc = btreeGetPage(pBt, pgno, ppPage, bReadonly);
   53219     if( rc==SQLITE_OK && (*ppPage)->isInit==0 ){
   53220       rc = btreeInitPage(*ppPage);
   53221       if( rc!=SQLITE_OK ){
   53222         releasePage(*ppPage);
   53223       }
   53224     }
   53225   }
   53226 
   53227   testcase( pgno==0 );
   53228   assert( pgno!=0 || rc==SQLITE_CORRUPT );
   53229   return rc;
   53230 }
   53231 
   53232 /*
   53233 ** Release a MemPage.  This should be called once for each prior
   53234 ** call to btreeGetPage.
   53235 */
   53236 static void releasePage(MemPage *pPage){
   53237   if( pPage ){
   53238     assert( pPage->aData );
   53239     assert( pPage->pBt );
   53240     assert( pPage->pDbPage!=0 );
   53241     assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
   53242     assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
   53243     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   53244     sqlite3PagerUnrefNotNull(pPage->pDbPage);
   53245   }
   53246 }
   53247 
   53248 /*
   53249 ** During a rollback, when the pager reloads information into the cache
   53250 ** so that the cache is restored to its original state at the start of
   53251 ** the transaction, for each page restored this routine is called.
   53252 **
   53253 ** This routine needs to reset the extra data section at the end of the
   53254 ** page to agree with the restored data.
   53255 */
   53256 static void pageReinit(DbPage *pData){
   53257   MemPage *pPage;
   53258   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
   53259   assert( sqlite3PagerPageRefcount(pData)>0 );
   53260   if( pPage->isInit ){
   53261     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   53262     pPage->isInit = 0;
   53263     if( sqlite3PagerPageRefcount(pData)>1 ){
   53264       /* pPage might not be a btree page;  it might be an overflow page
   53265       ** or ptrmap page or a free page.  In those cases, the following
   53266       ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
   53267       ** But no harm is done by this.  And it is very important that
   53268       ** btreeInitPage() be called on every btree page so we make
   53269       ** the call for every page that comes in for re-initing. */
   53270       btreeInitPage(pPage);
   53271     }
   53272   }
   53273 }
   53274 
   53275 /*
   53276 ** Invoke the busy handler for a btree.
   53277 */
   53278 static int btreeInvokeBusyHandler(void *pArg){
   53279   BtShared *pBt = (BtShared*)pArg;
   53280   assert( pBt->db );
   53281   assert( sqlite3_mutex_held(pBt->db->mutex) );
   53282   return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
   53283 }
   53284 
   53285 /*
   53286 ** Open a database file.
   53287 **
   53288 ** zFilename is the name of the database file.  If zFilename is NULL
   53289 ** then an ephemeral database is created.  The ephemeral database might
   53290 ** be exclusively in memory, or it might use a disk-based memory cache.
   53291 ** Either way, the ephemeral database will be automatically deleted
   53292 ** when sqlite3BtreeClose() is called.
   53293 **
   53294 ** If zFilename is ":memory:" then an in-memory database is created
   53295 ** that is automatically destroyed when it is closed.
   53296 **
   53297 ** The "flags" parameter is a bitmask that might contain bits like
   53298 ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
   53299 **
   53300 ** If the database is already opened in the same database connection
   53301 ** and we are in shared cache mode, then the open will fail with an
   53302 ** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
   53303 ** objects in the same database connection since doing so will lead
   53304 ** to problems with locking.
   53305 */
   53306 SQLITE_PRIVATE int sqlite3BtreeOpen(
   53307   sqlite3_vfs *pVfs,      /* VFS to use for this b-tree */
   53308   const char *zFilename,  /* Name of the file containing the BTree database */
   53309   sqlite3 *db,            /* Associated database handle */
   53310   Btree **ppBtree,        /* Pointer to new Btree object written here */
   53311   int flags,              /* Options */
   53312   int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
   53313 ){
   53314   BtShared *pBt = 0;             /* Shared part of btree structure */
   53315   Btree *p;                      /* Handle to return */
   53316   sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
   53317   int rc = SQLITE_OK;            /* Result code from this function */
   53318   u8 nReserve;                   /* Byte of unused space on each page */
   53319   unsigned char zDbHeader[100];  /* Database header content */
   53320 
   53321   /* True if opening an ephemeral, temporary database */
   53322   const int isTempDb = zFilename==0 || zFilename[0]==0;
   53323 
   53324   /* Set the variable isMemdb to true for an in-memory database, or
   53325   ** false for a file-based database.
   53326   */
   53327 #ifdef SQLITE_OMIT_MEMORYDB
   53328   const int isMemdb = 0;
   53329 #else
   53330   const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
   53331                        || (isTempDb && sqlite3TempInMemory(db))
   53332                        || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
   53333 #endif
   53334 
   53335   assert( db!=0 );
   53336   assert( pVfs!=0 );
   53337   assert( sqlite3_mutex_held(db->mutex) );
   53338   assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
   53339 
   53340   /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
   53341   assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
   53342 
   53343   /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
   53344   assert( (flags & BTREE_SINGLE)==0 || isTempDb );
   53345 
   53346   if( isMemdb ){
   53347     flags |= BTREE_MEMORY;
   53348   }
   53349   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
   53350     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
   53351   }
   53352   p = sqlite3MallocZero(sizeof(Btree));
   53353   if( !p ){
   53354     return SQLITE_NOMEM;
   53355   }
   53356   p->inTrans = TRANS_NONE;
   53357   p->db = db;
   53358 #ifndef SQLITE_OMIT_SHARED_CACHE
   53359   p->lock.pBtree = p;
   53360   p->lock.iTable = 1;
   53361 #endif
   53362 
   53363 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
   53364   /*
   53365   ** If this Btree is a candidate for shared cache, try to find an
   53366   ** existing BtShared object that we can share with
   53367   */
   53368   if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
   53369     if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
   53370       int nFullPathname = pVfs->mxPathname+1;
   53371       char *zFullPathname = sqlite3Malloc(nFullPathname);
   53372       MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
   53373       p->sharable = 1;
   53374       if( !zFullPathname ){
   53375         sqlite3_free(p);
   53376         return SQLITE_NOMEM;
   53377       }
   53378       if( isMemdb ){
   53379         memcpy(zFullPathname, zFilename, sqlite3Strlen30(zFilename)+1);
   53380       }else{
   53381         rc = sqlite3OsFullPathname(pVfs, zFilename,
   53382                                    nFullPathname, zFullPathname);
   53383         if( rc ){
   53384           sqlite3_free(zFullPathname);
   53385           sqlite3_free(p);
   53386           return rc;
   53387         }
   53388       }
   53389 #if SQLITE_THREADSAFE
   53390       mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
   53391       sqlite3_mutex_enter(mutexOpen);
   53392       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   53393       sqlite3_mutex_enter(mutexShared);
   53394 #endif
   53395       for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
   53396         assert( pBt->nRef>0 );
   53397         if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
   53398                  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
   53399           int iDb;
   53400           for(iDb=db->nDb-1; iDb>=0; iDb--){
   53401             Btree *pExisting = db->aDb[iDb].pBt;
   53402             if( pExisting && pExisting->pBt==pBt ){
   53403               sqlite3_mutex_leave(mutexShared);
   53404               sqlite3_mutex_leave(mutexOpen);
   53405               sqlite3_free(zFullPathname);
   53406               sqlite3_free(p);
   53407               return SQLITE_CONSTRAINT;
   53408             }
   53409           }
   53410           p->pBt = pBt;
   53411           pBt->nRef++;
   53412           break;
   53413         }
   53414       }
   53415       sqlite3_mutex_leave(mutexShared);
   53416       sqlite3_free(zFullPathname);
   53417     }
   53418 #ifdef SQLITE_DEBUG
   53419     else{
   53420       /* In debug mode, we mark all persistent databases as sharable
   53421       ** even when they are not.  This exercises the locking code and
   53422       ** gives more opportunity for asserts(sqlite3_mutex_held())
   53423       ** statements to find locking problems.
   53424       */
   53425       p->sharable = 1;
   53426     }
   53427 #endif
   53428   }
   53429 #endif
   53430   if( pBt==0 ){
   53431     /*
   53432     ** The following asserts make sure that structures used by the btree are
   53433     ** the right size.  This is to guard against size changes that result
   53434     ** when compiling on a different architecture.
   53435     */
   53436     assert( sizeof(i64)==8 || sizeof(i64)==4 );
   53437     assert( sizeof(u64)==8 || sizeof(u64)==4 );
   53438     assert( sizeof(u32)==4 );
   53439     assert( sizeof(u16)==2 );
   53440     assert( sizeof(Pgno)==4 );
   53441 
   53442     pBt = sqlite3MallocZero( sizeof(*pBt) );
   53443     if( pBt==0 ){
   53444       rc = SQLITE_NOMEM;
   53445       goto btree_open_out;
   53446     }
   53447     rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
   53448                           EXTRA_SIZE, flags, vfsFlags, pageReinit);
   53449     if( rc==SQLITE_OK ){
   53450       sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
   53451       rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
   53452     }
   53453     if( rc!=SQLITE_OK ){
   53454       goto btree_open_out;
   53455     }
   53456     pBt->openFlags = (u8)flags;
   53457     pBt->db = db;
   53458     sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
   53459     p->pBt = pBt;
   53460 
   53461     pBt->pCursor = 0;
   53462     pBt->pPage1 = 0;
   53463     if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
   53464 #ifdef SQLITE_SECURE_DELETE
   53465     pBt->btsFlags |= BTS_SECURE_DELETE;
   53466 #endif
   53467     pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
   53468     if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
   53469          || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
   53470       pBt->pageSize = 0;
   53471 #ifndef SQLITE_OMIT_AUTOVACUUM
   53472       /* If the magic name ":memory:" will create an in-memory database, then
   53473       ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
   53474       ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
   53475       ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
   53476       ** regular file-name. In this case the auto-vacuum applies as per normal.
   53477       */
   53478       if( zFilename && !isMemdb ){
   53479         pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
   53480         pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
   53481       }
   53482 #endif
   53483       nReserve = 0;
   53484     }else{
   53485       nReserve = zDbHeader[20];
   53486       pBt->btsFlags |= BTS_PAGESIZE_FIXED;
   53487 #ifndef SQLITE_OMIT_AUTOVACUUM
   53488       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
   53489       pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
   53490 #endif
   53491     }
   53492     rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
   53493     if( rc ) goto btree_open_out;
   53494     pBt->usableSize = pBt->pageSize - nReserve;
   53495     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
   53496 
   53497 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
   53498     /* Add the new BtShared object to the linked list sharable BtShareds.
   53499     */
   53500     if( p->sharable ){
   53501       MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
   53502       pBt->nRef = 1;
   53503       MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
   53504       if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
   53505         pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
   53506         if( pBt->mutex==0 ){
   53507           rc = SQLITE_NOMEM;
   53508           db->mallocFailed = 0;
   53509           goto btree_open_out;
   53510         }
   53511       }
   53512       sqlite3_mutex_enter(mutexShared);
   53513       pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
   53514       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
   53515       sqlite3_mutex_leave(mutexShared);
   53516     }
   53517 #endif
   53518   }
   53519 
   53520 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
   53521   /* If the new Btree uses a sharable pBtShared, then link the new
   53522   ** Btree into the list of all sharable Btrees for the same connection.
   53523   ** The list is kept in ascending order by pBt address.
   53524   */
   53525   if( p->sharable ){
   53526     int i;
   53527     Btree *pSib;
   53528     for(i=0; i<db->nDb; i++){
   53529       if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
   53530         while( pSib->pPrev ){ pSib = pSib->pPrev; }
   53531         if( p->pBt<pSib->pBt ){
   53532           p->pNext = pSib;
   53533           p->pPrev = 0;
   53534           pSib->pPrev = p;
   53535         }else{
   53536           while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
   53537             pSib = pSib->pNext;
   53538           }
   53539           p->pNext = pSib->pNext;
   53540           p->pPrev = pSib;
   53541           if( p->pNext ){
   53542             p->pNext->pPrev = p;
   53543           }
   53544           pSib->pNext = p;
   53545         }
   53546         break;
   53547       }
   53548     }
   53549   }
   53550 #endif
   53551   *ppBtree = p;
   53552 
   53553 btree_open_out:
   53554   if( rc!=SQLITE_OK ){
   53555     if( pBt && pBt->pPager ){
   53556       sqlite3PagerClose(pBt->pPager);
   53557     }
   53558     sqlite3_free(pBt);
   53559     sqlite3_free(p);
   53560     *ppBtree = 0;
   53561   }else{
   53562     /* If the B-Tree was successfully opened, set the pager-cache size to the
   53563     ** default value. Except, when opening on an existing shared pager-cache,
   53564     ** do not change the pager-cache size.
   53565     */
   53566     if( sqlite3BtreeSchema(p, 0, 0)==0 ){
   53567       sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
   53568     }
   53569   }
   53570   if( mutexOpen ){
   53571     assert( sqlite3_mutex_held(mutexOpen) );
   53572     sqlite3_mutex_leave(mutexOpen);
   53573   }
   53574   return rc;
   53575 }
   53576 
   53577 /*
   53578 ** Decrement the BtShared.nRef counter.  When it reaches zero,
   53579 ** remove the BtShared structure from the sharing list.  Return
   53580 ** true if the BtShared.nRef counter reaches zero and return
   53581 ** false if it is still positive.
   53582 */
   53583 static int removeFromSharingList(BtShared *pBt){
   53584 #ifndef SQLITE_OMIT_SHARED_CACHE
   53585   MUTEX_LOGIC( sqlite3_mutex *pMaster; )
   53586   BtShared *pList;
   53587   int removed = 0;
   53588 
   53589   assert( sqlite3_mutex_notheld(pBt->mutex) );
   53590   MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
   53591   sqlite3_mutex_enter(pMaster);
   53592   pBt->nRef--;
   53593   if( pBt->nRef<=0 ){
   53594     if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
   53595       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
   53596     }else{
   53597       pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
   53598       while( ALWAYS(pList) && pList->pNext!=pBt ){
   53599         pList=pList->pNext;
   53600       }
   53601       if( ALWAYS(pList) ){
   53602         pList->pNext = pBt->pNext;
   53603       }
   53604     }
   53605     if( SQLITE_THREADSAFE ){
   53606       sqlite3_mutex_free(pBt->mutex);
   53607     }
   53608     removed = 1;
   53609   }
   53610   sqlite3_mutex_leave(pMaster);
   53611   return removed;
   53612 #else
   53613   return 1;
   53614 #endif
   53615 }
   53616 
   53617 /*
   53618 ** Make sure pBt->pTmpSpace points to an allocation of
   53619 ** MX_CELL_SIZE(pBt) bytes.
   53620 */
   53621 static void allocateTempSpace(BtShared *pBt){
   53622   if( !pBt->pTmpSpace ){
   53623     pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
   53624 
   53625     /* One of the uses of pBt->pTmpSpace is to format cells before
   53626     ** inserting them into a leaf page (function fillInCell()). If
   53627     ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
   53628     ** by the various routines that manipulate binary cells. Which
   53629     ** can mean that fillInCell() only initializes the first 2 or 3
   53630     ** bytes of pTmpSpace, but that the first 4 bytes are copied from
   53631     ** it into a database page. This is not actually a problem, but it
   53632     ** does cause a valgrind error when the 1 or 2 bytes of unitialized
   53633     ** data is passed to system call write(). So to avoid this error,
   53634     ** zero the first 4 bytes of temp space here.  */
   53635     if( pBt->pTmpSpace ) memset(pBt->pTmpSpace, 0, 4);
   53636   }
   53637 }
   53638 
   53639 /*
   53640 ** Free the pBt->pTmpSpace allocation
   53641 */
   53642 static void freeTempSpace(BtShared *pBt){
   53643   sqlite3PageFree( pBt->pTmpSpace);
   53644   pBt->pTmpSpace = 0;
   53645 }
   53646 
   53647 /*
   53648 ** Close an open database and invalidate all cursors.
   53649 */
   53650 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
   53651   BtShared *pBt = p->pBt;
   53652   BtCursor *pCur;
   53653 
   53654   /* Close all cursors opened via this handle.  */
   53655   assert( sqlite3_mutex_held(p->db->mutex) );
   53656   sqlite3BtreeEnter(p);
   53657   pCur = pBt->pCursor;
   53658   while( pCur ){
   53659     BtCursor *pTmp = pCur;
   53660     pCur = pCur->pNext;
   53661     if( pTmp->pBtree==p ){
   53662       sqlite3BtreeCloseCursor(pTmp);
   53663     }
   53664   }
   53665 
   53666   /* Rollback any active transaction and free the handle structure.
   53667   ** The call to sqlite3BtreeRollback() drops any table-locks held by
   53668   ** this handle.
   53669   */
   53670   sqlite3BtreeRollback(p, SQLITE_OK);
   53671   sqlite3BtreeLeave(p);
   53672 
   53673   /* If there are still other outstanding references to the shared-btree
   53674   ** structure, return now. The remainder of this procedure cleans
   53675   ** up the shared-btree.
   53676   */
   53677   assert( p->wantToLock==0 && p->locked==0 );
   53678   if( !p->sharable || removeFromSharingList(pBt) ){
   53679     /* The pBt is no longer on the sharing list, so we can access
   53680     ** it without having to hold the mutex.
   53681     **
   53682     ** Clean out and delete the BtShared object.
   53683     */
   53684     assert( !pBt->pCursor );
   53685     sqlite3PagerClose(pBt->pPager);
   53686     if( pBt->xFreeSchema && pBt->pSchema ){
   53687       pBt->xFreeSchema(pBt->pSchema);
   53688     }
   53689     sqlite3DbFree(0, pBt->pSchema);
   53690     freeTempSpace(pBt);
   53691     sqlite3_free(pBt);
   53692   }
   53693 
   53694 #ifndef SQLITE_OMIT_SHARED_CACHE
   53695   assert( p->wantToLock==0 );
   53696   assert( p->locked==0 );
   53697   if( p->pPrev ) p->pPrev->pNext = p->pNext;
   53698   if( p->pNext ) p->pNext->pPrev = p->pPrev;
   53699 #endif
   53700 
   53701   sqlite3_free(p);
   53702   return SQLITE_OK;
   53703 }
   53704 
   53705 /*
   53706 ** Change the limit on the number of pages allowed in the cache.
   53707 **
   53708 ** The maximum number of cache pages is set to the absolute
   53709 ** value of mxPage.  If mxPage is negative, the pager will
   53710 ** operate asynchronously - it will not stop to do fsync()s
   53711 ** to insure data is written to the disk surface before
   53712 ** continuing.  Transactions still work if synchronous is off,
   53713 ** and the database cannot be corrupted if this program
   53714 ** crashes.  But if the operating system crashes or there is
   53715 ** an abrupt power failure when synchronous is off, the database
   53716 ** could be left in an inconsistent and unrecoverable state.
   53717 ** Synchronous is on by default so database corruption is not
   53718 ** normally a worry.
   53719 */
   53720 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
   53721   BtShared *pBt = p->pBt;
   53722   assert( sqlite3_mutex_held(p->db->mutex) );
   53723   sqlite3BtreeEnter(p);
   53724   sqlite3PagerSetCachesize(pBt->pPager, mxPage);
   53725   sqlite3BtreeLeave(p);
   53726   return SQLITE_OK;
   53727 }
   53728 
   53729 #if SQLITE_MAX_MMAP_SIZE>0
   53730 /*
   53731 ** Change the limit on the amount of the database file that may be
   53732 ** memory mapped.
   53733 */
   53734 SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
   53735   BtShared *pBt = p->pBt;
   53736   assert( sqlite3_mutex_held(p->db->mutex) );
   53737   sqlite3BtreeEnter(p);
   53738   sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
   53739   sqlite3BtreeLeave(p);
   53740   return SQLITE_OK;
   53741 }
   53742 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
   53743 
   53744 /*
   53745 ** Change the way data is synced to disk in order to increase or decrease
   53746 ** how well the database resists damage due to OS crashes and power
   53747 ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
   53748 ** there is a high probability of damage)  Level 2 is the default.  There
   53749 ** is a very low but non-zero probability of damage.  Level 3 reduces the
   53750 ** probability of damage to near zero but with a write performance reduction.
   53751 */
   53752 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   53753 SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
   53754   Btree *p,              /* The btree to set the safety level on */
   53755   unsigned pgFlags       /* Various PAGER_* flags */
   53756 ){
   53757   BtShared *pBt = p->pBt;
   53758   assert( sqlite3_mutex_held(p->db->mutex) );
   53759   sqlite3BtreeEnter(p);
   53760   sqlite3PagerSetFlags(pBt->pPager, pgFlags);
   53761   sqlite3BtreeLeave(p);
   53762   return SQLITE_OK;
   53763 }
   53764 #endif
   53765 
   53766 /*
   53767 ** Return TRUE if the given btree is set to safety level 1.  In other
   53768 ** words, return TRUE if no sync() occurs on the disk files.
   53769 */
   53770 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
   53771   BtShared *pBt = p->pBt;
   53772   int rc;
   53773   assert( sqlite3_mutex_held(p->db->mutex) );
   53774   sqlite3BtreeEnter(p);
   53775   assert( pBt && pBt->pPager );
   53776   rc = sqlite3PagerNosync(pBt->pPager);
   53777   sqlite3BtreeLeave(p);
   53778   return rc;
   53779 }
   53780 
   53781 /*
   53782 ** Change the default pages size and the number of reserved bytes per page.
   53783 ** Or, if the page size has already been fixed, return SQLITE_READONLY
   53784 ** without changing anything.
   53785 **
   53786 ** The page size must be a power of 2 between 512 and 65536.  If the page
   53787 ** size supplied does not meet this constraint then the page size is not
   53788 ** changed.
   53789 **
   53790 ** Page sizes are constrained to be a power of two so that the region
   53791 ** of the database file used for locking (beginning at PENDING_BYTE,
   53792 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
   53793 ** at the beginning of a page.
   53794 **
   53795 ** If parameter nReserve is less than zero, then the number of reserved
   53796 ** bytes per page is left unchanged.
   53797 **
   53798 ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
   53799 ** and autovacuum mode can no longer be changed.
   53800 */
   53801 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
   53802   int rc = SQLITE_OK;
   53803   BtShared *pBt = p->pBt;
   53804   assert( nReserve>=-1 && nReserve<=255 );
   53805   sqlite3BtreeEnter(p);
   53806   if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
   53807     sqlite3BtreeLeave(p);
   53808     return SQLITE_READONLY;
   53809   }
   53810   if( nReserve<0 ){
   53811     nReserve = pBt->pageSize - pBt->usableSize;
   53812   }
   53813   assert( nReserve>=0 && nReserve<=255 );
   53814   if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
   53815         ((pageSize-1)&pageSize)==0 ){
   53816     assert( (pageSize & 7)==0 );
   53817     assert( !pBt->pPage1 && !pBt->pCursor );
   53818     pBt->pageSize = (u32)pageSize;
   53819     freeTempSpace(pBt);
   53820   }
   53821   rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
   53822   pBt->usableSize = pBt->pageSize - (u16)nReserve;
   53823   if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
   53824   sqlite3BtreeLeave(p);
   53825   return rc;
   53826 }
   53827 
   53828 /*
   53829 ** Return the currently defined page size
   53830 */
   53831 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
   53832   return p->pBt->pageSize;
   53833 }
   53834 
   53835 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
   53836 /*
   53837 ** This function is similar to sqlite3BtreeGetReserve(), except that it
   53838 ** may only be called if it is guaranteed that the b-tree mutex is already
   53839 ** held.
   53840 **
   53841 ** This is useful in one special case in the backup API code where it is
   53842 ** known that the shared b-tree mutex is held, but the mutex on the
   53843 ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
   53844 ** were to be called, it might collide with some other operation on the
   53845 ** database handle that owns *p, causing undefined behavior.
   53846 */
   53847 SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
   53848   assert( sqlite3_mutex_held(p->pBt->mutex) );
   53849   return p->pBt->pageSize - p->pBt->usableSize;
   53850 }
   53851 #endif /* SQLITE_HAS_CODEC || SQLITE_DEBUG */
   53852 
   53853 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
   53854 /*
   53855 ** Return the number of bytes of space at the end of every page that
   53856 ** are intentually left unused.  This is the "reserved" space that is
   53857 ** sometimes used by extensions.
   53858 */
   53859 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
   53860   int n;
   53861   sqlite3BtreeEnter(p);
   53862   n = p->pBt->pageSize - p->pBt->usableSize;
   53863   sqlite3BtreeLeave(p);
   53864   return n;
   53865 }
   53866 
   53867 /*
   53868 ** Set the maximum page count for a database if mxPage is positive.
   53869 ** No changes are made if mxPage is 0 or negative.
   53870 ** Regardless of the value of mxPage, return the maximum page count.
   53871 */
   53872 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
   53873   int n;
   53874   sqlite3BtreeEnter(p);
   53875   n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
   53876   sqlite3BtreeLeave(p);
   53877   return n;
   53878 }
   53879 
   53880 /*
   53881 ** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1.  If newFlag is -1,
   53882 ** then make no changes.  Always return the value of the BTS_SECURE_DELETE
   53883 ** setting after the change.
   53884 */
   53885 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
   53886   int b;
   53887   if( p==0 ) return 0;
   53888   sqlite3BtreeEnter(p);
   53889   if( newFlag>=0 ){
   53890     p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
   53891     if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
   53892   }
   53893   b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
   53894   sqlite3BtreeLeave(p);
   53895   return b;
   53896 }
   53897 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
   53898 
   53899 /*
   53900 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
   53901 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
   53902 ** is disabled. The default value for the auto-vacuum property is
   53903 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
   53904 */
   53905 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
   53906 #ifdef SQLITE_OMIT_AUTOVACUUM
   53907   return SQLITE_READONLY;
   53908 #else
   53909   BtShared *pBt = p->pBt;
   53910   int rc = SQLITE_OK;
   53911   u8 av = (u8)autoVacuum;
   53912 
   53913   sqlite3BtreeEnter(p);
   53914   if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
   53915     rc = SQLITE_READONLY;
   53916   }else{
   53917     pBt->autoVacuum = av ?1:0;
   53918     pBt->incrVacuum = av==2 ?1:0;
   53919   }
   53920   sqlite3BtreeLeave(p);
   53921   return rc;
   53922 #endif
   53923 }
   53924 
   53925 /*
   53926 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
   53927 ** enabled 1 is returned. Otherwise 0.
   53928 */
   53929 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
   53930 #ifdef SQLITE_OMIT_AUTOVACUUM
   53931   return BTREE_AUTOVACUUM_NONE;
   53932 #else
   53933   int rc;
   53934   sqlite3BtreeEnter(p);
   53935   rc = (
   53936     (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
   53937     (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
   53938     BTREE_AUTOVACUUM_INCR
   53939   );
   53940   sqlite3BtreeLeave(p);
   53941   return rc;
   53942 #endif
   53943 }
   53944 
   53945 
   53946 /*
   53947 ** Get a reference to pPage1 of the database file.  This will
   53948 ** also acquire a readlock on that file.
   53949 **
   53950 ** SQLITE_OK is returned on success.  If the file is not a
   53951 ** well-formed database file, then SQLITE_CORRUPT is returned.
   53952 ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
   53953 ** is returned if we run out of memory.
   53954 */
   53955 static int lockBtree(BtShared *pBt){
   53956   int rc;              /* Result code from subfunctions */
   53957   MemPage *pPage1;     /* Page 1 of the database file */
   53958   int nPage;           /* Number of pages in the database */
   53959   int nPageFile = 0;   /* Number of pages in the database file */
   53960   int nPageHeader;     /* Number of pages in the database according to hdr */
   53961 
   53962   assert( sqlite3_mutex_held(pBt->mutex) );
   53963   assert( pBt->pPage1==0 );
   53964   rc = sqlite3PagerSharedLock(pBt->pPager);
   53965   if( rc!=SQLITE_OK ) return rc;
   53966   rc = btreeGetPage(pBt, 1, &pPage1, 0);
   53967   if( rc!=SQLITE_OK ) return rc;
   53968 
   53969   /* Do some checking to help insure the file we opened really is
   53970   ** a valid database file.
   53971   */
   53972   nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
   53973   sqlite3PagerPagecount(pBt->pPager, &nPageFile);
   53974   if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
   53975     nPage = nPageFile;
   53976   }
   53977   if( nPage>0 ){
   53978     u32 pageSize;
   53979     u32 usableSize;
   53980     u8 *page1 = pPage1->aData;
   53981     rc = SQLITE_NOTADB;
   53982     if( memcmp(page1, zMagicHeader, 16)!=0 ){
   53983       goto page1_init_failed;
   53984     }
   53985 
   53986 #ifdef SQLITE_OMIT_WAL
   53987     if( page1[18]>1 ){
   53988       pBt->btsFlags |= BTS_READ_ONLY;
   53989     }
   53990     if( page1[19]>1 ){
   53991       goto page1_init_failed;
   53992     }
   53993 #else
   53994     if( page1[18]>2 ){
   53995       pBt->btsFlags |= BTS_READ_ONLY;
   53996     }
   53997     if( page1[19]>2 ){
   53998       goto page1_init_failed;
   53999     }
   54000 
   54001     /* If the write version is set to 2, this database should be accessed
   54002     ** in WAL mode. If the log is not already open, open it now. Then
   54003     ** return SQLITE_OK and return without populating BtShared.pPage1.
   54004     ** The caller detects this and calls this function again. This is
   54005     ** required as the version of page 1 currently in the page1 buffer
   54006     ** may not be the latest version - there may be a newer one in the log
   54007     ** file.
   54008     */
   54009     if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
   54010       int isOpen = 0;
   54011       rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
   54012       if( rc!=SQLITE_OK ){
   54013         goto page1_init_failed;
   54014       }else if( isOpen==0 ){
   54015         releasePage(pPage1);
   54016         return SQLITE_OK;
   54017       }
   54018       rc = SQLITE_NOTADB;
   54019     }
   54020 #endif
   54021 
   54022     /* The maximum embedded fraction must be exactly 25%.  And the minimum
   54023     ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
   54024     ** The original design allowed these amounts to vary, but as of
   54025     ** version 3.6.0, we require them to be fixed.
   54026     */
   54027     if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
   54028       goto page1_init_failed;
   54029     }
   54030     pageSize = (page1[16]<<8) | (page1[17]<<16);
   54031     if( ((pageSize-1)&pageSize)!=0
   54032      || pageSize>SQLITE_MAX_PAGE_SIZE
   54033      || pageSize<=256
   54034     ){
   54035       goto page1_init_failed;
   54036     }
   54037     assert( (pageSize & 7)==0 );
   54038     usableSize = pageSize - page1[20];
   54039     if( (u32)pageSize!=pBt->pageSize ){
   54040       /* After reading the first page of the database assuming a page size
   54041       ** of BtShared.pageSize, we have discovered that the page-size is
   54042       ** actually pageSize. Unlock the database, leave pBt->pPage1 at
   54043       ** zero and return SQLITE_OK. The caller will call this function
   54044       ** again with the correct page-size.
   54045       */
   54046       releasePage(pPage1);
   54047       pBt->usableSize = usableSize;
   54048       pBt->pageSize = pageSize;
   54049       freeTempSpace(pBt);
   54050       rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
   54051                                    pageSize-usableSize);
   54052       return rc;
   54053     }
   54054     if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
   54055       rc = SQLITE_CORRUPT_BKPT;
   54056       goto page1_init_failed;
   54057     }
   54058     if( usableSize<480 ){
   54059       goto page1_init_failed;
   54060     }
   54061     pBt->pageSize = pageSize;
   54062     pBt->usableSize = usableSize;
   54063 #ifndef SQLITE_OMIT_AUTOVACUUM
   54064     pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
   54065     pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
   54066 #endif
   54067   }
   54068 
   54069   /* maxLocal is the maximum amount of payload to store locally for
   54070   ** a cell.  Make sure it is small enough so that at least minFanout
   54071   ** cells can will fit on one page.  We assume a 10-byte page header.
   54072   ** Besides the payload, the cell must store:
   54073   **     2-byte pointer to the cell
   54074   **     4-byte child pointer
   54075   **     9-byte nKey value
   54076   **     4-byte nData value
   54077   **     4-byte overflow page pointer
   54078   ** So a cell consists of a 2-byte pointer, a header which is as much as
   54079   ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
   54080   ** page pointer.
   54081   */
   54082   pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
   54083   pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
   54084   pBt->maxLeaf = (u16)(pBt->usableSize - 35);
   54085   pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
   54086   if( pBt->maxLocal>127 ){
   54087     pBt->max1bytePayload = 127;
   54088   }else{
   54089     pBt->max1bytePayload = (u8)pBt->maxLocal;
   54090   }
   54091   assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
   54092   pBt->pPage1 = pPage1;
   54093   pBt->nPage = nPage;
   54094   return SQLITE_OK;
   54095 
   54096 page1_init_failed:
   54097   releasePage(pPage1);
   54098   pBt->pPage1 = 0;
   54099   return rc;
   54100 }
   54101 
   54102 #ifndef NDEBUG
   54103 /*
   54104 ** Return the number of cursors open on pBt. This is for use
   54105 ** in assert() expressions, so it is only compiled if NDEBUG is not
   54106 ** defined.
   54107 **
   54108 ** Only write cursors are counted if wrOnly is true.  If wrOnly is
   54109 ** false then all cursors are counted.
   54110 **
   54111 ** For the purposes of this routine, a cursor is any cursor that
   54112 ** is capable of reading or writing to the databse.  Cursors that
   54113 ** have been tripped into the CURSOR_FAULT state are not counted.
   54114 */
   54115 static int countValidCursors(BtShared *pBt, int wrOnly){
   54116   BtCursor *pCur;
   54117   int r = 0;
   54118   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
   54119     if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
   54120      && pCur->eState!=CURSOR_FAULT ) r++;
   54121   }
   54122   return r;
   54123 }
   54124 #endif
   54125 
   54126 /*
   54127 ** If there are no outstanding cursors and we are not in the middle
   54128 ** of a transaction but there is a read lock on the database, then
   54129 ** this routine unrefs the first page of the database file which
   54130 ** has the effect of releasing the read lock.
   54131 **
   54132 ** If there is a transaction in progress, this routine is a no-op.
   54133 */
   54134 static void unlockBtreeIfUnused(BtShared *pBt){
   54135   assert( sqlite3_mutex_held(pBt->mutex) );
   54136   assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
   54137   if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
   54138     assert( pBt->pPage1->aData );
   54139     assert( sqlite3PagerRefcount(pBt->pPager)==1 );
   54140     assert( pBt->pPage1->aData );
   54141     releasePage(pBt->pPage1);
   54142     pBt->pPage1 = 0;
   54143   }
   54144 }
   54145 
   54146 /*
   54147 ** If pBt points to an empty file then convert that empty file
   54148 ** into a new empty database by initializing the first page of
   54149 ** the database.
   54150 */
   54151 static int newDatabase(BtShared *pBt){
   54152   MemPage *pP1;
   54153   unsigned char *data;
   54154   int rc;
   54155 
   54156   assert( sqlite3_mutex_held(pBt->mutex) );
   54157   if( pBt->nPage>0 ){
   54158     return SQLITE_OK;
   54159   }
   54160   pP1 = pBt->pPage1;
   54161   assert( pP1!=0 );
   54162   data = pP1->aData;
   54163   rc = sqlite3PagerWrite(pP1->pDbPage);
   54164   if( rc ) return rc;
   54165   memcpy(data, zMagicHeader, sizeof(zMagicHeader));
   54166   assert( sizeof(zMagicHeader)==16 );
   54167   data[16] = (u8)((pBt->pageSize>>8)&0xff);
   54168   data[17] = (u8)((pBt->pageSize>>16)&0xff);
   54169   data[18] = 1;
   54170   data[19] = 1;
   54171   assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
   54172   data[20] = (u8)(pBt->pageSize - pBt->usableSize);
   54173   data[21] = 64;
   54174   data[22] = 32;
   54175   data[23] = 32;
   54176   memset(&data[24], 0, 100-24);
   54177   zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
   54178   pBt->btsFlags |= BTS_PAGESIZE_FIXED;
   54179 #ifndef SQLITE_OMIT_AUTOVACUUM
   54180   assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
   54181   assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
   54182   put4byte(&data[36 + 4*4], pBt->autoVacuum);
   54183   put4byte(&data[36 + 7*4], pBt->incrVacuum);
   54184 #endif
   54185   pBt->nPage = 1;
   54186   data[31] = 1;
   54187   return SQLITE_OK;
   54188 }
   54189 
   54190 /*
   54191 ** Initialize the first page of the database file (creating a database
   54192 ** consisting of a single page and no schema objects). Return SQLITE_OK
   54193 ** if successful, or an SQLite error code otherwise.
   54194 */
   54195 SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
   54196   int rc;
   54197   sqlite3BtreeEnter(p);
   54198   p->pBt->nPage = 0;
   54199   rc = newDatabase(p->pBt);
   54200   sqlite3BtreeLeave(p);
   54201   return rc;
   54202 }
   54203 
   54204 /*
   54205 ** Attempt to start a new transaction. A write-transaction
   54206 ** is started if the second argument is nonzero, otherwise a read-
   54207 ** transaction.  If the second argument is 2 or more and exclusive
   54208 ** transaction is started, meaning that no other process is allowed
   54209 ** to access the database.  A preexisting transaction may not be
   54210 ** upgraded to exclusive by calling this routine a second time - the
   54211 ** exclusivity flag only works for a new transaction.
   54212 **
   54213 ** A write-transaction must be started before attempting any
   54214 ** changes to the database.  None of the following routines
   54215 ** will work unless a transaction is started first:
   54216 **
   54217 **      sqlite3BtreeCreateTable()
   54218 **      sqlite3BtreeCreateIndex()
   54219 **      sqlite3BtreeClearTable()
   54220 **      sqlite3BtreeDropTable()
   54221 **      sqlite3BtreeInsert()
   54222 **      sqlite3BtreeDelete()
   54223 **      sqlite3BtreeUpdateMeta()
   54224 **
   54225 ** If an initial attempt to acquire the lock fails because of lock contention
   54226 ** and the database was previously unlocked, then invoke the busy handler
   54227 ** if there is one.  But if there was previously a read-lock, do not
   54228 ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is
   54229 ** returned when there is already a read-lock in order to avoid a deadlock.
   54230 **
   54231 ** Suppose there are two processes A and B.  A has a read lock and B has
   54232 ** a reserved lock.  B tries to promote to exclusive but is blocked because
   54233 ** of A's read lock.  A tries to promote to reserved but is blocked by B.
   54234 ** One or the other of the two processes must give way or there can be
   54235 ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
   54236 ** when A already has a read lock, we encourage A to give up and let B
   54237 ** proceed.
   54238 */
   54239 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
   54240   sqlite3 *pBlock = 0;
   54241   BtShared *pBt = p->pBt;
   54242   int rc = SQLITE_OK;
   54243 
   54244   sqlite3BtreeEnter(p);
   54245   btreeIntegrity(p);
   54246 
   54247   /* If the btree is already in a write-transaction, or it
   54248   ** is already in a read-transaction and a read-transaction
   54249   ** is requested, this is a no-op.
   54250   */
   54251   if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
   54252     goto trans_begun;
   54253   }
   54254   assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
   54255 
   54256   /* Write transactions are not possible on a read-only database */
   54257   if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
   54258     rc = SQLITE_READONLY;
   54259     goto trans_begun;
   54260   }
   54261 
   54262 #ifndef SQLITE_OMIT_SHARED_CACHE
   54263   /* If another database handle has already opened a write transaction
   54264   ** on this shared-btree structure and a second write transaction is
   54265   ** requested, return SQLITE_LOCKED.
   54266   */
   54267   if( (wrflag && pBt->inTransaction==TRANS_WRITE)
   54268    || (pBt->btsFlags & BTS_PENDING)!=0
   54269   ){
   54270     pBlock = pBt->pWriter->db;
   54271   }else if( wrflag>1 ){
   54272     BtLock *pIter;
   54273     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
   54274       if( pIter->pBtree!=p ){
   54275         pBlock = pIter->pBtree->db;
   54276         break;
   54277       }
   54278     }
   54279   }
   54280   if( pBlock ){
   54281     sqlite3ConnectionBlocked(p->db, pBlock);
   54282     rc = SQLITE_LOCKED_SHAREDCACHE;
   54283     goto trans_begun;
   54284   }
   54285 #endif
   54286 
   54287   /* Any read-only or read-write transaction implies a read-lock on
   54288   ** page 1. So if some other shared-cache client already has a write-lock
   54289   ** on page 1, the transaction cannot be opened. */
   54290   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
   54291   if( SQLITE_OK!=rc ) goto trans_begun;
   54292 
   54293   pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
   54294   if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
   54295   do {
   54296     /* Call lockBtree() until either pBt->pPage1 is populated or
   54297     ** lockBtree() returns something other than SQLITE_OK. lockBtree()
   54298     ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
   54299     ** reading page 1 it discovers that the page-size of the database
   54300     ** file is not pBt->pageSize. In this case lockBtree() will update
   54301     ** pBt->pageSize to the page-size of the file on disk.
   54302     */
   54303     while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
   54304 
   54305     if( rc==SQLITE_OK && wrflag ){
   54306       if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
   54307         rc = SQLITE_READONLY;
   54308       }else{
   54309         rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
   54310         if( rc==SQLITE_OK ){
   54311           rc = newDatabase(pBt);
   54312         }
   54313       }
   54314     }
   54315 
   54316     if( rc!=SQLITE_OK ){
   54317       unlockBtreeIfUnused(pBt);
   54318     }
   54319   }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
   54320           btreeInvokeBusyHandler(pBt) );
   54321 
   54322   if( rc==SQLITE_OK ){
   54323     if( p->inTrans==TRANS_NONE ){
   54324       pBt->nTransaction++;
   54325 #ifndef SQLITE_OMIT_SHARED_CACHE
   54326       if( p->sharable ){
   54327         assert( p->lock.pBtree==p && p->lock.iTable==1 );
   54328         p->lock.eLock = READ_LOCK;
   54329         p->lock.pNext = pBt->pLock;
   54330         pBt->pLock = &p->lock;
   54331       }
   54332 #endif
   54333     }
   54334     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
   54335     if( p->inTrans>pBt->inTransaction ){
   54336       pBt->inTransaction = p->inTrans;
   54337     }
   54338     if( wrflag ){
   54339       MemPage *pPage1 = pBt->pPage1;
   54340 #ifndef SQLITE_OMIT_SHARED_CACHE
   54341       assert( !pBt->pWriter );
   54342       pBt->pWriter = p;
   54343       pBt->btsFlags &= ~BTS_EXCLUSIVE;
   54344       if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
   54345 #endif
   54346 
   54347       /* If the db-size header field is incorrect (as it may be if an old
   54348       ** client has been writing the database file), update it now. Doing
   54349       ** this sooner rather than later means the database size can safely
   54350       ** re-read the database size from page 1 if a savepoint or transaction
   54351       ** rollback occurs within the transaction.
   54352       */
   54353       if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
   54354         rc = sqlite3PagerWrite(pPage1->pDbPage);
   54355         if( rc==SQLITE_OK ){
   54356           put4byte(&pPage1->aData[28], pBt->nPage);
   54357         }
   54358       }
   54359     }
   54360   }
   54361 
   54362 
   54363 trans_begun:
   54364   if( rc==SQLITE_OK && wrflag ){
   54365     /* This call makes sure that the pager has the correct number of
   54366     ** open savepoints. If the second parameter is greater than 0 and
   54367     ** the sub-journal is not already open, then it will be opened here.
   54368     */
   54369     rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
   54370   }
   54371 
   54372   btreeIntegrity(p);
   54373   sqlite3BtreeLeave(p);
   54374   return rc;
   54375 }
   54376 
   54377 #ifndef SQLITE_OMIT_AUTOVACUUM
   54378 
   54379 /*
   54380 ** Set the pointer-map entries for all children of page pPage. Also, if
   54381 ** pPage contains cells that point to overflow pages, set the pointer
   54382 ** map entries for the overflow pages as well.
   54383 */
   54384 static int setChildPtrmaps(MemPage *pPage){
   54385   int i;                             /* Counter variable */
   54386   int nCell;                         /* Number of cells in page pPage */
   54387   int rc;                            /* Return code */
   54388   BtShared *pBt = pPage->pBt;
   54389   u8 isInitOrig = pPage->isInit;
   54390   Pgno pgno = pPage->pgno;
   54391 
   54392   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   54393   rc = btreeInitPage(pPage);
   54394   if( rc!=SQLITE_OK ){
   54395     goto set_child_ptrmaps_out;
   54396   }
   54397   nCell = pPage->nCell;
   54398 
   54399   for(i=0; i<nCell; i++){
   54400     u8 *pCell = findCell(pPage, i);
   54401 
   54402     ptrmapPutOvflPtr(pPage, pCell, &rc);
   54403 
   54404     if( !pPage->leaf ){
   54405       Pgno childPgno = get4byte(pCell);
   54406       ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
   54407     }
   54408   }
   54409 
   54410   if( !pPage->leaf ){
   54411     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
   54412     ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
   54413   }
   54414 
   54415 set_child_ptrmaps_out:
   54416   pPage->isInit = isInitOrig;
   54417   return rc;
   54418 }
   54419 
   54420 /*
   54421 ** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
   54422 ** that it points to iTo. Parameter eType describes the type of pointer to
   54423 ** be modified, as  follows:
   54424 **
   54425 ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child
   54426 **                   page of pPage.
   54427 **
   54428 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
   54429 **                   page pointed to by one of the cells on pPage.
   54430 **
   54431 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
   54432 **                   overflow page in the list.
   54433 */
   54434 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
   54435   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   54436   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   54437   if( eType==PTRMAP_OVERFLOW2 ){
   54438     /* The pointer is always the first 4 bytes of the page in this case.  */
   54439     if( get4byte(pPage->aData)!=iFrom ){
   54440       return SQLITE_CORRUPT_BKPT;
   54441     }
   54442     put4byte(pPage->aData, iTo);
   54443   }else{
   54444     u8 isInitOrig = pPage->isInit;
   54445     int i;
   54446     int nCell;
   54447 
   54448     btreeInitPage(pPage);
   54449     nCell = pPage->nCell;
   54450 
   54451     for(i=0; i<nCell; i++){
   54452       u8 *pCell = findCell(pPage, i);
   54453       if( eType==PTRMAP_OVERFLOW1 ){
   54454         CellInfo info;
   54455         btreeParseCellPtr(pPage, pCell, &info);
   54456         if( info.iOverflow
   54457          && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
   54458          && iFrom==get4byte(&pCell[info.iOverflow])
   54459         ){
   54460           put4byte(&pCell[info.iOverflow], iTo);
   54461           break;
   54462         }
   54463       }else{
   54464         if( get4byte(pCell)==iFrom ){
   54465           put4byte(pCell, iTo);
   54466           break;
   54467         }
   54468       }
   54469     }
   54470 
   54471     if( i==nCell ){
   54472       if( eType!=PTRMAP_BTREE ||
   54473           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
   54474         return SQLITE_CORRUPT_BKPT;
   54475       }
   54476       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
   54477     }
   54478 
   54479     pPage->isInit = isInitOrig;
   54480   }
   54481   return SQLITE_OK;
   54482 }
   54483 
   54484 
   54485 /*
   54486 ** Move the open database page pDbPage to location iFreePage in the
   54487 ** database. The pDbPage reference remains valid.
   54488 **
   54489 ** The isCommit flag indicates that there is no need to remember that
   54490 ** the journal needs to be sync()ed before database page pDbPage->pgno
   54491 ** can be written to. The caller has already promised not to write to that
   54492 ** page.
   54493 */
   54494 static int relocatePage(
   54495   BtShared *pBt,           /* Btree */
   54496   MemPage *pDbPage,        /* Open page to move */
   54497   u8 eType,                /* Pointer map 'type' entry for pDbPage */
   54498   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
   54499   Pgno iFreePage,          /* The location to move pDbPage to */
   54500   int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
   54501 ){
   54502   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
   54503   Pgno iDbPage = pDbPage->pgno;
   54504   Pager *pPager = pBt->pPager;
   54505   int rc;
   54506 
   54507   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
   54508       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
   54509   assert( sqlite3_mutex_held(pBt->mutex) );
   54510   assert( pDbPage->pBt==pBt );
   54511 
   54512   /* Move page iDbPage from its current location to page number iFreePage */
   54513   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
   54514       iDbPage, iFreePage, iPtrPage, eType));
   54515   rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
   54516   if( rc!=SQLITE_OK ){
   54517     return rc;
   54518   }
   54519   pDbPage->pgno = iFreePage;
   54520 
   54521   /* If pDbPage was a btree-page, then it may have child pages and/or cells
   54522   ** that point to overflow pages. The pointer map entries for all these
   54523   ** pages need to be changed.
   54524   **
   54525   ** If pDbPage is an overflow page, then the first 4 bytes may store a
   54526   ** pointer to a subsequent overflow page. If this is the case, then
   54527   ** the pointer map needs to be updated for the subsequent overflow page.
   54528   */
   54529   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
   54530     rc = setChildPtrmaps(pDbPage);
   54531     if( rc!=SQLITE_OK ){
   54532       return rc;
   54533     }
   54534   }else{
   54535     Pgno nextOvfl = get4byte(pDbPage->aData);
   54536     if( nextOvfl!=0 ){
   54537       ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
   54538       if( rc!=SQLITE_OK ){
   54539         return rc;
   54540       }
   54541     }
   54542   }
   54543 
   54544   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
   54545   ** that it points at iFreePage. Also fix the pointer map entry for
   54546   ** iPtrPage.
   54547   */
   54548   if( eType!=PTRMAP_ROOTPAGE ){
   54549     rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
   54550     if( rc!=SQLITE_OK ){
   54551       return rc;
   54552     }
   54553     rc = sqlite3PagerWrite(pPtrPage->pDbPage);
   54554     if( rc!=SQLITE_OK ){
   54555       releasePage(pPtrPage);
   54556       return rc;
   54557     }
   54558     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
   54559     releasePage(pPtrPage);
   54560     if( rc==SQLITE_OK ){
   54561       ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
   54562     }
   54563   }
   54564   return rc;
   54565 }
   54566 
   54567 /* Forward declaration required by incrVacuumStep(). */
   54568 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
   54569 
   54570 /*
   54571 ** Perform a single step of an incremental-vacuum. If successful, return
   54572 ** SQLITE_OK. If there is no work to do (and therefore no point in
   54573 ** calling this function again), return SQLITE_DONE. Or, if an error
   54574 ** occurs, return some other error code.
   54575 **
   54576 ** More specificly, this function attempts to re-organize the database so
   54577 ** that the last page of the file currently in use is no longer in use.
   54578 **
   54579 ** Parameter nFin is the number of pages that this database would contain
   54580 ** were this function called until it returns SQLITE_DONE.
   54581 **
   54582 ** If the bCommit parameter is non-zero, this function assumes that the
   54583 ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
   54584 ** or an error. bCommit is passed true for an auto-vacuum-on-commmit
   54585 ** operation, or false for an incremental vacuum.
   54586 */
   54587 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
   54588   Pgno nFreeList;           /* Number of pages still on the free-list */
   54589   int rc;
   54590 
   54591   assert( sqlite3_mutex_held(pBt->mutex) );
   54592   assert( iLastPg>nFin );
   54593 
   54594   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
   54595     u8 eType;
   54596     Pgno iPtrPage;
   54597 
   54598     nFreeList = get4byte(&pBt->pPage1->aData[36]);
   54599     if( nFreeList==0 ){
   54600       return SQLITE_DONE;
   54601     }
   54602 
   54603     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
   54604     if( rc!=SQLITE_OK ){
   54605       return rc;
   54606     }
   54607     if( eType==PTRMAP_ROOTPAGE ){
   54608       return SQLITE_CORRUPT_BKPT;
   54609     }
   54610 
   54611     if( eType==PTRMAP_FREEPAGE ){
   54612       if( bCommit==0 ){
   54613         /* Remove the page from the files free-list. This is not required
   54614         ** if bCommit is non-zero. In that case, the free-list will be
   54615         ** truncated to zero after this function returns, so it doesn't
   54616         ** matter if it still contains some garbage entries.
   54617         */
   54618         Pgno iFreePg;
   54619         MemPage *pFreePg;
   54620         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
   54621         if( rc!=SQLITE_OK ){
   54622           return rc;
   54623         }
   54624         assert( iFreePg==iLastPg );
   54625         releasePage(pFreePg);
   54626       }
   54627     } else {
   54628       Pgno iFreePg;             /* Index of free page to move pLastPg to */
   54629       MemPage *pLastPg;
   54630       u8 eMode = BTALLOC_ANY;   /* Mode parameter for allocateBtreePage() */
   54631       Pgno iNear = 0;           /* nearby parameter for allocateBtreePage() */
   54632 
   54633       rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
   54634       if( rc!=SQLITE_OK ){
   54635         return rc;
   54636       }
   54637 
   54638       /* If bCommit is zero, this loop runs exactly once and page pLastPg
   54639       ** is swapped with the first free page pulled off the free list.
   54640       **
   54641       ** On the other hand, if bCommit is greater than zero, then keep
   54642       ** looping until a free-page located within the first nFin pages
   54643       ** of the file is found.
   54644       */
   54645       if( bCommit==0 ){
   54646         eMode = BTALLOC_LE;
   54647         iNear = nFin;
   54648       }
   54649       do {
   54650         MemPage *pFreePg;
   54651         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
   54652         if( rc!=SQLITE_OK ){
   54653           releasePage(pLastPg);
   54654           return rc;
   54655         }
   54656         releasePage(pFreePg);
   54657       }while( bCommit && iFreePg>nFin );
   54658       assert( iFreePg<iLastPg );
   54659 
   54660       rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
   54661       releasePage(pLastPg);
   54662       if( rc!=SQLITE_OK ){
   54663         return rc;
   54664       }
   54665     }
   54666   }
   54667 
   54668   if( bCommit==0 ){
   54669     do {
   54670       iLastPg--;
   54671     }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
   54672     pBt->bDoTruncate = 1;
   54673     pBt->nPage = iLastPg;
   54674   }
   54675   return SQLITE_OK;
   54676 }
   54677 
   54678 /*
   54679 ** The database opened by the first argument is an auto-vacuum database
   54680 ** nOrig pages in size containing nFree free pages. Return the expected
   54681 ** size of the database in pages following an auto-vacuum operation.
   54682 */
   54683 static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
   54684   int nEntry;                     /* Number of entries on one ptrmap page */
   54685   Pgno nPtrmap;                   /* Number of PtrMap pages to be freed */
   54686   Pgno nFin;                      /* Return value */
   54687 
   54688   nEntry = pBt->usableSize/5;
   54689   nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
   54690   nFin = nOrig - nFree - nPtrmap;
   54691   if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
   54692     nFin--;
   54693   }
   54694   while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
   54695     nFin--;
   54696   }
   54697 
   54698   return nFin;
   54699 }
   54700 
   54701 /*
   54702 ** A write-transaction must be opened before calling this function.
   54703 ** It performs a single unit of work towards an incremental vacuum.
   54704 **
   54705 ** If the incremental vacuum is finished after this function has run,
   54706 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
   54707 ** SQLITE_OK is returned. Otherwise an SQLite error code.
   54708 */
   54709 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
   54710   int rc;
   54711   BtShared *pBt = p->pBt;
   54712 
   54713   sqlite3BtreeEnter(p);
   54714   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
   54715   if( !pBt->autoVacuum ){
   54716     rc = SQLITE_DONE;
   54717   }else{
   54718     Pgno nOrig = btreePagecount(pBt);
   54719     Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
   54720     Pgno nFin = finalDbSize(pBt, nOrig, nFree);
   54721 
   54722     if( nOrig<nFin ){
   54723       rc = SQLITE_CORRUPT_BKPT;
   54724     }else if( nFree>0 ){
   54725       rc = saveAllCursors(pBt, 0, 0);
   54726       if( rc==SQLITE_OK ){
   54727         invalidateAllOverflowCache(pBt);
   54728         rc = incrVacuumStep(pBt, nFin, nOrig, 0);
   54729       }
   54730       if( rc==SQLITE_OK ){
   54731         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
   54732         put4byte(&pBt->pPage1->aData[28], pBt->nPage);
   54733       }
   54734     }else{
   54735       rc = SQLITE_DONE;
   54736     }
   54737   }
   54738   sqlite3BtreeLeave(p);
   54739   return rc;
   54740 }
   54741 
   54742 /*
   54743 ** This routine is called prior to sqlite3PagerCommit when a transaction
   54744 ** is committed for an auto-vacuum database.
   54745 **
   54746 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
   54747 ** the database file should be truncated to during the commit process.
   54748 ** i.e. the database has been reorganized so that only the first *pnTrunc
   54749 ** pages are in use.
   54750 */
   54751 static int autoVacuumCommit(BtShared *pBt){
   54752   int rc = SQLITE_OK;
   54753   Pager *pPager = pBt->pPager;
   54754   VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
   54755 
   54756   assert( sqlite3_mutex_held(pBt->mutex) );
   54757   invalidateAllOverflowCache(pBt);
   54758   assert(pBt->autoVacuum);
   54759   if( !pBt->incrVacuum ){
   54760     Pgno nFin;         /* Number of pages in database after autovacuuming */
   54761     Pgno nFree;        /* Number of pages on the freelist initially */
   54762     Pgno iFree;        /* The next page to be freed */
   54763     Pgno nOrig;        /* Database size before freeing */
   54764 
   54765     nOrig = btreePagecount(pBt);
   54766     if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
   54767       /* It is not possible to create a database for which the final page
   54768       ** is either a pointer-map page or the pending-byte page. If one
   54769       ** is encountered, this indicates corruption.
   54770       */
   54771       return SQLITE_CORRUPT_BKPT;
   54772     }
   54773 
   54774     nFree = get4byte(&pBt->pPage1->aData[36]);
   54775     nFin = finalDbSize(pBt, nOrig, nFree);
   54776     if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
   54777     if( nFin<nOrig ){
   54778       rc = saveAllCursors(pBt, 0, 0);
   54779     }
   54780     for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
   54781       rc = incrVacuumStep(pBt, nFin, iFree, 1);
   54782     }
   54783     if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
   54784       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
   54785       put4byte(&pBt->pPage1->aData[32], 0);
   54786       put4byte(&pBt->pPage1->aData[36], 0);
   54787       put4byte(&pBt->pPage1->aData[28], nFin);
   54788       pBt->bDoTruncate = 1;
   54789       pBt->nPage = nFin;
   54790     }
   54791     if( rc!=SQLITE_OK ){
   54792       sqlite3PagerRollback(pPager);
   54793     }
   54794   }
   54795 
   54796   assert( nRef>=sqlite3PagerRefcount(pPager) );
   54797   return rc;
   54798 }
   54799 
   54800 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
   54801 # define setChildPtrmaps(x) SQLITE_OK
   54802 #endif
   54803 
   54804 /*
   54805 ** This routine does the first phase of a two-phase commit.  This routine
   54806 ** causes a rollback journal to be created (if it does not already exist)
   54807 ** and populated with enough information so that if a power loss occurs
   54808 ** the database can be restored to its original state by playing back
   54809 ** the journal.  Then the contents of the journal are flushed out to
   54810 ** the disk.  After the journal is safely on oxide, the changes to the
   54811 ** database are written into the database file and flushed to oxide.
   54812 ** At the end of this call, the rollback journal still exists on the
   54813 ** disk and we are still holding all locks, so the transaction has not
   54814 ** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
   54815 ** commit process.
   54816 **
   54817 ** This call is a no-op if no write-transaction is currently active on pBt.
   54818 **
   54819 ** Otherwise, sync the database file for the btree pBt. zMaster points to
   54820 ** the name of a master journal file that should be written into the
   54821 ** individual journal file, or is NULL, indicating no master journal file
   54822 ** (single database transaction).
   54823 **
   54824 ** When this is called, the master journal should already have been
   54825 ** created, populated with this journal pointer and synced to disk.
   54826 **
   54827 ** Once this is routine has returned, the only thing required to commit
   54828 ** the write-transaction for this database file is to delete the journal.
   54829 */
   54830 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
   54831   int rc = SQLITE_OK;
   54832   if( p->inTrans==TRANS_WRITE ){
   54833     BtShared *pBt = p->pBt;
   54834     sqlite3BtreeEnter(p);
   54835 #ifndef SQLITE_OMIT_AUTOVACUUM
   54836     if( pBt->autoVacuum ){
   54837       rc = autoVacuumCommit(pBt);
   54838       if( rc!=SQLITE_OK ){
   54839         sqlite3BtreeLeave(p);
   54840         return rc;
   54841       }
   54842     }
   54843     if( pBt->bDoTruncate ){
   54844       sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
   54845     }
   54846 #endif
   54847     rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
   54848     sqlite3BtreeLeave(p);
   54849   }
   54850   return rc;
   54851 }
   54852 
   54853 /*
   54854 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
   54855 ** at the conclusion of a transaction.
   54856 */
   54857 static void btreeEndTransaction(Btree *p){
   54858   BtShared *pBt = p->pBt;
   54859   sqlite3 *db = p->db;
   54860   assert( sqlite3BtreeHoldsMutex(p) );
   54861 
   54862 #ifndef SQLITE_OMIT_AUTOVACUUM
   54863   pBt->bDoTruncate = 0;
   54864 #endif
   54865   if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
   54866     /* If there are other active statements that belong to this database
   54867     ** handle, downgrade to a read-only transaction. The other statements
   54868     ** may still be reading from the database.  */
   54869     downgradeAllSharedCacheTableLocks(p);
   54870     p->inTrans = TRANS_READ;
   54871   }else{
   54872     /* If the handle had any kind of transaction open, decrement the
   54873     ** transaction count of the shared btree. If the transaction count
   54874     ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
   54875     ** call below will unlock the pager.  */
   54876     if( p->inTrans!=TRANS_NONE ){
   54877       clearAllSharedCacheTableLocks(p);
   54878       pBt->nTransaction--;
   54879       if( 0==pBt->nTransaction ){
   54880         pBt->inTransaction = TRANS_NONE;
   54881       }
   54882     }
   54883 
   54884     /* Set the current transaction state to TRANS_NONE and unlock the
   54885     ** pager if this call closed the only read or write transaction.  */
   54886     p->inTrans = TRANS_NONE;
   54887     unlockBtreeIfUnused(pBt);
   54888   }
   54889 
   54890   btreeIntegrity(p);
   54891 }
   54892 
   54893 /*
   54894 ** Commit the transaction currently in progress.
   54895 **
   54896 ** This routine implements the second phase of a 2-phase commit.  The
   54897 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
   54898 ** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
   54899 ** routine did all the work of writing information out to disk and flushing the
   54900 ** contents so that they are written onto the disk platter.  All this
   54901 ** routine has to do is delete or truncate or zero the header in the
   54902 ** the rollback journal (which causes the transaction to commit) and
   54903 ** drop locks.
   54904 **
   54905 ** Normally, if an error occurs while the pager layer is attempting to
   54906 ** finalize the underlying journal file, this function returns an error and
   54907 ** the upper layer will attempt a rollback. However, if the second argument
   54908 ** is non-zero then this b-tree transaction is part of a multi-file
   54909 ** transaction. In this case, the transaction has already been committed
   54910 ** (by deleting a master journal file) and the caller will ignore this
   54911 ** functions return code. So, even if an error occurs in the pager layer,
   54912 ** reset the b-tree objects internal state to indicate that the write
   54913 ** transaction has been closed. This is quite safe, as the pager will have
   54914 ** transitioned to the error state.
   54915 **
   54916 ** This will release the write lock on the database file.  If there
   54917 ** are no active cursors, it also releases the read lock.
   54918 */
   54919 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
   54920 
   54921   if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
   54922   sqlite3BtreeEnter(p);
   54923   btreeIntegrity(p);
   54924 
   54925   /* If the handle has a write-transaction open, commit the shared-btrees
   54926   ** transaction and set the shared state to TRANS_READ.
   54927   */
   54928   if( p->inTrans==TRANS_WRITE ){
   54929     int rc;
   54930     BtShared *pBt = p->pBt;
   54931     assert( pBt->inTransaction==TRANS_WRITE );
   54932     assert( pBt->nTransaction>0 );
   54933     rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
   54934     if( rc!=SQLITE_OK && bCleanup==0 ){
   54935       sqlite3BtreeLeave(p);
   54936       return rc;
   54937     }
   54938     pBt->inTransaction = TRANS_READ;
   54939     btreeClearHasContent(pBt);
   54940   }
   54941 
   54942   btreeEndTransaction(p);
   54943   sqlite3BtreeLeave(p);
   54944   return SQLITE_OK;
   54945 }
   54946 
   54947 /*
   54948 ** Do both phases of a commit.
   54949 */
   54950 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
   54951   int rc;
   54952   sqlite3BtreeEnter(p);
   54953   rc = sqlite3BtreeCommitPhaseOne(p, 0);
   54954   if( rc==SQLITE_OK ){
   54955     rc = sqlite3BtreeCommitPhaseTwo(p, 0);
   54956   }
   54957   sqlite3BtreeLeave(p);
   54958   return rc;
   54959 }
   54960 
   54961 /*
   54962 ** This routine sets the state to CURSOR_FAULT and the error
   54963 ** code to errCode for every cursor on BtShared that pBtree
   54964 ** references.
   54965 **
   54966 ** Every cursor is tripped, including cursors that belong
   54967 ** to other database connections that happen to be sharing
   54968 ** the cache with pBtree.
   54969 **
   54970 ** This routine gets called when a rollback occurs.
   54971 ** All cursors using the same cache must be tripped
   54972 ** to prevent them from trying to use the btree after
   54973 ** the rollback.  The rollback may have deleted tables
   54974 ** or moved root pages, so it is not sufficient to
   54975 ** save the state of the cursor.  The cursor must be
   54976 ** invalidated.
   54977 */
   54978 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
   54979   BtCursor *p;
   54980   if( pBtree==0 ) return;
   54981   sqlite3BtreeEnter(pBtree);
   54982   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
   54983     int i;
   54984     sqlite3BtreeClearCursor(p);
   54985     p->eState = CURSOR_FAULT;
   54986     p->skipNext = errCode;
   54987     for(i=0; i<=p->iPage; i++){
   54988       releasePage(p->apPage[i]);
   54989       p->apPage[i] = 0;
   54990     }
   54991   }
   54992   sqlite3BtreeLeave(pBtree);
   54993 }
   54994 
   54995 /*
   54996 ** Rollback the transaction in progress.  All cursors will be
   54997 ** invalided by this operation.  Any attempt to use a cursor
   54998 ** that was open at the beginning of this operation will result
   54999 ** in an error.
   55000 **
   55001 ** This will release the write lock on the database file.  If there
   55002 ** are no active cursors, it also releases the read lock.
   55003 */
   55004 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode){
   55005   int rc;
   55006   BtShared *pBt = p->pBt;
   55007   MemPage *pPage1;
   55008 
   55009   sqlite3BtreeEnter(p);
   55010   if( tripCode==SQLITE_OK ){
   55011     rc = tripCode = saveAllCursors(pBt, 0, 0);
   55012   }else{
   55013     rc = SQLITE_OK;
   55014   }
   55015   if( tripCode ){
   55016     sqlite3BtreeTripAllCursors(p, tripCode);
   55017   }
   55018   btreeIntegrity(p);
   55019 
   55020   if( p->inTrans==TRANS_WRITE ){
   55021     int rc2;
   55022 
   55023     assert( TRANS_WRITE==pBt->inTransaction );
   55024     rc2 = sqlite3PagerRollback(pBt->pPager);
   55025     if( rc2!=SQLITE_OK ){
   55026       rc = rc2;
   55027     }
   55028 
   55029     /* The rollback may have destroyed the pPage1->aData value.  So
   55030     ** call btreeGetPage() on page 1 again to make
   55031     ** sure pPage1->aData is set correctly. */
   55032     if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
   55033       int nPage = get4byte(28+(u8*)pPage1->aData);
   55034       testcase( nPage==0 );
   55035       if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
   55036       testcase( pBt->nPage!=nPage );
   55037       pBt->nPage = nPage;
   55038       releasePage(pPage1);
   55039     }
   55040     assert( countValidCursors(pBt, 1)==0 );
   55041     pBt->inTransaction = TRANS_READ;
   55042     btreeClearHasContent(pBt);
   55043   }
   55044 
   55045   btreeEndTransaction(p);
   55046   sqlite3BtreeLeave(p);
   55047   return rc;
   55048 }
   55049 
   55050 /*
   55051 ** Start a statement subtransaction. The subtransaction can can be rolled
   55052 ** back independently of the main transaction. You must start a transaction
   55053 ** before starting a subtransaction. The subtransaction is ended automatically
   55054 ** if the main transaction commits or rolls back.
   55055 **
   55056 ** Statement subtransactions are used around individual SQL statements
   55057 ** that are contained within a BEGIN...COMMIT block.  If a constraint
   55058 ** error occurs within the statement, the effect of that one statement
   55059 ** can be rolled back without having to rollback the entire transaction.
   55060 **
   55061 ** A statement sub-transaction is implemented as an anonymous savepoint. The
   55062 ** value passed as the second parameter is the total number of savepoints,
   55063 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
   55064 ** are no active savepoints and no other statement-transactions open,
   55065 ** iStatement is 1. This anonymous savepoint can be released or rolled back
   55066 ** using the sqlite3BtreeSavepoint() function.
   55067 */
   55068 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
   55069   int rc;
   55070   BtShared *pBt = p->pBt;
   55071   sqlite3BtreeEnter(p);
   55072   assert( p->inTrans==TRANS_WRITE );
   55073   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
   55074   assert( iStatement>0 );
   55075   assert( iStatement>p->db->nSavepoint );
   55076   assert( pBt->inTransaction==TRANS_WRITE );
   55077   /* At the pager level, a statement transaction is a savepoint with
   55078   ** an index greater than all savepoints created explicitly using
   55079   ** SQL statements. It is illegal to open, release or rollback any
   55080   ** such savepoints while the statement transaction savepoint is active.
   55081   */
   55082   rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
   55083   sqlite3BtreeLeave(p);
   55084   return rc;
   55085 }
   55086 
   55087 /*
   55088 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
   55089 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
   55090 ** savepoint identified by parameter iSavepoint, depending on the value
   55091 ** of op.
   55092 **
   55093 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
   55094 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
   55095 ** contents of the entire transaction are rolled back. This is different
   55096 ** from a normal transaction rollback, as no locks are released and the
   55097 ** transaction remains open.
   55098 */
   55099 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
   55100   int rc = SQLITE_OK;
   55101   if( p && p->inTrans==TRANS_WRITE ){
   55102     BtShared *pBt = p->pBt;
   55103     assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
   55104     assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
   55105     sqlite3BtreeEnter(p);
   55106     rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
   55107     if( rc==SQLITE_OK ){
   55108       if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
   55109         pBt->nPage = 0;
   55110       }
   55111       rc = newDatabase(pBt);
   55112       pBt->nPage = get4byte(28 + pBt->pPage1->aData);
   55113 
   55114       /* The database size was written into the offset 28 of the header
   55115       ** when the transaction started, so we know that the value at offset
   55116       ** 28 is nonzero. */
   55117       assert( pBt->nPage>0 );
   55118     }
   55119     sqlite3BtreeLeave(p);
   55120   }
   55121   return rc;
   55122 }
   55123 
   55124 /*
   55125 ** Create a new cursor for the BTree whose root is on the page
   55126 ** iTable. If a read-only cursor is requested, it is assumed that
   55127 ** the caller already has at least a read-only transaction open
   55128 ** on the database already. If a write-cursor is requested, then
   55129 ** the caller is assumed to have an open write transaction.
   55130 **
   55131 ** If wrFlag==0, then the cursor can only be used for reading.
   55132 ** If wrFlag==1, then the cursor can be used for reading or for
   55133 ** writing if other conditions for writing are also met.  These
   55134 ** are the conditions that must be met in order for writing to
   55135 ** be allowed:
   55136 **
   55137 ** 1:  The cursor must have been opened with wrFlag==1
   55138 **
   55139 ** 2:  Other database connections that share the same pager cache
   55140 **     but which are not in the READ_UNCOMMITTED state may not have
   55141 **     cursors open with wrFlag==0 on the same table.  Otherwise
   55142 **     the changes made by this write cursor would be visible to
   55143 **     the read cursors in the other database connection.
   55144 **
   55145 ** 3:  The database must be writable (not on read-only media)
   55146 **
   55147 ** 4:  There must be an active transaction.
   55148 **
   55149 ** No checking is done to make sure that page iTable really is the
   55150 ** root page of a b-tree.  If it is not, then the cursor acquired
   55151 ** will not work correctly.
   55152 **
   55153 ** It is assumed that the sqlite3BtreeCursorZero() has been called
   55154 ** on pCur to initialize the memory space prior to invoking this routine.
   55155 */
   55156 static int btreeCursor(
   55157   Btree *p,                              /* The btree */
   55158   int iTable,                            /* Root page of table to open */
   55159   int wrFlag,                            /* 1 to write. 0 read-only */
   55160   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
   55161   BtCursor *pCur                         /* Space for new cursor */
   55162 ){
   55163   BtShared *pBt = p->pBt;                /* Shared b-tree handle */
   55164 
   55165   assert( sqlite3BtreeHoldsMutex(p) );
   55166   assert( wrFlag==0 || wrFlag==1 );
   55167 
   55168   /* The following assert statements verify that if this is a sharable
   55169   ** b-tree database, the connection is holding the required table locks,
   55170   ** and that no other connection has any open cursor that conflicts with
   55171   ** this lock.  */
   55172   assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
   55173   assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
   55174 
   55175   /* Assert that the caller has opened the required transaction. */
   55176   assert( p->inTrans>TRANS_NONE );
   55177   assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
   55178   assert( pBt->pPage1 && pBt->pPage1->aData );
   55179 
   55180   if( NEVER(wrFlag && (pBt->btsFlags & BTS_READ_ONLY)!=0) ){
   55181     return SQLITE_READONLY;
   55182   }
   55183   if( iTable==1 && btreePagecount(pBt)==0 ){
   55184     assert( wrFlag==0 );
   55185     iTable = 0;
   55186   }
   55187 
   55188   /* Now that no other errors can occur, finish filling in the BtCursor
   55189   ** variables and link the cursor into the BtShared list.  */
   55190   pCur->pgnoRoot = (Pgno)iTable;
   55191   pCur->iPage = -1;
   55192   pCur->pKeyInfo = pKeyInfo;
   55193   pCur->pBtree = p;
   55194   pCur->pBt = pBt;
   55195   assert( wrFlag==0 || wrFlag==BTCF_WriteFlag );
   55196   pCur->curFlags = wrFlag;
   55197   pCur->pNext = pBt->pCursor;
   55198   if( pCur->pNext ){
   55199     pCur->pNext->pPrev = pCur;
   55200   }
   55201   pBt->pCursor = pCur;
   55202   pCur->eState = CURSOR_INVALID;
   55203   return SQLITE_OK;
   55204 }
   55205 SQLITE_PRIVATE int sqlite3BtreeCursor(
   55206   Btree *p,                                   /* The btree */
   55207   int iTable,                                 /* Root page of table to open */
   55208   int wrFlag,                                 /* 1 to write. 0 read-only */
   55209   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
   55210   BtCursor *pCur                              /* Write new cursor here */
   55211 ){
   55212   int rc;
   55213   sqlite3BtreeEnter(p);
   55214   rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
   55215   sqlite3BtreeLeave(p);
   55216   return rc;
   55217 }
   55218 
   55219 /*
   55220 ** Return the size of a BtCursor object in bytes.
   55221 **
   55222 ** This interfaces is needed so that users of cursors can preallocate
   55223 ** sufficient storage to hold a cursor.  The BtCursor object is opaque
   55224 ** to users so they cannot do the sizeof() themselves - they must call
   55225 ** this routine.
   55226 */
   55227 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
   55228   return ROUND8(sizeof(BtCursor));
   55229 }
   55230 
   55231 /*
   55232 ** Initialize memory that will be converted into a BtCursor object.
   55233 **
   55234 ** The simple approach here would be to memset() the entire object
   55235 ** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
   55236 ** do not need to be zeroed and they are large, so we can save a lot
   55237 ** of run-time by skipping the initialization of those elements.
   55238 */
   55239 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
   55240   memset(p, 0, offsetof(BtCursor, iPage));
   55241 }
   55242 
   55243 /*
   55244 ** Close a cursor.  The read lock on the database file is released
   55245 ** when the last cursor is closed.
   55246 */
   55247 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
   55248   Btree *pBtree = pCur->pBtree;
   55249   if( pBtree ){
   55250     int i;
   55251     BtShared *pBt = pCur->pBt;
   55252     sqlite3BtreeEnter(pBtree);
   55253     sqlite3BtreeClearCursor(pCur);
   55254     if( pCur->pPrev ){
   55255       pCur->pPrev->pNext = pCur->pNext;
   55256     }else{
   55257       pBt->pCursor = pCur->pNext;
   55258     }
   55259     if( pCur->pNext ){
   55260       pCur->pNext->pPrev = pCur->pPrev;
   55261     }
   55262     for(i=0; i<=pCur->iPage; i++){
   55263       releasePage(pCur->apPage[i]);
   55264     }
   55265     unlockBtreeIfUnused(pBt);
   55266     sqlite3DbFree(pBtree->db, pCur->aOverflow);
   55267     /* sqlite3_free(pCur); */
   55268     sqlite3BtreeLeave(pBtree);
   55269   }
   55270   return SQLITE_OK;
   55271 }
   55272 
   55273 /*
   55274 ** Make sure the BtCursor* given in the argument has a valid
   55275 ** BtCursor.info structure.  If it is not already valid, call
   55276 ** btreeParseCell() to fill it in.
   55277 **
   55278 ** BtCursor.info is a cache of the information in the current cell.
   55279 ** Using this cache reduces the number of calls to btreeParseCell().
   55280 **
   55281 ** 2007-06-25:  There is a bug in some versions of MSVC that cause the
   55282 ** compiler to crash when getCellInfo() is implemented as a macro.
   55283 ** But there is a measureable speed advantage to using the macro on gcc
   55284 ** (when less compiler optimizations like -Os or -O0 are used and the
   55285 ** compiler is not doing agressive inlining.)  So we use a real function
   55286 ** for MSVC and a macro for everything else.  Ticket #2457.
   55287 */
   55288 #ifndef NDEBUG
   55289   static void assertCellInfo(BtCursor *pCur){
   55290     CellInfo info;
   55291     int iPage = pCur->iPage;
   55292     memset(&info, 0, sizeof(info));
   55293     btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
   55294     assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 );
   55295   }
   55296 #else
   55297   #define assertCellInfo(x)
   55298 #endif
   55299 #ifdef _MSC_VER
   55300   /* Use a real function in MSVC to work around bugs in that compiler. */
   55301   static void getCellInfo(BtCursor *pCur){
   55302     if( pCur->info.nSize==0 ){
   55303       int iPage = pCur->iPage;
   55304       btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
   55305       pCur->curFlags |= BTCF_ValidNKey;
   55306     }else{
   55307       assertCellInfo(pCur);
   55308     }
   55309   }
   55310 #else /* if not _MSC_VER */
   55311   /* Use a macro in all other compilers so that the function is inlined */
   55312 #define getCellInfo(pCur)                                                      \
   55313   if( pCur->info.nSize==0 ){                                                   \
   55314     int iPage = pCur->iPage;                                                   \
   55315     btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);        \
   55316     pCur->curFlags |= BTCF_ValidNKey;                                          \
   55317   }else{                                                                       \
   55318     assertCellInfo(pCur);                                                      \
   55319   }
   55320 #endif /* _MSC_VER */
   55321 
   55322 #ifndef NDEBUG  /* The next routine used only within assert() statements */
   55323 /*
   55324 ** Return true if the given BtCursor is valid.  A valid cursor is one
   55325 ** that is currently pointing to a row in a (non-empty) table.
   55326 ** This is a verification routine is used only within assert() statements.
   55327 */
   55328 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
   55329   return pCur && pCur->eState==CURSOR_VALID;
   55330 }
   55331 #endif /* NDEBUG */
   55332 
   55333 /*
   55334 ** Set *pSize to the size of the buffer needed to hold the value of
   55335 ** the key for the current entry.  If the cursor is not pointing
   55336 ** to a valid entry, *pSize is set to 0.
   55337 **
   55338 ** For a table with the INTKEY flag set, this routine returns the key
   55339 ** itself, not the number of bytes in the key.
   55340 **
   55341 ** The caller must position the cursor prior to invoking this routine.
   55342 **
   55343 ** This routine cannot fail.  It always returns SQLITE_OK.
   55344 */
   55345 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
   55346   assert( cursorHoldsMutex(pCur) );
   55347   assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
   55348   if( pCur->eState!=CURSOR_VALID ){
   55349     *pSize = 0;
   55350   }else{
   55351     getCellInfo(pCur);
   55352     *pSize = pCur->info.nKey;
   55353   }
   55354   return SQLITE_OK;
   55355 }
   55356 
   55357 /*
   55358 ** Set *pSize to the number of bytes of data in the entry the
   55359 ** cursor currently points to.
   55360 **
   55361 ** The caller must guarantee that the cursor is pointing to a non-NULL
   55362 ** valid entry.  In other words, the calling procedure must guarantee
   55363 ** that the cursor has Cursor.eState==CURSOR_VALID.
   55364 **
   55365 ** Failure is not possible.  This function always returns SQLITE_OK.
   55366 ** It might just as well be a procedure (returning void) but we continue
   55367 ** to return an integer result code for historical reasons.
   55368 */
   55369 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
   55370   assert( cursorHoldsMutex(pCur) );
   55371   assert( pCur->eState==CURSOR_VALID );
   55372   getCellInfo(pCur);
   55373   *pSize = pCur->info.nData;
   55374   return SQLITE_OK;
   55375 }
   55376 
   55377 /*
   55378 ** Given the page number of an overflow page in the database (parameter
   55379 ** ovfl), this function finds the page number of the next page in the
   55380 ** linked list of overflow pages. If possible, it uses the auto-vacuum
   55381 ** pointer-map data instead of reading the content of page ovfl to do so.
   55382 **
   55383 ** If an error occurs an SQLite error code is returned. Otherwise:
   55384 **
   55385 ** The page number of the next overflow page in the linked list is
   55386 ** written to *pPgnoNext. If page ovfl is the last page in its linked
   55387 ** list, *pPgnoNext is set to zero.
   55388 **
   55389 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
   55390 ** to page number pOvfl was obtained, then *ppPage is set to point to that
   55391 ** reference. It is the responsibility of the caller to call releasePage()
   55392 ** on *ppPage to free the reference. In no reference was obtained (because
   55393 ** the pointer-map was used to obtain the value for *pPgnoNext), then
   55394 ** *ppPage is set to zero.
   55395 */
   55396 static int getOverflowPage(
   55397   BtShared *pBt,               /* The database file */
   55398   Pgno ovfl,                   /* Current overflow page number */
   55399   MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
   55400   Pgno *pPgnoNext              /* OUT: Next overflow page number */
   55401 ){
   55402   Pgno next = 0;
   55403   MemPage *pPage = 0;
   55404   int rc = SQLITE_OK;
   55405 
   55406   assert( sqlite3_mutex_held(pBt->mutex) );
   55407   assert(pPgnoNext);
   55408 
   55409 #ifndef SQLITE_OMIT_AUTOVACUUM
   55410   /* Try to find the next page in the overflow list using the
   55411   ** autovacuum pointer-map pages. Guess that the next page in
   55412   ** the overflow list is page number (ovfl+1). If that guess turns
   55413   ** out to be wrong, fall back to loading the data of page
   55414   ** number ovfl to determine the next page number.
   55415   */
   55416   if( pBt->autoVacuum ){
   55417     Pgno pgno;
   55418     Pgno iGuess = ovfl+1;
   55419     u8 eType;
   55420 
   55421     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
   55422       iGuess++;
   55423     }
   55424 
   55425     if( iGuess<=btreePagecount(pBt) ){
   55426       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
   55427       if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
   55428         next = iGuess;
   55429         rc = SQLITE_DONE;
   55430       }
   55431     }
   55432   }
   55433 #endif
   55434 
   55435   assert( next==0 || rc==SQLITE_DONE );
   55436   if( rc==SQLITE_OK ){
   55437     rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
   55438     assert( rc==SQLITE_OK || pPage==0 );
   55439     if( rc==SQLITE_OK ){
   55440       next = get4byte(pPage->aData);
   55441     }
   55442   }
   55443 
   55444   *pPgnoNext = next;
   55445   if( ppPage ){
   55446     *ppPage = pPage;
   55447   }else{
   55448     releasePage(pPage);
   55449   }
   55450   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
   55451 }
   55452 
   55453 /*
   55454 ** Copy data from a buffer to a page, or from a page to a buffer.
   55455 **
   55456 ** pPayload is a pointer to data stored on database page pDbPage.
   55457 ** If argument eOp is false, then nByte bytes of data are copied
   55458 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
   55459 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
   55460 ** of data are copied from the buffer pBuf to pPayload.
   55461 **
   55462 ** SQLITE_OK is returned on success, otherwise an error code.
   55463 */
   55464 static int copyPayload(
   55465   void *pPayload,           /* Pointer to page data */
   55466   void *pBuf,               /* Pointer to buffer */
   55467   int nByte,                /* Number of bytes to copy */
   55468   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
   55469   DbPage *pDbPage           /* Page containing pPayload */
   55470 ){
   55471   if( eOp ){
   55472     /* Copy data from buffer to page (a write operation) */
   55473     int rc = sqlite3PagerWrite(pDbPage);
   55474     if( rc!=SQLITE_OK ){
   55475       return rc;
   55476     }
   55477     memcpy(pPayload, pBuf, nByte);
   55478   }else{
   55479     /* Copy data from page to buffer (a read operation) */
   55480     memcpy(pBuf, pPayload, nByte);
   55481   }
   55482   return SQLITE_OK;
   55483 }
   55484 
   55485 /*
   55486 ** This function is used to read or overwrite payload information
   55487 ** for the entry that the pCur cursor is pointing to. The eOp
   55488 ** argument is interpreted as follows:
   55489 **
   55490 **   0: The operation is a read. Populate the overflow cache.
   55491 **   1: The operation is a write. Populate the overflow cache.
   55492 **   2: The operation is a read. Do not populate the overflow cache.
   55493 **
   55494 ** A total of "amt" bytes are read or written beginning at "offset".
   55495 ** Data is read to or from the buffer pBuf.
   55496 **
   55497 ** The content being read or written might appear on the main page
   55498 ** or be scattered out on multiple overflow pages.
   55499 **
   55500 ** If the current cursor entry uses one or more overflow pages and the
   55501 ** eOp argument is not 2, this function may allocate space for and lazily
   55502 ** popluates the overflow page-list cache array (BtCursor.aOverflow).
   55503 ** Subsequent calls use this cache to make seeking to the supplied offset
   55504 ** more efficient.
   55505 **
   55506 ** Once an overflow page-list cache has been allocated, it may be
   55507 ** invalidated if some other cursor writes to the same table, or if
   55508 ** the cursor is moved to a different row. Additionally, in auto-vacuum
   55509 ** mode, the following events may invalidate an overflow page-list cache.
   55510 **
   55511 **   * An incremental vacuum,
   55512 **   * A commit in auto_vacuum="full" mode,
   55513 **   * Creating a table (may require moving an overflow page).
   55514 */
   55515 static int accessPayload(
   55516   BtCursor *pCur,      /* Cursor pointing to entry to read from */
   55517   u32 offset,          /* Begin reading this far into payload */
   55518   u32 amt,             /* Read this many bytes */
   55519   unsigned char *pBuf, /* Write the bytes into this buffer */
   55520   int eOp              /* zero to read. non-zero to write. */
   55521 ){
   55522   unsigned char *aPayload;
   55523   int rc = SQLITE_OK;
   55524   u32 nKey;
   55525   int iIdx = 0;
   55526   MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
   55527   BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
   55528 #ifdef SQLITE_DIRECT_OVERFLOW_READ
   55529   int bEnd;                                   /* True if reading to end of data */
   55530 #endif
   55531 
   55532   assert( pPage );
   55533   assert( pCur->eState==CURSOR_VALID );
   55534   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
   55535   assert( cursorHoldsMutex(pCur) );
   55536   assert( eOp!=2 || offset==0 );      /* Always start from beginning for eOp==2 */
   55537 
   55538   getCellInfo(pCur);
   55539   aPayload = pCur->info.pCell + pCur->info.nHeader;
   55540   nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
   55541 #ifdef SQLITE_DIRECT_OVERFLOW_READ
   55542   bEnd = (offset+amt==nKey+pCur->info.nData);
   55543 #endif
   55544 
   55545   if( NEVER(offset+amt > nKey+pCur->info.nData)
   55546    || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
   55547   ){
   55548     /* Trying to read or write past the end of the data is an error */
   55549     return SQLITE_CORRUPT_BKPT;
   55550   }
   55551 
   55552   /* Check if data must be read/written to/from the btree page itself. */
   55553   if( offset<pCur->info.nLocal ){
   55554     int a = amt;
   55555     if( a+offset>pCur->info.nLocal ){
   55556       a = pCur->info.nLocal - offset;
   55557     }
   55558     rc = copyPayload(&aPayload[offset], pBuf, a, (eOp & 0x01), pPage->pDbPage);
   55559     offset = 0;
   55560     pBuf += a;
   55561     amt -= a;
   55562   }else{
   55563     offset -= pCur->info.nLocal;
   55564   }
   55565 
   55566   if( rc==SQLITE_OK && amt>0 ){
   55567     const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
   55568     Pgno nextPage;
   55569 
   55570     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
   55571 
   55572     /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
   55573     ** Except, do not allocate aOverflow[] for eOp==2.
   55574     **
   55575     ** The aOverflow[] array is sized at one entry for each overflow page
   55576     ** in the overflow chain. The page number of the first overflow page is
   55577     ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
   55578     ** means "not yet known" (the cache is lazily populated).
   55579     */
   55580     if( eOp!=2 && (pCur->curFlags & BTCF_ValidOvfl)==0 ){
   55581       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
   55582       if( nOvfl>pCur->nOvflAlloc ){
   55583         Pgno *aNew = (Pgno*)sqlite3DbRealloc(
   55584             pCur->pBtree->db, pCur->aOverflow, nOvfl*2*sizeof(Pgno)
   55585         );
   55586         if( aNew==0 ){
   55587           rc = SQLITE_NOMEM;
   55588         }else{
   55589           pCur->nOvflAlloc = nOvfl*2;
   55590           pCur->aOverflow = aNew;
   55591         }
   55592       }
   55593       if( rc==SQLITE_OK ){
   55594         memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
   55595         pCur->curFlags |= BTCF_ValidOvfl;
   55596       }
   55597     }
   55598 
   55599     /* If the overflow page-list cache has been allocated and the
   55600     ** entry for the first required overflow page is valid, skip
   55601     ** directly to it.
   55602     */
   55603     if( (pCur->curFlags & BTCF_ValidOvfl)!=0 && pCur->aOverflow[offset/ovflSize] ){
   55604       iIdx = (offset/ovflSize);
   55605       nextPage = pCur->aOverflow[iIdx];
   55606       offset = (offset%ovflSize);
   55607     }
   55608 
   55609     for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
   55610 
   55611       /* If required, populate the overflow page-list cache. */
   55612       if( (pCur->curFlags & BTCF_ValidOvfl)!=0 ){
   55613         assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
   55614         pCur->aOverflow[iIdx] = nextPage;
   55615       }
   55616 
   55617       if( offset>=ovflSize ){
   55618         /* The only reason to read this page is to obtain the page
   55619         ** number for the next page in the overflow chain. The page
   55620         ** data is not required. So first try to lookup the overflow
   55621         ** page-list cache, if any, then fall back to the getOverflowPage()
   55622         ** function.
   55623         **
   55624         ** Note that the aOverflow[] array must be allocated because eOp!=2
   55625         ** here.  If eOp==2, then offset==0 and this branch is never taken.
   55626         */
   55627         assert( eOp!=2 );
   55628         assert( pCur->curFlags & BTCF_ValidOvfl );
   55629         if( pCur->aOverflow[iIdx+1] ){
   55630           nextPage = pCur->aOverflow[iIdx+1];
   55631         }else{
   55632           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
   55633         }
   55634         offset -= ovflSize;
   55635       }else{
   55636         /* Need to read this page properly. It contains some of the
   55637         ** range of data that is being read (eOp==0) or written (eOp!=0).
   55638         */
   55639 #ifdef SQLITE_DIRECT_OVERFLOW_READ
   55640         sqlite3_file *fd;
   55641 #endif
   55642         int a = amt;
   55643         if( a + offset > ovflSize ){
   55644           a = ovflSize - offset;
   55645         }
   55646 
   55647 #ifdef SQLITE_DIRECT_OVERFLOW_READ
   55648         /* If all the following are true:
   55649         **
   55650         **   1) this is a read operation, and
   55651         **   2) data is required from the start of this overflow page, and
   55652         **   3) the database is file-backed, and
   55653         **   4) there is no open write-transaction, and
   55654         **   5) the database is not a WAL database,
   55655         **   6) all data from the page is being read.
   55656         **
   55657         ** then data can be read directly from the database file into the
   55658         ** output buffer, bypassing the page-cache altogether. This speeds
   55659         ** up loading large records that span many overflow pages.
   55660         */
   55661         if( (eOp&0x01)==0                                      /* (1) */
   55662          && offset==0                                          /* (2) */
   55663          && (bEnd || a==ovflSize)                              /* (6) */
   55664          && pBt->inTransaction==TRANS_READ                     /* (4) */
   55665          && (fd = sqlite3PagerFile(pBt->pPager))->pMethods     /* (3) */
   55666          && pBt->pPage1->aData[19]==0x01                       /* (5) */
   55667         ){
   55668           u8 aSave[4];
   55669           u8 *aWrite = &pBuf[-4];
   55670           memcpy(aSave, aWrite, 4);
   55671           rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
   55672           nextPage = get4byte(aWrite);
   55673           memcpy(aWrite, aSave, 4);
   55674         }else
   55675 #endif
   55676 
   55677         {
   55678           DbPage *pDbPage;
   55679           rc = sqlite3PagerAcquire(pBt->pPager, nextPage, &pDbPage,
   55680               ((eOp&0x01)==0 ? PAGER_GET_READONLY : 0)
   55681           );
   55682           if( rc==SQLITE_OK ){
   55683             aPayload = sqlite3PagerGetData(pDbPage);
   55684             nextPage = get4byte(aPayload);
   55685             rc = copyPayload(&aPayload[offset+4], pBuf, a, (eOp&0x01), pDbPage);
   55686             sqlite3PagerUnref(pDbPage);
   55687             offset = 0;
   55688           }
   55689         }
   55690         amt -= a;
   55691         pBuf += a;
   55692       }
   55693     }
   55694   }
   55695 
   55696   if( rc==SQLITE_OK && amt>0 ){
   55697     return SQLITE_CORRUPT_BKPT;
   55698   }
   55699   return rc;
   55700 }
   55701 
   55702 /*
   55703 ** Read part of the key associated with cursor pCur.  Exactly
   55704 ** "amt" bytes will be transfered into pBuf[].  The transfer
   55705 ** begins at "offset".
   55706 **
   55707 ** The caller must ensure that pCur is pointing to a valid row
   55708 ** in the table.
   55709 **
   55710 ** Return SQLITE_OK on success or an error code if anything goes
   55711 ** wrong.  An error is returned if "offset+amt" is larger than
   55712 ** the available payload.
   55713 */
   55714 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
   55715   assert( cursorHoldsMutex(pCur) );
   55716   assert( pCur->eState==CURSOR_VALID );
   55717   assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
   55718   assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
   55719   return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
   55720 }
   55721 
   55722 /*
   55723 ** Read part of the data associated with cursor pCur.  Exactly
   55724 ** "amt" bytes will be transfered into pBuf[].  The transfer
   55725 ** begins at "offset".
   55726 **
   55727 ** Return SQLITE_OK on success or an error code if anything goes
   55728 ** wrong.  An error is returned if "offset+amt" is larger than
   55729 ** the available payload.
   55730 */
   55731 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
   55732   int rc;
   55733 
   55734 #ifndef SQLITE_OMIT_INCRBLOB
   55735   if ( pCur->eState==CURSOR_INVALID ){
   55736     return SQLITE_ABORT;
   55737   }
   55738 #endif
   55739 
   55740   assert( cursorHoldsMutex(pCur) );
   55741   rc = restoreCursorPosition(pCur);
   55742   if( rc==SQLITE_OK ){
   55743     assert( pCur->eState==CURSOR_VALID );
   55744     assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
   55745     assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
   55746     rc = accessPayload(pCur, offset, amt, pBuf, 0);
   55747   }
   55748   return rc;
   55749 }
   55750 
   55751 /*
   55752 ** Return a pointer to payload information from the entry that the
   55753 ** pCur cursor is pointing to.  The pointer is to the beginning of
   55754 ** the key if index btrees (pPage->intKey==0) and is the data for
   55755 ** table btrees (pPage->intKey==1). The number of bytes of available
   55756 ** key/data is written into *pAmt.  If *pAmt==0, then the value
   55757 ** returned will not be a valid pointer.
   55758 **
   55759 ** This routine is an optimization.  It is common for the entire key
   55760 ** and data to fit on the local page and for there to be no overflow
   55761 ** pages.  When that is so, this routine can be used to access the
   55762 ** key and data without making a copy.  If the key and/or data spills
   55763 ** onto overflow pages, then accessPayload() must be used to reassemble
   55764 ** the key/data and copy it into a preallocated buffer.
   55765 **
   55766 ** The pointer returned by this routine looks directly into the cached
   55767 ** page of the database.  The data might change or move the next time
   55768 ** any btree routine is called.
   55769 */
   55770 static const void *fetchPayload(
   55771   BtCursor *pCur,      /* Cursor pointing to entry to read from */
   55772   u32 *pAmt            /* Write the number of available bytes here */
   55773 ){
   55774   assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
   55775   assert( pCur->eState==CURSOR_VALID );
   55776   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
   55777   assert( cursorHoldsMutex(pCur) );
   55778   assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
   55779   assert( pCur->info.nSize>0 );
   55780   *pAmt = pCur->info.nLocal;
   55781   return (void*)(pCur->info.pCell + pCur->info.nHeader);
   55782 }
   55783 
   55784 
   55785 /*
   55786 ** For the entry that cursor pCur is point to, return as
   55787 ** many bytes of the key or data as are available on the local
   55788 ** b-tree page.  Write the number of available bytes into *pAmt.
   55789 **
   55790 ** The pointer returned is ephemeral.  The key/data may move
   55791 ** or be destroyed on the next call to any Btree routine,
   55792 ** including calls from other threads against the same cache.
   55793 ** Hence, a mutex on the BtShared should be held prior to calling
   55794 ** this routine.
   55795 **
   55796 ** These routines is used to get quick access to key and data
   55797 ** in the common case where no overflow pages are used.
   55798 */
   55799 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, u32 *pAmt){
   55800   return fetchPayload(pCur, pAmt);
   55801 }
   55802 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, u32 *pAmt){
   55803   return fetchPayload(pCur, pAmt);
   55804 }
   55805 
   55806 
   55807 /*
   55808 ** Move the cursor down to a new child page.  The newPgno argument is the
   55809 ** page number of the child page to move to.
   55810 **
   55811 ** This function returns SQLITE_CORRUPT if the page-header flags field of
   55812 ** the new child page does not match the flags field of the parent (i.e.
   55813 ** if an intkey page appears to be the parent of a non-intkey page, or
   55814 ** vice-versa).
   55815 */
   55816 static int moveToChild(BtCursor *pCur, u32 newPgno){
   55817   int rc;
   55818   int i = pCur->iPage;
   55819   MemPage *pNewPage;
   55820   BtShared *pBt = pCur->pBt;
   55821 
   55822   assert( cursorHoldsMutex(pCur) );
   55823   assert( pCur->eState==CURSOR_VALID );
   55824   assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
   55825   assert( pCur->iPage>=0 );
   55826   if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
   55827     return SQLITE_CORRUPT_BKPT;
   55828   }
   55829   rc = getAndInitPage(pBt, newPgno, &pNewPage,
   55830                (pCur->curFlags & BTCF_WriteFlag)==0 ? PAGER_GET_READONLY : 0);
   55831   if( rc ) return rc;
   55832   pCur->apPage[i+1] = pNewPage;
   55833   pCur->aiIdx[i+1] = 0;
   55834   pCur->iPage++;
   55835 
   55836   pCur->info.nSize = 0;
   55837   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
   55838   if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
   55839     return SQLITE_CORRUPT_BKPT;
   55840   }
   55841   return SQLITE_OK;
   55842 }
   55843 
   55844 #if 0
   55845 /*
   55846 ** Page pParent is an internal (non-leaf) tree page. This function
   55847 ** asserts that page number iChild is the left-child if the iIdx'th
   55848 ** cell in page pParent. Or, if iIdx is equal to the total number of
   55849 ** cells in pParent, that page number iChild is the right-child of
   55850 ** the page.
   55851 */
   55852 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
   55853   assert( iIdx<=pParent->nCell );
   55854   if( iIdx==pParent->nCell ){
   55855     assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
   55856   }else{
   55857     assert( get4byte(findCell(pParent, iIdx))==iChild );
   55858   }
   55859 }
   55860 #else
   55861 #  define assertParentIndex(x,y,z)
   55862 #endif
   55863 
   55864 /*
   55865 ** Move the cursor up to the parent page.
   55866 **
   55867 ** pCur->idx is set to the cell index that contains the pointer
   55868 ** to the page we are coming from.  If we are coming from the
   55869 ** right-most child page then pCur->idx is set to one more than
   55870 ** the largest cell index.
   55871 */
   55872 static void moveToParent(BtCursor *pCur){
   55873   assert( cursorHoldsMutex(pCur) );
   55874   assert( pCur->eState==CURSOR_VALID );
   55875   assert( pCur->iPage>0 );
   55876   assert( pCur->apPage[pCur->iPage] );
   55877 
   55878   /* UPDATE: It is actually possible for the condition tested by the assert
   55879   ** below to be untrue if the database file is corrupt. This can occur if
   55880   ** one cursor has modified page pParent while a reference to it is held
   55881   ** by a second cursor. Which can only happen if a single page is linked
   55882   ** into more than one b-tree structure in a corrupt database.  */
   55883 #if 0
   55884   assertParentIndex(
   55885     pCur->apPage[pCur->iPage-1],
   55886     pCur->aiIdx[pCur->iPage-1],
   55887     pCur->apPage[pCur->iPage]->pgno
   55888   );
   55889 #endif
   55890   testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
   55891 
   55892   releasePage(pCur->apPage[pCur->iPage]);
   55893   pCur->iPage--;
   55894   pCur->info.nSize = 0;
   55895   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
   55896 }
   55897 
   55898 /*
   55899 ** Move the cursor to point to the root page of its b-tree structure.
   55900 **
   55901 ** If the table has a virtual root page, then the cursor is moved to point
   55902 ** to the virtual root page instead of the actual root page. A table has a
   55903 ** virtual root page when the actual root page contains no cells and a
   55904 ** single child page. This can only happen with the table rooted at page 1.
   55905 **
   55906 ** If the b-tree structure is empty, the cursor state is set to
   55907 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
   55908 ** cell located on the root (or virtual root) page and the cursor state
   55909 ** is set to CURSOR_VALID.
   55910 **
   55911 ** If this function returns successfully, it may be assumed that the
   55912 ** page-header flags indicate that the [virtual] root-page is the expected
   55913 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
   55914 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
   55915 ** indicating a table b-tree, or if the caller did specify a KeyInfo
   55916 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
   55917 ** b-tree).
   55918 */
   55919 static int moveToRoot(BtCursor *pCur){
   55920   MemPage *pRoot;
   55921   int rc = SQLITE_OK;
   55922 
   55923   assert( cursorHoldsMutex(pCur) );
   55924   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
   55925   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
   55926   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
   55927   if( pCur->eState>=CURSOR_REQUIRESEEK ){
   55928     if( pCur->eState==CURSOR_FAULT ){
   55929       assert( pCur->skipNext!=SQLITE_OK );
   55930       return pCur->skipNext;
   55931     }
   55932     sqlite3BtreeClearCursor(pCur);
   55933   }
   55934 
   55935   if( pCur->iPage>=0 ){
   55936     while( pCur->iPage ) releasePage(pCur->apPage[pCur->iPage--]);
   55937   }else if( pCur->pgnoRoot==0 ){
   55938     pCur->eState = CURSOR_INVALID;
   55939     return SQLITE_OK;
   55940   }else{
   55941     rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->apPage[0],
   55942                  (pCur->curFlags & BTCF_WriteFlag)==0 ? PAGER_GET_READONLY : 0);
   55943     if( rc!=SQLITE_OK ){
   55944       pCur->eState = CURSOR_INVALID;
   55945       return rc;
   55946     }
   55947     pCur->iPage = 0;
   55948   }
   55949   pRoot = pCur->apPage[0];
   55950   assert( pRoot->pgno==pCur->pgnoRoot );
   55951 
   55952   /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
   55953   ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
   55954   ** NULL, the caller expects a table b-tree. If this is not the case,
   55955   ** return an SQLITE_CORRUPT error.
   55956   **
   55957   ** Earlier versions of SQLite assumed that this test could not fail
   55958   ** if the root page was already loaded when this function was called (i.e.
   55959   ** if pCur->iPage>=0). But this is not so if the database is corrupted
   55960   ** in such a way that page pRoot is linked into a second b-tree table
   55961   ** (or the freelist).  */
   55962   assert( pRoot->intKey==1 || pRoot->intKey==0 );
   55963   if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
   55964     return SQLITE_CORRUPT_BKPT;
   55965   }
   55966 
   55967   pCur->aiIdx[0] = 0;
   55968   pCur->info.nSize = 0;
   55969   pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
   55970 
   55971   if( pRoot->nCell>0 ){
   55972     pCur->eState = CURSOR_VALID;
   55973   }else if( !pRoot->leaf ){
   55974     Pgno subpage;
   55975     if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
   55976     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
   55977     pCur->eState = CURSOR_VALID;
   55978     rc = moveToChild(pCur, subpage);
   55979   }else{
   55980     pCur->eState = CURSOR_INVALID;
   55981   }
   55982   return rc;
   55983 }
   55984 
   55985 /*
   55986 ** Move the cursor down to the left-most leaf entry beneath the
   55987 ** entry to which it is currently pointing.
   55988 **
   55989 ** The left-most leaf is the one with the smallest key - the first
   55990 ** in ascending order.
   55991 */
   55992 static int moveToLeftmost(BtCursor *pCur){
   55993   Pgno pgno;
   55994   int rc = SQLITE_OK;
   55995   MemPage *pPage;
   55996 
   55997   assert( cursorHoldsMutex(pCur) );
   55998   assert( pCur->eState==CURSOR_VALID );
   55999   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
   56000     assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
   56001     pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
   56002     rc = moveToChild(pCur, pgno);
   56003   }
   56004   return rc;
   56005 }
   56006 
   56007 /*
   56008 ** Move the cursor down to the right-most leaf entry beneath the
   56009 ** page to which it is currently pointing.  Notice the difference
   56010 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
   56011 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
   56012 ** finds the right-most entry beneath the *page*.
   56013 **
   56014 ** The right-most entry is the one with the largest key - the last
   56015 ** key in ascending order.
   56016 */
   56017 static int moveToRightmost(BtCursor *pCur){
   56018   Pgno pgno;
   56019   int rc = SQLITE_OK;
   56020   MemPage *pPage = 0;
   56021 
   56022   assert( cursorHoldsMutex(pCur) );
   56023   assert( pCur->eState==CURSOR_VALID );
   56024   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
   56025     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
   56026     pCur->aiIdx[pCur->iPage] = pPage->nCell;
   56027     rc = moveToChild(pCur, pgno);
   56028   }
   56029   if( rc==SQLITE_OK ){
   56030     pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
   56031     pCur->info.nSize = 0;
   56032     pCur->curFlags &= ~BTCF_ValidNKey;
   56033   }
   56034   return rc;
   56035 }
   56036 
   56037 /* Move the cursor to the first entry in the table.  Return SQLITE_OK
   56038 ** on success.  Set *pRes to 0 if the cursor actually points to something
   56039 ** or set *pRes to 1 if the table is empty.
   56040 */
   56041 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
   56042   int rc;
   56043 
   56044   assert( cursorHoldsMutex(pCur) );
   56045   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
   56046   rc = moveToRoot(pCur);
   56047   if( rc==SQLITE_OK ){
   56048     if( pCur->eState==CURSOR_INVALID ){
   56049       assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
   56050       *pRes = 1;
   56051     }else{
   56052       assert( pCur->apPage[pCur->iPage]->nCell>0 );
   56053       *pRes = 0;
   56054       rc = moveToLeftmost(pCur);
   56055     }
   56056   }
   56057   return rc;
   56058 }
   56059 
   56060 /* Move the cursor to the last entry in the table.  Return SQLITE_OK
   56061 ** on success.  Set *pRes to 0 if the cursor actually points to something
   56062 ** or set *pRes to 1 if the table is empty.
   56063 */
   56064 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
   56065   int rc;
   56066 
   56067   assert( cursorHoldsMutex(pCur) );
   56068   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
   56069 
   56070   /* If the cursor already points to the last entry, this is a no-op. */
   56071   if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
   56072 #ifdef SQLITE_DEBUG
   56073     /* This block serves to assert() that the cursor really does point
   56074     ** to the last entry in the b-tree. */
   56075     int ii;
   56076     for(ii=0; ii<pCur->iPage; ii++){
   56077       assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
   56078     }
   56079     assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
   56080     assert( pCur->apPage[pCur->iPage]->leaf );
   56081 #endif
   56082     return SQLITE_OK;
   56083   }
   56084 
   56085   rc = moveToRoot(pCur);
   56086   if( rc==SQLITE_OK ){
   56087     if( CURSOR_INVALID==pCur->eState ){
   56088       assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
   56089       *pRes = 1;
   56090     }else{
   56091       assert( pCur->eState==CURSOR_VALID );
   56092       *pRes = 0;
   56093       rc = moveToRightmost(pCur);
   56094       if( rc==SQLITE_OK ){
   56095         pCur->curFlags |= BTCF_AtLast;
   56096       }else{
   56097         pCur->curFlags &= ~BTCF_AtLast;
   56098       }
   56099 
   56100     }
   56101   }
   56102   return rc;
   56103 }
   56104 
   56105 /* Move the cursor so that it points to an entry near the key
   56106 ** specified by pIdxKey or intKey.   Return a success code.
   56107 **
   56108 ** For INTKEY tables, the intKey parameter is used.  pIdxKey
   56109 ** must be NULL.  For index tables, pIdxKey is used and intKey
   56110 ** is ignored.
   56111 **
   56112 ** If an exact match is not found, then the cursor is always
   56113 ** left pointing at a leaf page which would hold the entry if it
   56114 ** were present.  The cursor might point to an entry that comes
   56115 ** before or after the key.
   56116 **
   56117 ** An integer is written into *pRes which is the result of
   56118 ** comparing the key with the entry to which the cursor is
   56119 ** pointing.  The meaning of the integer written into
   56120 ** *pRes is as follows:
   56121 **
   56122 **     *pRes<0      The cursor is left pointing at an entry that
   56123 **                  is smaller than intKey/pIdxKey or if the table is empty
   56124 **                  and the cursor is therefore left point to nothing.
   56125 **
   56126 **     *pRes==0     The cursor is left pointing at an entry that
   56127 **                  exactly matches intKey/pIdxKey.
   56128 **
   56129 **     *pRes>0      The cursor is left pointing at an entry that
   56130 **                  is larger than intKey/pIdxKey.
   56131 **
   56132 */
   56133 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
   56134   BtCursor *pCur,          /* The cursor to be moved */
   56135   UnpackedRecord *pIdxKey, /* Unpacked index key */
   56136   i64 intKey,              /* The table key */
   56137   int biasRight,           /* If true, bias the search to the high end */
   56138   int *pRes                /* Write search results here */
   56139 ){
   56140   int rc;
   56141   RecordCompare xRecordCompare;
   56142 
   56143   assert( cursorHoldsMutex(pCur) );
   56144   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
   56145   assert( pRes );
   56146   assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
   56147 
   56148   /* If the cursor is already positioned at the point we are trying
   56149   ** to move to, then just return without doing any work */
   56150   if( pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
   56151    && pCur->apPage[0]->intKey
   56152   ){
   56153     if( pCur->info.nKey==intKey ){
   56154       *pRes = 0;
   56155       return SQLITE_OK;
   56156     }
   56157     if( (pCur->curFlags & BTCF_AtLast)!=0 && pCur->info.nKey<intKey ){
   56158       *pRes = -1;
   56159       return SQLITE_OK;
   56160     }
   56161   }
   56162 
   56163   if( pIdxKey ){
   56164     xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
   56165     pIdxKey->isCorrupt = 0;
   56166     assert( pIdxKey->default_rc==1
   56167          || pIdxKey->default_rc==0
   56168          || pIdxKey->default_rc==-1
   56169     );
   56170   }else{
   56171     xRecordCompare = 0; /* All keys are integers */
   56172   }
   56173 
   56174   rc = moveToRoot(pCur);
   56175   if( rc ){
   56176     return rc;
   56177   }
   56178   assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
   56179   assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
   56180   assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
   56181   if( pCur->eState==CURSOR_INVALID ){
   56182     *pRes = -1;
   56183     assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
   56184     return SQLITE_OK;
   56185   }
   56186   assert( pCur->apPage[0]->intKey || pIdxKey );
   56187   for(;;){
   56188     int lwr, upr, idx, c;
   56189     Pgno chldPg;
   56190     MemPage *pPage = pCur->apPage[pCur->iPage];
   56191     u8 *pCell;                          /* Pointer to current cell in pPage */
   56192 
   56193     /* pPage->nCell must be greater than zero. If this is the root-page
   56194     ** the cursor would have been INVALID above and this for(;;) loop
   56195     ** not run. If this is not the root-page, then the moveToChild() routine
   56196     ** would have already detected db corruption. Similarly, pPage must
   56197     ** be the right kind (index or table) of b-tree page. Otherwise
   56198     ** a moveToChild() or moveToRoot() call would have detected corruption.  */
   56199     assert( pPage->nCell>0 );
   56200     assert( pPage->intKey==(pIdxKey==0) );
   56201     lwr = 0;
   56202     upr = pPage->nCell-1;
   56203     assert( biasRight==0 || biasRight==1 );
   56204     idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
   56205     pCur->aiIdx[pCur->iPage] = (u16)idx;
   56206     if( xRecordCompare==0 ){
   56207       for(;;){
   56208         i64 nCellKey;
   56209         pCell = findCell(pPage, idx) + pPage->childPtrSize;
   56210         if( pPage->hasData ){
   56211           while( 0x80 <= *(pCell++) ){
   56212             if( pCell>=pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
   56213           }
   56214         }
   56215         getVarint(pCell, (u64*)&nCellKey);
   56216         if( nCellKey<intKey ){
   56217           lwr = idx+1;
   56218           if( lwr>upr ){ c = -1; break; }
   56219         }else if( nCellKey>intKey ){
   56220           upr = idx-1;
   56221           if( lwr>upr ){ c = +1; break; }
   56222         }else{
   56223           assert( nCellKey==intKey );
   56224           pCur->curFlags |= BTCF_ValidNKey;
   56225           pCur->info.nKey = nCellKey;
   56226           pCur->aiIdx[pCur->iPage] = (u16)idx;
   56227           if( !pPage->leaf ){
   56228             lwr = idx;
   56229             goto moveto_next_layer;
   56230           }else{
   56231             *pRes = 0;
   56232             rc = SQLITE_OK;
   56233             goto moveto_finish;
   56234           }
   56235         }
   56236         assert( lwr+upr>=0 );
   56237         idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2; */
   56238       }
   56239     }else{
   56240       for(;;){
   56241         int nCell;
   56242         pCell = findCell(pPage, idx) + pPage->childPtrSize;
   56243 
   56244         /* The maximum supported page-size is 65536 bytes. This means that
   56245         ** the maximum number of record bytes stored on an index B-Tree
   56246         ** page is less than 16384 bytes and may be stored as a 2-byte
   56247         ** varint. This information is used to attempt to avoid parsing
   56248         ** the entire cell by checking for the cases where the record is
   56249         ** stored entirely within the b-tree page by inspecting the first
   56250         ** 2 bytes of the cell.
   56251         */
   56252         nCell = pCell[0];
   56253         if( nCell<=pPage->max1bytePayload ){
   56254           /* This branch runs if the record-size field of the cell is a
   56255           ** single byte varint and the record fits entirely on the main
   56256           ** b-tree page.  */
   56257           testcase( pCell+nCell+1==pPage->aDataEnd );
   56258           c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey, 0);
   56259         }else if( !(pCell[1] & 0x80)
   56260           && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
   56261         ){
   56262           /* The record-size field is a 2 byte varint and the record
   56263           ** fits entirely on the main b-tree page.  */
   56264           testcase( pCell+nCell+2==pPage->aDataEnd );
   56265           c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey, 0);
   56266         }else{
   56267           /* The record flows over onto one or more overflow pages. In
   56268           ** this case the whole cell needs to be parsed, a buffer allocated
   56269           ** and accessPayload() used to retrieve the record into the
   56270           ** buffer before VdbeRecordCompare() can be called. */
   56271           void *pCellKey;
   56272           u8 * const pCellBody = pCell - pPage->childPtrSize;
   56273           btreeParseCellPtr(pPage, pCellBody, &pCur->info);
   56274           nCell = (int)pCur->info.nKey;
   56275           pCellKey = sqlite3Malloc( nCell );
   56276           if( pCellKey==0 ){
   56277             rc = SQLITE_NOMEM;
   56278             goto moveto_finish;
   56279           }
   56280           pCur->aiIdx[pCur->iPage] = (u16)idx;
   56281           rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 2);
   56282           if( rc ){
   56283             sqlite3_free(pCellKey);
   56284             goto moveto_finish;
   56285           }
   56286           c = xRecordCompare(nCell, pCellKey, pIdxKey, 0);
   56287           sqlite3_free(pCellKey);
   56288         }
   56289         assert( pIdxKey->isCorrupt==0 || c==0 );
   56290         if( c<0 ){
   56291           lwr = idx+1;
   56292         }else if( c>0 ){
   56293           upr = idx-1;
   56294         }else{
   56295           assert( c==0 );
   56296           *pRes = 0;
   56297           rc = SQLITE_OK;
   56298           pCur->aiIdx[pCur->iPage] = (u16)idx;
   56299           if( pIdxKey->isCorrupt ) rc = SQLITE_CORRUPT;
   56300           goto moveto_finish;
   56301         }
   56302         if( lwr>upr ) break;
   56303         assert( lwr+upr>=0 );
   56304         idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2 */
   56305       }
   56306     }
   56307     assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
   56308     assert( pPage->isInit );
   56309     if( pPage->leaf ){
   56310       assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
   56311       pCur->aiIdx[pCur->iPage] = (u16)idx;
   56312       *pRes = c;
   56313       rc = SQLITE_OK;
   56314       goto moveto_finish;
   56315     }
   56316 moveto_next_layer:
   56317     if( lwr>=pPage->nCell ){
   56318       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
   56319     }else{
   56320       chldPg = get4byte(findCell(pPage, lwr));
   56321     }
   56322     pCur->aiIdx[pCur->iPage] = (u16)lwr;
   56323     rc = moveToChild(pCur, chldPg);
   56324     if( rc ) break;
   56325   }
   56326 moveto_finish:
   56327   pCur->info.nSize = 0;
   56328   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
   56329   return rc;
   56330 }
   56331 
   56332 
   56333 /*
   56334 ** Return TRUE if the cursor is not pointing at an entry of the table.
   56335 **
   56336 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
   56337 ** past the last entry in the table or sqlite3BtreePrev() moves past
   56338 ** the first entry.  TRUE is also returned if the table is empty.
   56339 */
   56340 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
   56341   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
   56342   ** have been deleted? This API will need to change to return an error code
   56343   ** as well as the boolean result value.
   56344   */
   56345   return (CURSOR_VALID!=pCur->eState);
   56346 }
   56347 
   56348 /*
   56349 ** Advance the cursor to the next entry in the database.  If
   56350 ** successful then set *pRes=0.  If the cursor
   56351 ** was already pointing to the last entry in the database before
   56352 ** this routine was called, then set *pRes=1.
   56353 **
   56354 ** The calling function will set *pRes to 0 or 1.  The initial *pRes value
   56355 ** will be 1 if the cursor being stepped corresponds to an SQL index and
   56356 ** if this routine could have been skipped if that SQL index had been
   56357 ** a unique index.  Otherwise the caller will have set *pRes to zero.
   56358 ** Zero is the common case. The btree implementation is free to use the
   56359 ** initial *pRes value as a hint to improve performance, but the current
   56360 ** SQLite btree implementation does not. (Note that the comdb2 btree
   56361 ** implementation does use this hint, however.)
   56362 */
   56363 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
   56364   int rc;
   56365   int idx;
   56366   MemPage *pPage;
   56367 
   56368   assert( cursorHoldsMutex(pCur) );
   56369   assert( pRes!=0 );
   56370   assert( *pRes==0 || *pRes==1 );
   56371   assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
   56372   if( pCur->eState!=CURSOR_VALID ){
   56373     invalidateOverflowCache(pCur);
   56374     rc = restoreCursorPosition(pCur);
   56375     if( rc!=SQLITE_OK ){
   56376       *pRes = 0;
   56377       return rc;
   56378     }
   56379     if( CURSOR_INVALID==pCur->eState ){
   56380       *pRes = 1;
   56381       return SQLITE_OK;
   56382     }
   56383     if( pCur->skipNext ){
   56384       assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
   56385       pCur->eState = CURSOR_VALID;
   56386       if( pCur->skipNext>0 ){
   56387         pCur->skipNext = 0;
   56388         *pRes = 0;
   56389         return SQLITE_OK;
   56390       }
   56391       pCur->skipNext = 0;
   56392     }
   56393   }
   56394 
   56395   pPage = pCur->apPage[pCur->iPage];
   56396   idx = ++pCur->aiIdx[pCur->iPage];
   56397   assert( pPage->isInit );
   56398 
   56399   /* If the database file is corrupt, it is possible for the value of idx
   56400   ** to be invalid here. This can only occur if a second cursor modifies
   56401   ** the page while cursor pCur is holding a reference to it. Which can
   56402   ** only happen if the database is corrupt in such a way as to link the
   56403   ** page into more than one b-tree structure. */
   56404   testcase( idx>pPage->nCell );
   56405 
   56406   pCur->info.nSize = 0;
   56407   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
   56408   if( idx>=pPage->nCell ){
   56409     if( !pPage->leaf ){
   56410       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
   56411       if( rc ){
   56412         *pRes = 0;
   56413         return rc;
   56414       }
   56415       rc = moveToLeftmost(pCur);
   56416       *pRes = 0;
   56417       return rc;
   56418     }
   56419     do{
   56420       if( pCur->iPage==0 ){
   56421         *pRes = 1;
   56422         pCur->eState = CURSOR_INVALID;
   56423         return SQLITE_OK;
   56424       }
   56425       moveToParent(pCur);
   56426       pPage = pCur->apPage[pCur->iPage];
   56427     }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
   56428     *pRes = 0;
   56429     if( pPage->intKey ){
   56430       rc = sqlite3BtreeNext(pCur, pRes);
   56431     }else{
   56432       rc = SQLITE_OK;
   56433     }
   56434     return rc;
   56435   }
   56436   *pRes = 0;
   56437   if( pPage->leaf ){
   56438     return SQLITE_OK;
   56439   }
   56440   rc = moveToLeftmost(pCur);
   56441   return rc;
   56442 }
   56443 
   56444 
   56445 /*
   56446 ** Step the cursor to the back to the previous entry in the database.  If
   56447 ** successful then set *pRes=0.  If the cursor
   56448 ** was already pointing to the first entry in the database before
   56449 ** this routine was called, then set *pRes=1.
   56450 **
   56451 ** The calling function will set *pRes to 0 or 1.  The initial *pRes value
   56452 ** will be 1 if the cursor being stepped corresponds to an SQL index and
   56453 ** if this routine could have been skipped if that SQL index had been
   56454 ** a unique index.  Otherwise the caller will have set *pRes to zero.
   56455 ** Zero is the common case. The btree implementation is free to use the
   56456 ** initial *pRes value as a hint to improve performance, but the current
   56457 ** SQLite btree implementation does not. (Note that the comdb2 btree
   56458 ** implementation does use this hint, however.)
   56459 */
   56460 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
   56461   int rc;
   56462   MemPage *pPage;
   56463 
   56464   assert( cursorHoldsMutex(pCur) );
   56465   assert( pRes!=0 );
   56466   assert( *pRes==0 || *pRes==1 );
   56467   assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
   56468   pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl);
   56469   if( pCur->eState!=CURSOR_VALID ){
   56470     if( ALWAYS(pCur->eState>=CURSOR_REQUIRESEEK) ){
   56471       rc = btreeRestoreCursorPosition(pCur);
   56472       if( rc!=SQLITE_OK ){
   56473         *pRes = 0;
   56474         return rc;
   56475       }
   56476     }
   56477     if( CURSOR_INVALID==pCur->eState ){
   56478       *pRes = 1;
   56479       return SQLITE_OK;
   56480     }
   56481     if( pCur->skipNext ){
   56482       assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
   56483       pCur->eState = CURSOR_VALID;
   56484       if( pCur->skipNext<0 ){
   56485         pCur->skipNext = 0;
   56486         *pRes = 0;
   56487         return SQLITE_OK;
   56488       }
   56489       pCur->skipNext = 0;
   56490     }
   56491   }
   56492 
   56493   pPage = pCur->apPage[pCur->iPage];
   56494   assert( pPage->isInit );
   56495   if( !pPage->leaf ){
   56496     int idx = pCur->aiIdx[pCur->iPage];
   56497     rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
   56498     if( rc ){
   56499       *pRes = 0;
   56500       return rc;
   56501     }
   56502     rc = moveToRightmost(pCur);
   56503   }else{
   56504     while( pCur->aiIdx[pCur->iPage]==0 ){
   56505       if( pCur->iPage==0 ){
   56506         pCur->eState = CURSOR_INVALID;
   56507         *pRes = 1;
   56508         return SQLITE_OK;
   56509       }
   56510       moveToParent(pCur);
   56511     }
   56512     pCur->info.nSize = 0;
   56513     pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
   56514 
   56515     pCur->aiIdx[pCur->iPage]--;
   56516     pPage = pCur->apPage[pCur->iPage];
   56517     if( pPage->intKey && !pPage->leaf ){
   56518       rc = sqlite3BtreePrevious(pCur, pRes);
   56519     }else{
   56520       rc = SQLITE_OK;
   56521     }
   56522   }
   56523   *pRes = 0;
   56524   return rc;
   56525 }
   56526 
   56527 /*
   56528 ** Allocate a new page from the database file.
   56529 **
   56530 ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
   56531 ** has already been called on the new page.)  The new page has also
   56532 ** been referenced and the calling routine is responsible for calling
   56533 ** sqlite3PagerUnref() on the new page when it is done.
   56534 **
   56535 ** SQLITE_OK is returned on success.  Any other return value indicates
   56536 ** an error.  *ppPage and *pPgno are undefined in the event of an error.
   56537 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
   56538 **
   56539 ** If the "nearby" parameter is not 0, then an effort is made to
   56540 ** locate a page close to the page number "nearby".  This can be used in an
   56541 ** attempt to keep related pages close to each other in the database file,
   56542 ** which in turn can make database access faster.
   56543 **
   56544 ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
   56545 ** anywhere on the free-list, then it is guaranteed to be returned.  If
   56546 ** eMode is BTALLOC_LT then the page returned will be less than or equal
   56547 ** to nearby if any such page exists.  If eMode is BTALLOC_ANY then there
   56548 ** are no restrictions on which page is returned.
   56549 */
   56550 static int allocateBtreePage(
   56551   BtShared *pBt,         /* The btree */
   56552   MemPage **ppPage,      /* Store pointer to the allocated page here */
   56553   Pgno *pPgno,           /* Store the page number here */
   56554   Pgno nearby,           /* Search for a page near this one */
   56555   u8 eMode               /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
   56556 ){
   56557   MemPage *pPage1;
   56558   int rc;
   56559   u32 n;     /* Number of pages on the freelist */
   56560   u32 k;     /* Number of leaves on the trunk of the freelist */
   56561   MemPage *pTrunk = 0;
   56562   MemPage *pPrevTrunk = 0;
   56563   Pgno mxPage;     /* Total size of the database file */
   56564 
   56565   assert( sqlite3_mutex_held(pBt->mutex) );
   56566   assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
   56567   pPage1 = pBt->pPage1;
   56568   mxPage = btreePagecount(pBt);
   56569   n = get4byte(&pPage1->aData[36]);
   56570   testcase( n==mxPage-1 );
   56571   if( n>=mxPage ){
   56572     return SQLITE_CORRUPT_BKPT;
   56573   }
   56574   if( n>0 ){
   56575     /* There are pages on the freelist.  Reuse one of those pages. */
   56576     Pgno iTrunk;
   56577     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
   56578 
   56579     /* If eMode==BTALLOC_EXACT and a query of the pointer-map
   56580     ** shows that the page 'nearby' is somewhere on the free-list, then
   56581     ** the entire-list will be searched for that page.
   56582     */
   56583 #ifndef SQLITE_OMIT_AUTOVACUUM
   56584     if( eMode==BTALLOC_EXACT ){
   56585       if( nearby<=mxPage ){
   56586         u8 eType;
   56587         assert( nearby>0 );
   56588         assert( pBt->autoVacuum );
   56589         rc = ptrmapGet(pBt, nearby, &eType, 0);
   56590         if( rc ) return rc;
   56591         if( eType==PTRMAP_FREEPAGE ){
   56592           searchList = 1;
   56593         }
   56594       }
   56595     }else if( eMode==BTALLOC_LE ){
   56596       searchList = 1;
   56597     }
   56598 #endif
   56599 
   56600     /* Decrement the free-list count by 1. Set iTrunk to the index of the
   56601     ** first free-list trunk page. iPrevTrunk is initially 1.
   56602     */
   56603     rc = sqlite3PagerWrite(pPage1->pDbPage);
   56604     if( rc ) return rc;
   56605     put4byte(&pPage1->aData[36], n-1);
   56606 
   56607     /* The code within this loop is run only once if the 'searchList' variable
   56608     ** is not true. Otherwise, it runs once for each trunk-page on the
   56609     ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
   56610     ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
   56611     */
   56612     do {
   56613       pPrevTrunk = pTrunk;
   56614       if( pPrevTrunk ){
   56615         iTrunk = get4byte(&pPrevTrunk->aData[0]);
   56616       }else{
   56617         iTrunk = get4byte(&pPage1->aData[32]);
   56618       }
   56619       testcase( iTrunk==mxPage );
   56620       if( iTrunk>mxPage ){
   56621         rc = SQLITE_CORRUPT_BKPT;
   56622       }else{
   56623         rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
   56624       }
   56625       if( rc ){
   56626         pTrunk = 0;
   56627         goto end_allocate_page;
   56628       }
   56629       assert( pTrunk!=0 );
   56630       assert( pTrunk->aData!=0 );
   56631 
   56632       k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
   56633       if( k==0 && !searchList ){
   56634         /* The trunk has no leaves and the list is not being searched.
   56635         ** So extract the trunk page itself and use it as the newly
   56636         ** allocated page */
   56637         assert( pPrevTrunk==0 );
   56638         rc = sqlite3PagerWrite(pTrunk->pDbPage);
   56639         if( rc ){
   56640           goto end_allocate_page;
   56641         }
   56642         *pPgno = iTrunk;
   56643         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
   56644         *ppPage = pTrunk;
   56645         pTrunk = 0;
   56646         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
   56647       }else if( k>(u32)(pBt->usableSize/4 - 2) ){
   56648         /* Value of k is out of range.  Database corruption */
   56649         rc = SQLITE_CORRUPT_BKPT;
   56650         goto end_allocate_page;
   56651 #ifndef SQLITE_OMIT_AUTOVACUUM
   56652       }else if( searchList
   56653             && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
   56654       ){
   56655         /* The list is being searched and this trunk page is the page
   56656         ** to allocate, regardless of whether it has leaves.
   56657         */
   56658         *pPgno = iTrunk;
   56659         *ppPage = pTrunk;
   56660         searchList = 0;
   56661         rc = sqlite3PagerWrite(pTrunk->pDbPage);
   56662         if( rc ){
   56663           goto end_allocate_page;
   56664         }
   56665         if( k==0 ){
   56666           if( !pPrevTrunk ){
   56667             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
   56668           }else{
   56669             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
   56670             if( rc!=SQLITE_OK ){
   56671               goto end_allocate_page;
   56672             }
   56673             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
   56674           }
   56675         }else{
   56676           /* The trunk page is required by the caller but it contains
   56677           ** pointers to free-list leaves. The first leaf becomes a trunk
   56678           ** page in this case.
   56679           */
   56680           MemPage *pNewTrunk;
   56681           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
   56682           if( iNewTrunk>mxPage ){
   56683             rc = SQLITE_CORRUPT_BKPT;
   56684             goto end_allocate_page;
   56685           }
   56686           testcase( iNewTrunk==mxPage );
   56687           rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
   56688           if( rc!=SQLITE_OK ){
   56689             goto end_allocate_page;
   56690           }
   56691           rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
   56692           if( rc!=SQLITE_OK ){
   56693             releasePage(pNewTrunk);
   56694             goto end_allocate_page;
   56695           }
   56696           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
   56697           put4byte(&pNewTrunk->aData[4], k-1);
   56698           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
   56699           releasePage(pNewTrunk);
   56700           if( !pPrevTrunk ){
   56701             assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
   56702             put4byte(&pPage1->aData[32], iNewTrunk);
   56703           }else{
   56704             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
   56705             if( rc ){
   56706               goto end_allocate_page;
   56707             }
   56708             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
   56709           }
   56710         }
   56711         pTrunk = 0;
   56712         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
   56713 #endif
   56714       }else if( k>0 ){
   56715         /* Extract a leaf from the trunk */
   56716         u32 closest;
   56717         Pgno iPage;
   56718         unsigned char *aData = pTrunk->aData;
   56719         if( nearby>0 ){
   56720           u32 i;
   56721           closest = 0;
   56722           if( eMode==BTALLOC_LE ){
   56723             for(i=0; i<k; i++){
   56724               iPage = get4byte(&aData[8+i*4]);
   56725               if( iPage<=nearby ){
   56726                 closest = i;
   56727                 break;
   56728               }
   56729             }
   56730           }else{
   56731             int dist;
   56732             dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
   56733             for(i=1; i<k; i++){
   56734               int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
   56735               if( d2<dist ){
   56736                 closest = i;
   56737                 dist = d2;
   56738               }
   56739             }
   56740           }
   56741         }else{
   56742           closest = 0;
   56743         }
   56744 
   56745         iPage = get4byte(&aData[8+closest*4]);
   56746         testcase( iPage==mxPage );
   56747         if( iPage>mxPage ){
   56748           rc = SQLITE_CORRUPT_BKPT;
   56749           goto end_allocate_page;
   56750         }
   56751         testcase( iPage==mxPage );
   56752         if( !searchList
   56753          || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
   56754         ){
   56755           int noContent;
   56756           *pPgno = iPage;
   56757           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
   56758                  ": %d more free pages\n",
   56759                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
   56760           rc = sqlite3PagerWrite(pTrunk->pDbPage);
   56761           if( rc ) goto end_allocate_page;
   56762           if( closest<k-1 ){
   56763             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
   56764           }
   56765           put4byte(&aData[4], k-1);
   56766           noContent = !btreeGetHasContent(pBt, *pPgno) ? PAGER_GET_NOCONTENT : 0;
   56767           rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
   56768           if( rc==SQLITE_OK ){
   56769             rc = sqlite3PagerWrite((*ppPage)->pDbPage);
   56770             if( rc!=SQLITE_OK ){
   56771               releasePage(*ppPage);
   56772             }
   56773           }
   56774           searchList = 0;
   56775         }
   56776       }
   56777       releasePage(pPrevTrunk);
   56778       pPrevTrunk = 0;
   56779     }while( searchList );
   56780   }else{
   56781     /* There are no pages on the freelist, so append a new page to the
   56782     ** database image.
   56783     **
   56784     ** Normally, new pages allocated by this block can be requested from the
   56785     ** pager layer with the 'no-content' flag set. This prevents the pager
   56786     ** from trying to read the pages content from disk. However, if the
   56787     ** current transaction has already run one or more incremental-vacuum
   56788     ** steps, then the page we are about to allocate may contain content
   56789     ** that is required in the event of a rollback. In this case, do
   56790     ** not set the no-content flag. This causes the pager to load and journal
   56791     ** the current page content before overwriting it.
   56792     **
   56793     ** Note that the pager will not actually attempt to load or journal
   56794     ** content for any page that really does lie past the end of the database
   56795     ** file on disk. So the effects of disabling the no-content optimization
   56796     ** here are confined to those pages that lie between the end of the
   56797     ** database image and the end of the database file.
   56798     */
   56799     int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate)) ? PAGER_GET_NOCONTENT : 0;
   56800 
   56801     rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
   56802     if( rc ) return rc;
   56803     pBt->nPage++;
   56804     if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
   56805 
   56806 #ifndef SQLITE_OMIT_AUTOVACUUM
   56807     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
   56808       /* If *pPgno refers to a pointer-map page, allocate two new pages
   56809       ** at the end of the file instead of one. The first allocated page
   56810       ** becomes a new pointer-map page, the second is used by the caller.
   56811       */
   56812       MemPage *pPg = 0;
   56813       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
   56814       assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
   56815       rc = btreeGetPage(pBt, pBt->nPage, &pPg, bNoContent);
   56816       if( rc==SQLITE_OK ){
   56817         rc = sqlite3PagerWrite(pPg->pDbPage);
   56818         releasePage(pPg);
   56819       }
   56820       if( rc ) return rc;
   56821       pBt->nPage++;
   56822       if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
   56823     }
   56824 #endif
   56825     put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
   56826     *pPgno = pBt->nPage;
   56827 
   56828     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
   56829     rc = btreeGetPage(pBt, *pPgno, ppPage, bNoContent);
   56830     if( rc ) return rc;
   56831     rc = sqlite3PagerWrite((*ppPage)->pDbPage);
   56832     if( rc!=SQLITE_OK ){
   56833       releasePage(*ppPage);
   56834     }
   56835     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
   56836   }
   56837 
   56838   assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
   56839 
   56840 end_allocate_page:
   56841   releasePage(pTrunk);
   56842   releasePage(pPrevTrunk);
   56843   if( rc==SQLITE_OK ){
   56844     if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
   56845       releasePage(*ppPage);
   56846       *ppPage = 0;
   56847       return SQLITE_CORRUPT_BKPT;
   56848     }
   56849     (*ppPage)->isInit = 0;
   56850   }else{
   56851     *ppPage = 0;
   56852   }
   56853   assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
   56854   return rc;
   56855 }
   56856 
   56857 /*
   56858 ** This function is used to add page iPage to the database file free-list.
   56859 ** It is assumed that the page is not already a part of the free-list.
   56860 **
   56861 ** The value passed as the second argument to this function is optional.
   56862 ** If the caller happens to have a pointer to the MemPage object
   56863 ** corresponding to page iPage handy, it may pass it as the second value.
   56864 ** Otherwise, it may pass NULL.
   56865 **
   56866 ** If a pointer to a MemPage object is passed as the second argument,
   56867 ** its reference count is not altered by this function.
   56868 */
   56869 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
   56870   MemPage *pTrunk = 0;                /* Free-list trunk page */
   56871   Pgno iTrunk = 0;                    /* Page number of free-list trunk page */
   56872   MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
   56873   MemPage *pPage;                     /* Page being freed. May be NULL. */
   56874   int rc;                             /* Return Code */
   56875   int nFree;                          /* Initial number of pages on free-list */
   56876 
   56877   assert( sqlite3_mutex_held(pBt->mutex) );
   56878   assert( iPage>1 );
   56879   assert( !pMemPage || pMemPage->pgno==iPage );
   56880 
   56881   if( pMemPage ){
   56882     pPage = pMemPage;
   56883     sqlite3PagerRef(pPage->pDbPage);
   56884   }else{
   56885     pPage = btreePageLookup(pBt, iPage);
   56886   }
   56887 
   56888   /* Increment the free page count on pPage1 */
   56889   rc = sqlite3PagerWrite(pPage1->pDbPage);
   56890   if( rc ) goto freepage_out;
   56891   nFree = get4byte(&pPage1->aData[36]);
   56892   put4byte(&pPage1->aData[36], nFree+1);
   56893 
   56894   if( pBt->btsFlags & BTS_SECURE_DELETE ){
   56895     /* If the secure_delete option is enabled, then
   56896     ** always fully overwrite deleted information with zeros.
   56897     */
   56898     if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
   56899      ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
   56900     ){
   56901       goto freepage_out;
   56902     }
   56903     memset(pPage->aData, 0, pPage->pBt->pageSize);
   56904   }
   56905 
   56906   /* If the database supports auto-vacuum, write an entry in the pointer-map
   56907   ** to indicate that the page is free.
   56908   */
   56909   if( ISAUTOVACUUM ){
   56910     ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
   56911     if( rc ) goto freepage_out;
   56912   }
   56913 
   56914   /* Now manipulate the actual database free-list structure. There are two
   56915   ** possibilities. If the free-list is currently empty, or if the first
   56916   ** trunk page in the free-list is full, then this page will become a
   56917   ** new free-list trunk page. Otherwise, it will become a leaf of the
   56918   ** first trunk page in the current free-list. This block tests if it
   56919   ** is possible to add the page as a new free-list leaf.
   56920   */
   56921   if( nFree!=0 ){
   56922     u32 nLeaf;                /* Initial number of leaf cells on trunk page */
   56923 
   56924     iTrunk = get4byte(&pPage1->aData[32]);
   56925     rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
   56926     if( rc!=SQLITE_OK ){
   56927       goto freepage_out;
   56928     }
   56929 
   56930     nLeaf = get4byte(&pTrunk->aData[4]);
   56931     assert( pBt->usableSize>32 );
   56932     if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
   56933       rc = SQLITE_CORRUPT_BKPT;
   56934       goto freepage_out;
   56935     }
   56936     if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
   56937       /* In this case there is room on the trunk page to insert the page
   56938       ** being freed as a new leaf.
   56939       **
   56940       ** Note that the trunk page is not really full until it contains
   56941       ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
   56942       ** coded.  But due to a coding error in versions of SQLite prior to
   56943       ** 3.6.0, databases with freelist trunk pages holding more than
   56944       ** usableSize/4 - 8 entries will be reported as corrupt.  In order
   56945       ** to maintain backwards compatibility with older versions of SQLite,
   56946       ** we will continue to restrict the number of entries to usableSize/4 - 8
   56947       ** for now.  At some point in the future (once everyone has upgraded
   56948       ** to 3.6.0 or later) we should consider fixing the conditional above
   56949       ** to read "usableSize/4-2" instead of "usableSize/4-8".
   56950       */
   56951       rc = sqlite3PagerWrite(pTrunk->pDbPage);
   56952       if( rc==SQLITE_OK ){
   56953         put4byte(&pTrunk->aData[4], nLeaf+1);
   56954         put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
   56955         if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
   56956           sqlite3PagerDontWrite(pPage->pDbPage);
   56957         }
   56958         rc = btreeSetHasContent(pBt, iPage);
   56959       }
   56960       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
   56961       goto freepage_out;
   56962     }
   56963   }
   56964 
   56965   /* If control flows to this point, then it was not possible to add the
   56966   ** the page being freed as a leaf page of the first trunk in the free-list.
   56967   ** Possibly because the free-list is empty, or possibly because the
   56968   ** first trunk in the free-list is full. Either way, the page being freed
   56969   ** will become the new first trunk page in the free-list.
   56970   */
   56971   if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
   56972     goto freepage_out;
   56973   }
   56974   rc = sqlite3PagerWrite(pPage->pDbPage);
   56975   if( rc!=SQLITE_OK ){
   56976     goto freepage_out;
   56977   }
   56978   put4byte(pPage->aData, iTrunk);
   56979   put4byte(&pPage->aData[4], 0);
   56980   put4byte(&pPage1->aData[32], iPage);
   56981   TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
   56982 
   56983 freepage_out:
   56984   if( pPage ){
   56985     pPage->isInit = 0;
   56986   }
   56987   releasePage(pPage);
   56988   releasePage(pTrunk);
   56989   return rc;
   56990 }
   56991 static void freePage(MemPage *pPage, int *pRC){
   56992   if( (*pRC)==SQLITE_OK ){
   56993     *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
   56994   }
   56995 }
   56996 
   56997 /*
   56998 ** Free any overflow pages associated with the given Cell.
   56999 */
   57000 static int clearCell(MemPage *pPage, unsigned char *pCell){
   57001   BtShared *pBt = pPage->pBt;
   57002   CellInfo info;
   57003   Pgno ovflPgno;
   57004   int rc;
   57005   int nOvfl;
   57006   u32 ovflPageSize;
   57007 
   57008   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   57009   btreeParseCellPtr(pPage, pCell, &info);
   57010   if( info.iOverflow==0 ){
   57011     return SQLITE_OK;  /* No overflow pages. Return without doing anything */
   57012   }
   57013   if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
   57014     return SQLITE_CORRUPT_BKPT;  /* Cell extends past end of page */
   57015   }
   57016   ovflPgno = get4byte(&pCell[info.iOverflow]);
   57017   assert( pBt->usableSize > 4 );
   57018   ovflPageSize = pBt->usableSize - 4;
   57019   nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
   57020   assert( ovflPgno==0 || nOvfl>0 );
   57021   while( nOvfl-- ){
   57022     Pgno iNext = 0;
   57023     MemPage *pOvfl = 0;
   57024     if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
   57025       /* 0 is not a legal page number and page 1 cannot be an
   57026       ** overflow page. Therefore if ovflPgno<2 or past the end of the
   57027       ** file the database must be corrupt. */
   57028       return SQLITE_CORRUPT_BKPT;
   57029     }
   57030     if( nOvfl ){
   57031       rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
   57032       if( rc ) return rc;
   57033     }
   57034 
   57035     if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
   57036      && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
   57037     ){
   57038       /* There is no reason any cursor should have an outstanding reference
   57039       ** to an overflow page belonging to a cell that is being deleted/updated.
   57040       ** So if there exists more than one reference to this page, then it
   57041       ** must not really be an overflow page and the database must be corrupt.
   57042       ** It is helpful to detect this before calling freePage2(), as
   57043       ** freePage2() may zero the page contents if secure-delete mode is
   57044       ** enabled. If this 'overflow' page happens to be a page that the
   57045       ** caller is iterating through or using in some other way, this
   57046       ** can be problematic.
   57047       */
   57048       rc = SQLITE_CORRUPT_BKPT;
   57049     }else{
   57050       rc = freePage2(pBt, pOvfl, ovflPgno);
   57051     }
   57052 
   57053     if( pOvfl ){
   57054       sqlite3PagerUnref(pOvfl->pDbPage);
   57055     }
   57056     if( rc ) return rc;
   57057     ovflPgno = iNext;
   57058   }
   57059   return SQLITE_OK;
   57060 }
   57061 
   57062 /*
   57063 ** Create the byte sequence used to represent a cell on page pPage
   57064 ** and write that byte sequence into pCell[].  Overflow pages are
   57065 ** allocated and filled in as necessary.  The calling procedure
   57066 ** is responsible for making sure sufficient space has been allocated
   57067 ** for pCell[].
   57068 **
   57069 ** Note that pCell does not necessary need to point to the pPage->aData
   57070 ** area.  pCell might point to some temporary storage.  The cell will
   57071 ** be constructed in this temporary area then copied into pPage->aData
   57072 ** later.
   57073 */
   57074 static int fillInCell(
   57075   MemPage *pPage,                /* The page that contains the cell */
   57076   unsigned char *pCell,          /* Complete text of the cell */
   57077   const void *pKey, i64 nKey,    /* The key */
   57078   const void *pData,int nData,   /* The data */
   57079   int nZero,                     /* Extra zero bytes to append to pData */
   57080   int *pnSize                    /* Write cell size here */
   57081 ){
   57082   int nPayload;
   57083   const u8 *pSrc;
   57084   int nSrc, n, rc;
   57085   int spaceLeft;
   57086   MemPage *pOvfl = 0;
   57087   MemPage *pToRelease = 0;
   57088   unsigned char *pPrior;
   57089   unsigned char *pPayload;
   57090   BtShared *pBt = pPage->pBt;
   57091   Pgno pgnoOvfl = 0;
   57092   int nHeader;
   57093   CellInfo info;
   57094 
   57095   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   57096 
   57097   /* pPage is not necessarily writeable since pCell might be auxiliary
   57098   ** buffer space that is separate from the pPage buffer area */
   57099   assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
   57100             || sqlite3PagerIswriteable(pPage->pDbPage) );
   57101 
   57102   /* Fill in the header. */
   57103   nHeader = 0;
   57104   if( !pPage->leaf ){
   57105     nHeader += 4;
   57106   }
   57107   if( pPage->hasData ){
   57108     nHeader += putVarint32(&pCell[nHeader], nData+nZero);
   57109   }else{
   57110     nData = nZero = 0;
   57111   }
   57112   nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
   57113   btreeParseCellPtr(pPage, pCell, &info);
   57114   assert( info.nHeader==nHeader );
   57115   assert( info.nKey==nKey );
   57116   assert( info.nData==(u32)(nData+nZero) );
   57117 
   57118   /* Fill in the payload */
   57119   nPayload = nData + nZero;
   57120   if( pPage->intKey ){
   57121     pSrc = pData;
   57122     nSrc = nData;
   57123     nData = 0;
   57124   }else{
   57125     if( NEVER(nKey>0x7fffffff || pKey==0) ){
   57126       return SQLITE_CORRUPT_BKPT;
   57127     }
   57128     nPayload += (int)nKey;
   57129     pSrc = pKey;
   57130     nSrc = (int)nKey;
   57131   }
   57132   *pnSize = info.nSize;
   57133   spaceLeft = info.nLocal;
   57134   pPayload = &pCell[nHeader];
   57135   pPrior = &pCell[info.iOverflow];
   57136 
   57137   while( nPayload>0 ){
   57138     if( spaceLeft==0 ){
   57139 #ifndef SQLITE_OMIT_AUTOVACUUM
   57140       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
   57141       if( pBt->autoVacuum ){
   57142         do{
   57143           pgnoOvfl++;
   57144         } while(
   57145           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
   57146         );
   57147       }
   57148 #endif
   57149       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
   57150 #ifndef SQLITE_OMIT_AUTOVACUUM
   57151       /* If the database supports auto-vacuum, and the second or subsequent
   57152       ** overflow page is being allocated, add an entry to the pointer-map
   57153       ** for that page now.
   57154       **
   57155       ** If this is the first overflow page, then write a partial entry
   57156       ** to the pointer-map. If we write nothing to this pointer-map slot,
   57157       ** then the optimistic overflow chain processing in clearCell()
   57158       ** may misinterpret the uninitialized values and delete the
   57159       ** wrong pages from the database.
   57160       */
   57161       if( pBt->autoVacuum && rc==SQLITE_OK ){
   57162         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
   57163         ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
   57164         if( rc ){
   57165           releasePage(pOvfl);
   57166         }
   57167       }
   57168 #endif
   57169       if( rc ){
   57170         releasePage(pToRelease);
   57171         return rc;
   57172       }
   57173 
   57174       /* If pToRelease is not zero than pPrior points into the data area
   57175       ** of pToRelease.  Make sure pToRelease is still writeable. */
   57176       assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
   57177 
   57178       /* If pPrior is part of the data area of pPage, then make sure pPage
   57179       ** is still writeable */
   57180       assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
   57181             || sqlite3PagerIswriteable(pPage->pDbPage) );
   57182 
   57183       put4byte(pPrior, pgnoOvfl);
   57184       releasePage(pToRelease);
   57185       pToRelease = pOvfl;
   57186       pPrior = pOvfl->aData;
   57187       put4byte(pPrior, 0);
   57188       pPayload = &pOvfl->aData[4];
   57189       spaceLeft = pBt->usableSize - 4;
   57190     }
   57191     n = nPayload;
   57192     if( n>spaceLeft ) n = spaceLeft;
   57193 
   57194     /* If pToRelease is not zero than pPayload points into the data area
   57195     ** of pToRelease.  Make sure pToRelease is still writeable. */
   57196     assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
   57197 
   57198     /* If pPayload is part of the data area of pPage, then make sure pPage
   57199     ** is still writeable */
   57200     assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
   57201             || sqlite3PagerIswriteable(pPage->pDbPage) );
   57202 
   57203     if( nSrc>0 ){
   57204       if( n>nSrc ) n = nSrc;
   57205       assert( pSrc );
   57206       memcpy(pPayload, pSrc, n);
   57207     }else{
   57208       memset(pPayload, 0, n);
   57209     }
   57210     nPayload -= n;
   57211     pPayload += n;
   57212     pSrc += n;
   57213     nSrc -= n;
   57214     spaceLeft -= n;
   57215     if( nSrc==0 ){
   57216       nSrc = nData;
   57217       pSrc = pData;
   57218     }
   57219   }
   57220   releasePage(pToRelease);
   57221   return SQLITE_OK;
   57222 }
   57223 
   57224 /*
   57225 ** Remove the i-th cell from pPage.  This routine effects pPage only.
   57226 ** The cell content is not freed or deallocated.  It is assumed that
   57227 ** the cell content has been copied someplace else.  This routine just
   57228 ** removes the reference to the cell from pPage.
   57229 **
   57230 ** "sz" must be the number of bytes in the cell.
   57231 */
   57232 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
   57233   u32 pc;         /* Offset to cell content of cell being deleted */
   57234   u8 *data;       /* pPage->aData */
   57235   u8 *ptr;        /* Used to move bytes around within data[] */
   57236   int rc;         /* The return code */
   57237   int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
   57238 
   57239   if( *pRC ) return;
   57240 
   57241   assert( idx>=0 && idx<pPage->nCell );
   57242   assert( sz==cellSize(pPage, idx) );
   57243   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   57244   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   57245   data = pPage->aData;
   57246   ptr = &pPage->aCellIdx[2*idx];
   57247   pc = get2byte(ptr);
   57248   hdr = pPage->hdrOffset;
   57249   testcase( pc==get2byte(&data[hdr+5]) );
   57250   testcase( pc+sz==pPage->pBt->usableSize );
   57251   if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
   57252     *pRC = SQLITE_CORRUPT_BKPT;
   57253     return;
   57254   }
   57255   rc = freeSpace(pPage, pc, sz);
   57256   if( rc ){
   57257     *pRC = rc;
   57258     return;
   57259   }
   57260   pPage->nCell--;
   57261   memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
   57262   put2byte(&data[hdr+3], pPage->nCell);
   57263   pPage->nFree += 2;
   57264 }
   57265 
   57266 /*
   57267 ** Insert a new cell on pPage at cell index "i".  pCell points to the
   57268 ** content of the cell.
   57269 **
   57270 ** If the cell content will fit on the page, then put it there.  If it
   57271 ** will not fit, then make a copy of the cell content into pTemp if
   57272 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
   57273 ** in pPage->apOvfl[] and make it point to the cell content (either
   57274 ** in pTemp or the original pCell) and also record its index.
   57275 ** Allocating a new entry in pPage->aCell[] implies that
   57276 ** pPage->nOverflow is incremented.
   57277 **
   57278 ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
   57279 ** cell. The caller will overwrite them after this function returns. If
   57280 ** nSkip is non-zero, then pCell may not point to an invalid memory location
   57281 ** (but pCell+nSkip is always valid).
   57282 */
   57283 static void insertCell(
   57284   MemPage *pPage,   /* Page into which we are copying */
   57285   int i,            /* New cell becomes the i-th cell of the page */
   57286   u8 *pCell,        /* Content of the new cell */
   57287   int sz,           /* Bytes of content in pCell */
   57288   u8 *pTemp,        /* Temp storage space for pCell, if needed */
   57289   Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
   57290   int *pRC          /* Read and write return code from here */
   57291 ){
   57292   int idx = 0;      /* Where to write new cell content in data[] */
   57293   int j;            /* Loop counter */
   57294   int end;          /* First byte past the last cell pointer in data[] */
   57295   int ins;          /* Index in data[] where new cell pointer is inserted */
   57296   int cellOffset;   /* Address of first cell pointer in data[] */
   57297   u8 *data;         /* The content of the whole page */
   57298   int nSkip = (iChild ? 4 : 0);
   57299 
   57300   if( *pRC ) return;
   57301 
   57302   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
   57303   assert( MX_CELL(pPage->pBt)<=10921 );
   57304   assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
   57305   assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
   57306   assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
   57307   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   57308   /* The cell should normally be sized correctly.  However, when moving a
   57309   ** malformed cell from a leaf page to an interior page, if the cell size
   57310   ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
   57311   ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
   57312   ** the term after the || in the following assert(). */
   57313   assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
   57314   if( pPage->nOverflow || sz+2>pPage->nFree ){
   57315     if( pTemp ){
   57316       memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
   57317       pCell = pTemp;
   57318     }
   57319     if( iChild ){
   57320       put4byte(pCell, iChild);
   57321     }
   57322     j = pPage->nOverflow++;
   57323     assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
   57324     pPage->apOvfl[j] = pCell;
   57325     pPage->aiOvfl[j] = (u16)i;
   57326   }else{
   57327     int rc = sqlite3PagerWrite(pPage->pDbPage);
   57328     if( rc!=SQLITE_OK ){
   57329       *pRC = rc;
   57330       return;
   57331     }
   57332     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   57333     data = pPage->aData;
   57334     cellOffset = pPage->cellOffset;
   57335     end = cellOffset + 2*pPage->nCell;
   57336     ins = cellOffset + 2*i;
   57337     rc = allocateSpace(pPage, sz, &idx);
   57338     if( rc ){ *pRC = rc; return; }
   57339     /* The allocateSpace() routine guarantees the following two properties
   57340     ** if it returns success */
   57341     assert( idx >= end+2 );
   57342     assert( idx+sz <= (int)pPage->pBt->usableSize );
   57343     pPage->nCell++;
   57344     pPage->nFree -= (u16)(2 + sz);
   57345     memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
   57346     if( iChild ){
   57347       put4byte(&data[idx], iChild);
   57348     }
   57349     memmove(&data[ins+2], &data[ins], end-ins);
   57350     put2byte(&data[ins], idx);
   57351     put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
   57352 #ifndef SQLITE_OMIT_AUTOVACUUM
   57353     if( pPage->pBt->autoVacuum ){
   57354       /* The cell may contain a pointer to an overflow page. If so, write
   57355       ** the entry for the overflow page into the pointer map.
   57356       */
   57357       ptrmapPutOvflPtr(pPage, pCell, pRC);
   57358     }
   57359 #endif
   57360   }
   57361 }
   57362 
   57363 /*
   57364 ** Add a list of cells to a page.  The page should be initially empty.
   57365 ** The cells are guaranteed to fit on the page.
   57366 */
   57367 static void assemblePage(
   57368   MemPage *pPage,   /* The page to be assemblied */
   57369   int nCell,        /* The number of cells to add to this page */
   57370   u8 **apCell,      /* Pointers to cell bodies */
   57371   u16 *aSize        /* Sizes of the cells */
   57372 ){
   57373   int i;            /* Loop counter */
   57374   u8 *pCellptr;     /* Address of next cell pointer */
   57375   int cellbody;     /* Address of next cell body */
   57376   u8 * const data = pPage->aData;             /* Pointer to data for pPage */
   57377   const int hdr = pPage->hdrOffset;           /* Offset of header on pPage */
   57378   const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
   57379 
   57380   assert( pPage->nOverflow==0 );
   57381   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   57382   assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
   57383             && (int)MX_CELL(pPage->pBt)<=10921);
   57384   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   57385 
   57386   /* Check that the page has just been zeroed by zeroPage() */
   57387   assert( pPage->nCell==0 );
   57388   assert( get2byteNotZero(&data[hdr+5])==nUsable );
   57389 
   57390   pCellptr = &pPage->aCellIdx[nCell*2];
   57391   cellbody = nUsable;
   57392   for(i=nCell-1; i>=0; i--){
   57393     u16 sz = aSize[i];
   57394     pCellptr -= 2;
   57395     cellbody -= sz;
   57396     put2byte(pCellptr, cellbody);
   57397     memcpy(&data[cellbody], apCell[i], sz);
   57398   }
   57399   put2byte(&data[hdr+3], nCell);
   57400   put2byte(&data[hdr+5], cellbody);
   57401   pPage->nFree -= (nCell*2 + nUsable - cellbody);
   57402   pPage->nCell = (u16)nCell;
   57403 }
   57404 
   57405 /*
   57406 ** The following parameters determine how many adjacent pages get involved
   57407 ** in a balancing operation.  NN is the number of neighbors on either side
   57408 ** of the page that participate in the balancing operation.  NB is the
   57409 ** total number of pages that participate, including the target page and
   57410 ** NN neighbors on either side.
   57411 **
   57412 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
   57413 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
   57414 ** in exchange for a larger degradation in INSERT and UPDATE performance.
   57415 ** The value of NN appears to give the best results overall.
   57416 */
   57417 #define NN 1             /* Number of neighbors on either side of pPage */
   57418 #define NB (NN*2+1)      /* Total pages involved in the balance */
   57419 
   57420 
   57421 #ifndef SQLITE_OMIT_QUICKBALANCE
   57422 /*
   57423 ** This version of balance() handles the common special case where
   57424 ** a new entry is being inserted on the extreme right-end of the
   57425 ** tree, in other words, when the new entry will become the largest
   57426 ** entry in the tree.
   57427 **
   57428 ** Instead of trying to balance the 3 right-most leaf pages, just add
   57429 ** a new page to the right-hand side and put the one new entry in
   57430 ** that page.  This leaves the right side of the tree somewhat
   57431 ** unbalanced.  But odds are that we will be inserting new entries
   57432 ** at the end soon afterwards so the nearly empty page will quickly
   57433 ** fill up.  On average.
   57434 **
   57435 ** pPage is the leaf page which is the right-most page in the tree.
   57436 ** pParent is its parent.  pPage must have a single overflow entry
   57437 ** which is also the right-most entry on the page.
   57438 **
   57439 ** The pSpace buffer is used to store a temporary copy of the divider
   57440 ** cell that will be inserted into pParent. Such a cell consists of a 4
   57441 ** byte page number followed by a variable length integer. In other
   57442 ** words, at most 13 bytes. Hence the pSpace buffer must be at
   57443 ** least 13 bytes in size.
   57444 */
   57445 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
   57446   BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
   57447   MemPage *pNew;                       /* Newly allocated page */
   57448   int rc;                              /* Return Code */
   57449   Pgno pgnoNew;                        /* Page number of pNew */
   57450 
   57451   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   57452   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
   57453   assert( pPage->nOverflow==1 );
   57454 
   57455   /* This error condition is now caught prior to reaching this function */
   57456   if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT;
   57457 
   57458   /* Allocate a new page. This page will become the right-sibling of
   57459   ** pPage. Make the parent page writable, so that the new divider cell
   57460   ** may be inserted. If both these operations are successful, proceed.
   57461   */
   57462   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
   57463 
   57464   if( rc==SQLITE_OK ){
   57465 
   57466     u8 *pOut = &pSpace[4];
   57467     u8 *pCell = pPage->apOvfl[0];
   57468     u16 szCell = cellSizePtr(pPage, pCell);
   57469     u8 *pStop;
   57470 
   57471     assert( sqlite3PagerIswriteable(pNew->pDbPage) );
   57472     assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
   57473     zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
   57474     assemblePage(pNew, 1, &pCell, &szCell);
   57475 
   57476     /* If this is an auto-vacuum database, update the pointer map
   57477     ** with entries for the new page, and any pointer from the
   57478     ** cell on the page to an overflow page. If either of these
   57479     ** operations fails, the return code is set, but the contents
   57480     ** of the parent page are still manipulated by thh code below.
   57481     ** That is Ok, at this point the parent page is guaranteed to
   57482     ** be marked as dirty. Returning an error code will cause a
   57483     ** rollback, undoing any changes made to the parent page.
   57484     */
   57485     if( ISAUTOVACUUM ){
   57486       ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
   57487       if( szCell>pNew->minLocal ){
   57488         ptrmapPutOvflPtr(pNew, pCell, &rc);
   57489       }
   57490     }
   57491 
   57492     /* Create a divider cell to insert into pParent. The divider cell
   57493     ** consists of a 4-byte page number (the page number of pPage) and
   57494     ** a variable length key value (which must be the same value as the
   57495     ** largest key on pPage).
   57496     **
   57497     ** To find the largest key value on pPage, first find the right-most
   57498     ** cell on pPage. The first two fields of this cell are the
   57499     ** record-length (a variable length integer at most 32-bits in size)
   57500     ** and the key value (a variable length integer, may have any value).
   57501     ** The first of the while(...) loops below skips over the record-length
   57502     ** field. The second while(...) loop copies the key value from the
   57503     ** cell on pPage into the pSpace buffer.
   57504     */
   57505     pCell = findCell(pPage, pPage->nCell-1);
   57506     pStop = &pCell[9];
   57507     while( (*(pCell++)&0x80) && pCell<pStop );
   57508     pStop = &pCell[9];
   57509     while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
   57510 
   57511     /* Insert the new divider cell into pParent. */
   57512     insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
   57513                0, pPage->pgno, &rc);
   57514 
   57515     /* Set the right-child pointer of pParent to point to the new page. */
   57516     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
   57517 
   57518     /* Release the reference to the new page. */
   57519     releasePage(pNew);
   57520   }
   57521 
   57522   return rc;
   57523 }
   57524 #endif /* SQLITE_OMIT_QUICKBALANCE */
   57525 
   57526 #if 0
   57527 /*
   57528 ** This function does not contribute anything to the operation of SQLite.
   57529 ** it is sometimes activated temporarily while debugging code responsible
   57530 ** for setting pointer-map entries.
   57531 */
   57532 static int ptrmapCheckPages(MemPage **apPage, int nPage){
   57533   int i, j;
   57534   for(i=0; i<nPage; i++){
   57535     Pgno n;
   57536     u8 e;
   57537     MemPage *pPage = apPage[i];
   57538     BtShared *pBt = pPage->pBt;
   57539     assert( pPage->isInit );
   57540 
   57541     for(j=0; j<pPage->nCell; j++){
   57542       CellInfo info;
   57543       u8 *z;
   57544 
   57545       z = findCell(pPage, j);
   57546       btreeParseCellPtr(pPage, z, &info);
   57547       if( info.iOverflow ){
   57548         Pgno ovfl = get4byte(&z[info.iOverflow]);
   57549         ptrmapGet(pBt, ovfl, &e, &n);
   57550         assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
   57551       }
   57552       if( !pPage->leaf ){
   57553         Pgno child = get4byte(z);
   57554         ptrmapGet(pBt, child, &e, &n);
   57555         assert( n==pPage->pgno && e==PTRMAP_BTREE );
   57556       }
   57557     }
   57558     if( !pPage->leaf ){
   57559       Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
   57560       ptrmapGet(pBt, child, &e, &n);
   57561       assert( n==pPage->pgno && e==PTRMAP_BTREE );
   57562     }
   57563   }
   57564   return 1;
   57565 }
   57566 #endif
   57567 
   57568 /*
   57569 ** This function is used to copy the contents of the b-tree node stored
   57570 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
   57571 ** the pointer-map entries for each child page are updated so that the
   57572 ** parent page stored in the pointer map is page pTo. If pFrom contained
   57573 ** any cells with overflow page pointers, then the corresponding pointer
   57574 ** map entries are also updated so that the parent page is page pTo.
   57575 **
   57576 ** If pFrom is currently carrying any overflow cells (entries in the
   57577 ** MemPage.apOvfl[] array), they are not copied to pTo.
   57578 **
   57579 ** Before returning, page pTo is reinitialized using btreeInitPage().
   57580 **
   57581 ** The performance of this function is not critical. It is only used by
   57582 ** the balance_shallower() and balance_deeper() procedures, neither of
   57583 ** which are called often under normal circumstances.
   57584 */
   57585 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
   57586   if( (*pRC)==SQLITE_OK ){
   57587     BtShared * const pBt = pFrom->pBt;
   57588     u8 * const aFrom = pFrom->aData;
   57589     u8 * const aTo = pTo->aData;
   57590     int const iFromHdr = pFrom->hdrOffset;
   57591     int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
   57592     int rc;
   57593     int iData;
   57594 
   57595 
   57596     assert( pFrom->isInit );
   57597     assert( pFrom->nFree>=iToHdr );
   57598     assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
   57599 
   57600     /* Copy the b-tree node content from page pFrom to page pTo. */
   57601     iData = get2byte(&aFrom[iFromHdr+5]);
   57602     memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
   57603     memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
   57604 
   57605     /* Reinitialize page pTo so that the contents of the MemPage structure
   57606     ** match the new data. The initialization of pTo can actually fail under
   57607     ** fairly obscure circumstances, even though it is a copy of initialized
   57608     ** page pFrom.
   57609     */
   57610     pTo->isInit = 0;
   57611     rc = btreeInitPage(pTo);
   57612     if( rc!=SQLITE_OK ){
   57613       *pRC = rc;
   57614       return;
   57615     }
   57616 
   57617     /* If this is an auto-vacuum database, update the pointer-map entries
   57618     ** for any b-tree or overflow pages that pTo now contains the pointers to.
   57619     */
   57620     if( ISAUTOVACUUM ){
   57621       *pRC = setChildPtrmaps(pTo);
   57622     }
   57623   }
   57624 }
   57625 
   57626 /*
   57627 ** This routine redistributes cells on the iParentIdx'th child of pParent
   57628 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
   57629 ** same amount of free space. Usually a single sibling on either side of the
   57630 ** page are used in the balancing, though both siblings might come from one
   57631 ** side if the page is the first or last child of its parent. If the page
   57632 ** has fewer than 2 siblings (something which can only happen if the page
   57633 ** is a root page or a child of a root page) then all available siblings
   57634 ** participate in the balancing.
   57635 **
   57636 ** The number of siblings of the page might be increased or decreased by
   57637 ** one or two in an effort to keep pages nearly full but not over full.
   57638 **
   57639 ** Note that when this routine is called, some of the cells on the page
   57640 ** might not actually be stored in MemPage.aData[]. This can happen
   57641 ** if the page is overfull. This routine ensures that all cells allocated
   57642 ** to the page and its siblings fit into MemPage.aData[] before returning.
   57643 **
   57644 ** In the course of balancing the page and its siblings, cells may be
   57645 ** inserted into or removed from the parent page (pParent). Doing so
   57646 ** may cause the parent page to become overfull or underfull. If this
   57647 ** happens, it is the responsibility of the caller to invoke the correct
   57648 ** balancing routine to fix this problem (see the balance() routine).
   57649 **
   57650 ** If this routine fails for any reason, it might leave the database
   57651 ** in a corrupted state. So if this routine fails, the database should
   57652 ** be rolled back.
   57653 **
   57654 ** The third argument to this function, aOvflSpace, is a pointer to a
   57655 ** buffer big enough to hold one page. If while inserting cells into the parent
   57656 ** page (pParent) the parent page becomes overfull, this buffer is
   57657 ** used to store the parent's overflow cells. Because this function inserts
   57658 ** a maximum of four divider cells into the parent page, and the maximum
   57659 ** size of a cell stored within an internal node is always less than 1/4
   57660 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
   57661 ** enough for all overflow cells.
   57662 **
   57663 ** If aOvflSpace is set to a null pointer, this function returns
   57664 ** SQLITE_NOMEM.
   57665 */
   57666 #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
   57667 #pragma optimize("", off)
   57668 #endif
   57669 static int balance_nonroot(
   57670   MemPage *pParent,               /* Parent page of siblings being balanced */
   57671   int iParentIdx,                 /* Index of "the page" in pParent */
   57672   u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
   57673   int isRoot,                     /* True if pParent is a root-page */
   57674   int bBulk                       /* True if this call is part of a bulk load */
   57675 ){
   57676   BtShared *pBt;               /* The whole database */
   57677   int nCell = 0;               /* Number of cells in apCell[] */
   57678   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
   57679   int nNew = 0;                /* Number of pages in apNew[] */
   57680   int nOld;                    /* Number of pages in apOld[] */
   57681   int i, j, k;                 /* Loop counters */
   57682   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
   57683   int rc = SQLITE_OK;          /* The return code */
   57684   u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
   57685   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
   57686   int usableSpace;             /* Bytes in pPage beyond the header */
   57687   int pageFlags;               /* Value of pPage->aData[0] */
   57688   int subtotal;                /* Subtotal of bytes in cells on one page */
   57689   int iSpace1 = 0;             /* First unused byte of aSpace1[] */
   57690   int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
   57691   int szScratch;               /* Size of scratch memory requested */
   57692   MemPage *apOld[NB];          /* pPage and up to two siblings */
   57693   MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
   57694   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
   57695   u8 *pRight;                  /* Location in parent of right-sibling pointer */
   57696   u8 *apDiv[NB-1];             /* Divider cells in pParent */
   57697   int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
   57698   int szNew[NB+2];             /* Combined size of cells place on i-th page */
   57699   u8 **apCell = 0;             /* All cells begin balanced */
   57700   u16 *szCell;                 /* Local size of all cells in apCell[] */
   57701   u8 *aSpace1;                 /* Space for copies of dividers cells */
   57702   Pgno pgno;                   /* Temp var to store a page number in */
   57703 
   57704   pBt = pParent->pBt;
   57705   assert( sqlite3_mutex_held(pBt->mutex) );
   57706   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
   57707 
   57708 #if 0
   57709   TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
   57710 #endif
   57711 
   57712   /* At this point pParent may have at most one overflow cell. And if
   57713   ** this overflow cell is present, it must be the cell with
   57714   ** index iParentIdx. This scenario comes about when this function
   57715   ** is called (indirectly) from sqlite3BtreeDelete().
   57716   */
   57717   assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
   57718   assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
   57719 
   57720   if( !aOvflSpace ){
   57721     return SQLITE_NOMEM;
   57722   }
   57723 
   57724   /* Find the sibling pages to balance. Also locate the cells in pParent
   57725   ** that divide the siblings. An attempt is made to find NN siblings on
   57726   ** either side of pPage. More siblings are taken from one side, however,
   57727   ** if there are fewer than NN siblings on the other side. If pParent
   57728   ** has NB or fewer children then all children of pParent are taken.
   57729   **
   57730   ** This loop also drops the divider cells from the parent page. This
   57731   ** way, the remainder of the function does not have to deal with any
   57732   ** overflow cells in the parent page, since if any existed they will
   57733   ** have already been removed.
   57734   */
   57735   i = pParent->nOverflow + pParent->nCell;
   57736   if( i<2 ){
   57737     nxDiv = 0;
   57738   }else{
   57739     assert( bBulk==0 || bBulk==1 );
   57740     if( iParentIdx==0 ){
   57741       nxDiv = 0;
   57742     }else if( iParentIdx==i ){
   57743       nxDiv = i-2+bBulk;
   57744     }else{
   57745       assert( bBulk==0 );
   57746       nxDiv = iParentIdx-1;
   57747     }
   57748     i = 2-bBulk;
   57749   }
   57750   nOld = i+1;
   57751   if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
   57752     pRight = &pParent->aData[pParent->hdrOffset+8];
   57753   }else{
   57754     pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
   57755   }
   57756   pgno = get4byte(pRight);
   57757   while( 1 ){
   57758     rc = getAndInitPage(pBt, pgno, &apOld[i], 0);
   57759     if( rc ){
   57760       memset(apOld, 0, (i+1)*sizeof(MemPage*));
   57761       goto balance_cleanup;
   57762     }
   57763     nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
   57764     if( (i--)==0 ) break;
   57765 
   57766     if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
   57767       apDiv[i] = pParent->apOvfl[0];
   57768       pgno = get4byte(apDiv[i]);
   57769       szNew[i] = cellSizePtr(pParent, apDiv[i]);
   57770       pParent->nOverflow = 0;
   57771     }else{
   57772       apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
   57773       pgno = get4byte(apDiv[i]);
   57774       szNew[i] = cellSizePtr(pParent, apDiv[i]);
   57775 
   57776       /* Drop the cell from the parent page. apDiv[i] still points to
   57777       ** the cell within the parent, even though it has been dropped.
   57778       ** This is safe because dropping a cell only overwrites the first
   57779       ** four bytes of it, and this function does not need the first
   57780       ** four bytes of the divider cell. So the pointer is safe to use
   57781       ** later on.
   57782       **
   57783       ** But not if we are in secure-delete mode. In secure-delete mode,
   57784       ** the dropCell() routine will overwrite the entire cell with zeroes.
   57785       ** In this case, temporarily copy the cell into the aOvflSpace[]
   57786       ** buffer. It will be copied out again as soon as the aSpace[] buffer
   57787       ** is allocated.  */
   57788       if( pBt->btsFlags & BTS_SECURE_DELETE ){
   57789         int iOff;
   57790 
   57791         iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
   57792         if( (iOff+szNew[i])>(int)pBt->usableSize ){
   57793           rc = SQLITE_CORRUPT_BKPT;
   57794           memset(apOld, 0, (i+1)*sizeof(MemPage*));
   57795           goto balance_cleanup;
   57796         }else{
   57797           memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
   57798           apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
   57799         }
   57800       }
   57801       dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
   57802     }
   57803   }
   57804 
   57805   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
   57806   ** alignment */
   57807   nMaxCells = (nMaxCells + 3)&~3;
   57808 
   57809   /*
   57810   ** Allocate space for memory structures
   57811   */
   57812   k = pBt->pageSize + ROUND8(sizeof(MemPage));
   57813   szScratch =
   57814        nMaxCells*sizeof(u8*)                       /* apCell */
   57815      + nMaxCells*sizeof(u16)                       /* szCell */
   57816      + pBt->pageSize                               /* aSpace1 */
   57817      + k*nOld;                                     /* Page copies (apCopy) */
   57818   apCell = sqlite3ScratchMalloc( szScratch );
   57819   if( apCell==0 ){
   57820     rc = SQLITE_NOMEM;
   57821     goto balance_cleanup;
   57822   }
   57823   szCell = (u16*)&apCell[nMaxCells];
   57824   aSpace1 = (u8*)&szCell[nMaxCells];
   57825   assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
   57826 
   57827   /*
   57828   ** Load pointers to all cells on sibling pages and the divider cells
   57829   ** into the local apCell[] array.  Make copies of the divider cells
   57830   ** into space obtained from aSpace1[] and remove the divider cells
   57831   ** from pParent.
   57832   **
   57833   ** If the siblings are on leaf pages, then the child pointers of the
   57834   ** divider cells are stripped from the cells before they are copied
   57835   ** into aSpace1[].  In this way, all cells in apCell[] are without
   57836   ** child pointers.  If siblings are not leaves, then all cell in
   57837   ** apCell[] include child pointers.  Either way, all cells in apCell[]
   57838   ** are alike.
   57839   **
   57840   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
   57841   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
   57842   */
   57843   leafCorrection = apOld[0]->leaf*4;
   57844   leafData = apOld[0]->hasData;
   57845   for(i=0; i<nOld; i++){
   57846     int limit;
   57847 
   57848     /* Before doing anything else, take a copy of the i'th original sibling
   57849     ** The rest of this function will use data from the copies rather
   57850     ** that the original pages since the original pages will be in the
   57851     ** process of being overwritten.  */
   57852     MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
   57853     memcpy(pOld, apOld[i], sizeof(MemPage));
   57854     pOld->aData = (void*)&pOld[1];
   57855     memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
   57856 
   57857     limit = pOld->nCell+pOld->nOverflow;
   57858     if( pOld->nOverflow>0 ){
   57859       for(j=0; j<limit; j++){
   57860         assert( nCell<nMaxCells );
   57861         apCell[nCell] = findOverflowCell(pOld, j);
   57862         szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
   57863         nCell++;
   57864       }
   57865     }else{
   57866       u8 *aData = pOld->aData;
   57867       u16 maskPage = pOld->maskPage;
   57868       u16 cellOffset = pOld->cellOffset;
   57869       for(j=0; j<limit; j++){
   57870         assert( nCell<nMaxCells );
   57871         apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
   57872         szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
   57873         nCell++;
   57874       }
   57875     }
   57876     if( i<nOld-1 && !leafData){
   57877       u16 sz = (u16)szNew[i];
   57878       u8 *pTemp;
   57879       assert( nCell<nMaxCells );
   57880       szCell[nCell] = sz;
   57881       pTemp = &aSpace1[iSpace1];
   57882       iSpace1 += sz;
   57883       assert( sz<=pBt->maxLocal+23 );
   57884       assert( iSpace1 <= (int)pBt->pageSize );
   57885       memcpy(pTemp, apDiv[i], sz);
   57886       apCell[nCell] = pTemp+leafCorrection;
   57887       assert( leafCorrection==0 || leafCorrection==4 );
   57888       szCell[nCell] = szCell[nCell] - leafCorrection;
   57889       if( !pOld->leaf ){
   57890         assert( leafCorrection==0 );
   57891         assert( pOld->hdrOffset==0 );
   57892         /* The right pointer of the child page pOld becomes the left
   57893         ** pointer of the divider cell */
   57894         memcpy(apCell[nCell], &pOld->aData[8], 4);
   57895       }else{
   57896         assert( leafCorrection==4 );
   57897         if( szCell[nCell]<4 ){
   57898           /* Do not allow any cells smaller than 4 bytes. */
   57899           szCell[nCell] = 4;
   57900         }
   57901       }
   57902       nCell++;
   57903     }
   57904   }
   57905 
   57906   /*
   57907   ** Figure out the number of pages needed to hold all nCell cells.
   57908   ** Store this number in "k".  Also compute szNew[] which is the total
   57909   ** size of all cells on the i-th page and cntNew[] which is the index
   57910   ** in apCell[] of the cell that divides page i from page i+1.
   57911   ** cntNew[k] should equal nCell.
   57912   **
   57913   ** Values computed by this block:
   57914   **
   57915   **           k: The total number of sibling pages
   57916   **    szNew[i]: Spaced used on the i-th sibling page.
   57917   **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
   57918   **              the right of the i-th sibling page.
   57919   ** usableSpace: Number of bytes of space available on each sibling.
   57920   **
   57921   */
   57922   usableSpace = pBt->usableSize - 12 + leafCorrection;
   57923   for(subtotal=k=i=0; i<nCell; i++){
   57924     assert( i<nMaxCells );
   57925     subtotal += szCell[i] + 2;
   57926     if( subtotal > usableSpace ){
   57927       szNew[k] = subtotal - szCell[i];
   57928       cntNew[k] = i;
   57929       if( leafData ){ i--; }
   57930       subtotal = 0;
   57931       k++;
   57932       if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
   57933     }
   57934   }
   57935   szNew[k] = subtotal;
   57936   cntNew[k] = nCell;
   57937   k++;
   57938 
   57939   /*
   57940   ** The packing computed by the previous block is biased toward the siblings
   57941   ** on the left side.  The left siblings are always nearly full, while the
   57942   ** right-most sibling might be nearly empty.  This block of code attempts
   57943   ** to adjust the packing of siblings to get a better balance.
   57944   **
   57945   ** This adjustment is more than an optimization.  The packing above might
   57946   ** be so out of balance as to be illegal.  For example, the right-most
   57947   ** sibling might be completely empty.  This adjustment is not optional.
   57948   */
   57949   for(i=k-1; i>0; i--){
   57950     int szRight = szNew[i];  /* Size of sibling on the right */
   57951     int szLeft = szNew[i-1]; /* Size of sibling on the left */
   57952     int r;              /* Index of right-most cell in left sibling */
   57953     int d;              /* Index of first cell to the left of right sibling */
   57954 
   57955     r = cntNew[i-1] - 1;
   57956     d = r + 1 - leafData;
   57957     assert( d<nMaxCells );
   57958     assert( r<nMaxCells );
   57959     while( szRight==0
   57960        || (!bBulk && szRight+szCell[d]+2<=szLeft-(szCell[r]+2))
   57961     ){
   57962       szRight += szCell[d] + 2;
   57963       szLeft -= szCell[r] + 2;
   57964       cntNew[i-1]--;
   57965       r = cntNew[i-1] - 1;
   57966       d = r + 1 - leafData;
   57967     }
   57968     szNew[i] = szRight;
   57969     szNew[i-1] = szLeft;
   57970   }
   57971 
   57972   /* Either we found one or more cells (cntnew[0])>0) or pPage is
   57973   ** a virtual root page.  A virtual root page is when the real root
   57974   ** page is page 1 and we are the only child of that page.
   57975   **
   57976   ** UPDATE:  The assert() below is not necessarily true if the database
   57977   ** file is corrupt.  The corruption will be detected and reported later
   57978   ** in this procedure so there is no need to act upon it now.
   57979   */
   57980 #if 0
   57981   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
   57982 #endif
   57983 
   57984   TRACE(("BALANCE: old: %d %d %d  ",
   57985     apOld[0]->pgno,
   57986     nOld>=2 ? apOld[1]->pgno : 0,
   57987     nOld>=3 ? apOld[2]->pgno : 0
   57988   ));
   57989 
   57990   /*
   57991   ** Allocate k new pages.  Reuse old pages where possible.
   57992   */
   57993   if( apOld[0]->pgno<=1 ){
   57994     rc = SQLITE_CORRUPT_BKPT;
   57995     goto balance_cleanup;
   57996   }
   57997   pageFlags = apOld[0]->aData[0];
   57998   for(i=0; i<k; i++){
   57999     MemPage *pNew;
   58000     if( i<nOld ){
   58001       pNew = apNew[i] = apOld[i];
   58002       apOld[i] = 0;
   58003       rc = sqlite3PagerWrite(pNew->pDbPage);
   58004       nNew++;
   58005       if( rc ) goto balance_cleanup;
   58006     }else{
   58007       assert( i>0 );
   58008       rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
   58009       if( rc ) goto balance_cleanup;
   58010       apNew[i] = pNew;
   58011       nNew++;
   58012 
   58013       /* Set the pointer-map entry for the new sibling page. */
   58014       if( ISAUTOVACUUM ){
   58015         ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
   58016         if( rc!=SQLITE_OK ){
   58017           goto balance_cleanup;
   58018         }
   58019       }
   58020     }
   58021   }
   58022 
   58023   /* Free any old pages that were not reused as new pages.
   58024   */
   58025   while( i<nOld ){
   58026     freePage(apOld[i], &rc);
   58027     if( rc ) goto balance_cleanup;
   58028     releasePage(apOld[i]);
   58029     apOld[i] = 0;
   58030     i++;
   58031   }
   58032 
   58033   /*
   58034   ** Put the new pages in accending order.  This helps to
   58035   ** keep entries in the disk file in order so that a scan
   58036   ** of the table is a linear scan through the file.  That
   58037   ** in turn helps the operating system to deliver pages
   58038   ** from the disk more rapidly.
   58039   **
   58040   ** An O(n^2) insertion sort algorithm is used, but since
   58041   ** n is never more than NB (a small constant), that should
   58042   ** not be a problem.
   58043   **
   58044   ** When NB==3, this one optimization makes the database
   58045   ** about 25% faster for large insertions and deletions.
   58046   */
   58047   for(i=0; i<k-1; i++){
   58048     int minV = apNew[i]->pgno;
   58049     int minI = i;
   58050     for(j=i+1; j<k; j++){
   58051       if( apNew[j]->pgno<(unsigned)minV ){
   58052         minI = j;
   58053         minV = apNew[j]->pgno;
   58054       }
   58055     }
   58056     if( minI>i ){
   58057       MemPage *pT;
   58058       pT = apNew[i];
   58059       apNew[i] = apNew[minI];
   58060       apNew[minI] = pT;
   58061     }
   58062   }
   58063   TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
   58064     apNew[0]->pgno, szNew[0],
   58065     nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
   58066     nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
   58067     nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
   58068     nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
   58069 
   58070   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
   58071   put4byte(pRight, apNew[nNew-1]->pgno);
   58072 
   58073   /*
   58074   ** Evenly distribute the data in apCell[] across the new pages.
   58075   ** Insert divider cells into pParent as necessary.
   58076   */
   58077   j = 0;
   58078   for(i=0; i<nNew; i++){
   58079     /* Assemble the new sibling page. */
   58080     MemPage *pNew = apNew[i];
   58081     assert( j<nMaxCells );
   58082     zeroPage(pNew, pageFlags);
   58083     assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
   58084     assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
   58085     assert( pNew->nOverflow==0 );
   58086 
   58087     j = cntNew[i];
   58088 
   58089     /* If the sibling page assembled above was not the right-most sibling,
   58090     ** insert a divider cell into the parent page.
   58091     */
   58092     assert( i<nNew-1 || j==nCell );
   58093     if( j<nCell ){
   58094       u8 *pCell;
   58095       u8 *pTemp;
   58096       int sz;
   58097 
   58098       assert( j<nMaxCells );
   58099       pCell = apCell[j];
   58100       sz = szCell[j] + leafCorrection;
   58101       pTemp = &aOvflSpace[iOvflSpace];
   58102       if( !pNew->leaf ){
   58103         memcpy(&pNew->aData[8], pCell, 4);
   58104       }else if( leafData ){
   58105         /* If the tree is a leaf-data tree, and the siblings are leaves,
   58106         ** then there is no divider cell in apCell[]. Instead, the divider
   58107         ** cell consists of the integer key for the right-most cell of
   58108         ** the sibling-page assembled above only.
   58109         */
   58110         CellInfo info;
   58111         j--;
   58112         btreeParseCellPtr(pNew, apCell[j], &info);
   58113         pCell = pTemp;
   58114         sz = 4 + putVarint(&pCell[4], info.nKey);
   58115         pTemp = 0;
   58116       }else{
   58117         pCell -= 4;
   58118         /* Obscure case for non-leaf-data trees: If the cell at pCell was
   58119         ** previously stored on a leaf node, and its reported size was 4
   58120         ** bytes, then it may actually be smaller than this
   58121         ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
   58122         ** any cell). But it is important to pass the correct size to
   58123         ** insertCell(), so reparse the cell now.
   58124         **
   58125         ** Note that this can never happen in an SQLite data file, as all
   58126         ** cells are at least 4 bytes. It only happens in b-trees used
   58127         ** to evaluate "IN (SELECT ...)" and similar clauses.
   58128         */
   58129         if( szCell[j]==4 ){
   58130           assert(leafCorrection==4);
   58131           sz = cellSizePtr(pParent, pCell);
   58132         }
   58133       }
   58134       iOvflSpace += sz;
   58135       assert( sz<=pBt->maxLocal+23 );
   58136       assert( iOvflSpace <= (int)pBt->pageSize );
   58137       insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
   58138       if( rc!=SQLITE_OK ) goto balance_cleanup;
   58139       assert( sqlite3PagerIswriteable(pParent->pDbPage) );
   58140 
   58141       j++;
   58142       nxDiv++;
   58143     }
   58144   }
   58145   assert( j==nCell );
   58146   assert( nOld>0 );
   58147   assert( nNew>0 );
   58148   if( (pageFlags & PTF_LEAF)==0 ){
   58149     u8 *zChild = &apCopy[nOld-1]->aData[8];
   58150     memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
   58151   }
   58152 
   58153   if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
   58154     /* The root page of the b-tree now contains no cells. The only sibling
   58155     ** page is the right-child of the parent. Copy the contents of the
   58156     ** child page into the parent, decreasing the overall height of the
   58157     ** b-tree structure by one. This is described as the "balance-shallower"
   58158     ** sub-algorithm in some documentation.
   58159     **
   58160     ** If this is an auto-vacuum database, the call to copyNodeContent()
   58161     ** sets all pointer-map entries corresponding to database image pages
   58162     ** for which the pointer is stored within the content being copied.
   58163     **
   58164     ** The second assert below verifies that the child page is defragmented
   58165     ** (it must be, as it was just reconstructed using assemblePage()). This
   58166     ** is important if the parent page happens to be page 1 of the database
   58167     ** image.  */
   58168     assert( nNew==1 );
   58169     assert( apNew[0]->nFree ==
   58170         (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
   58171     );
   58172     copyNodeContent(apNew[0], pParent, &rc);
   58173     freePage(apNew[0], &rc);
   58174   }else if( ISAUTOVACUUM ){
   58175     /* Fix the pointer-map entries for all the cells that were shifted around.
   58176     ** There are several different types of pointer-map entries that need to
   58177     ** be dealt with by this routine. Some of these have been set already, but
   58178     ** many have not. The following is a summary:
   58179     **
   58180     **   1) The entries associated with new sibling pages that were not
   58181     **      siblings when this function was called. These have already
   58182     **      been set. We don't need to worry about old siblings that were
   58183     **      moved to the free-list - the freePage() code has taken care
   58184     **      of those.
   58185     **
   58186     **   2) The pointer-map entries associated with the first overflow
   58187     **      page in any overflow chains used by new divider cells. These
   58188     **      have also already been taken care of by the insertCell() code.
   58189     **
   58190     **   3) If the sibling pages are not leaves, then the child pages of
   58191     **      cells stored on the sibling pages may need to be updated.
   58192     **
   58193     **   4) If the sibling pages are not internal intkey nodes, then any
   58194     **      overflow pages used by these cells may need to be updated
   58195     **      (internal intkey nodes never contain pointers to overflow pages).
   58196     **
   58197     **   5) If the sibling pages are not leaves, then the pointer-map
   58198     **      entries for the right-child pages of each sibling may need
   58199     **      to be updated.
   58200     **
   58201     ** Cases 1 and 2 are dealt with above by other code. The next
   58202     ** block deals with cases 3 and 4 and the one after that, case 5. Since
   58203     ** setting a pointer map entry is a relatively expensive operation, this
   58204     ** code only sets pointer map entries for child or overflow pages that have
   58205     ** actually moved between pages.  */
   58206     MemPage *pNew = apNew[0];
   58207     MemPage *pOld = apCopy[0];
   58208     int nOverflow = pOld->nOverflow;
   58209     int iNextOld = pOld->nCell + nOverflow;
   58210     int iOverflow = (nOverflow ? pOld->aiOvfl[0] : -1);
   58211     j = 0;                             /* Current 'old' sibling page */
   58212     k = 0;                             /* Current 'new' sibling page */
   58213     for(i=0; i<nCell; i++){
   58214       int isDivider = 0;
   58215       while( i==iNextOld ){
   58216         /* Cell i is the cell immediately following the last cell on old
   58217         ** sibling page j. If the siblings are not leaf pages of an
   58218         ** intkey b-tree, then cell i was a divider cell. */
   58219         assert( j+1 < ArraySize(apCopy) );
   58220         assert( j+1 < nOld );
   58221         pOld = apCopy[++j];
   58222         iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
   58223         if( pOld->nOverflow ){
   58224           nOverflow = pOld->nOverflow;
   58225           iOverflow = i + !leafData + pOld->aiOvfl[0];
   58226         }
   58227         isDivider = !leafData;
   58228       }
   58229 
   58230       assert(nOverflow>0 || iOverflow<i );
   58231       assert(nOverflow<2 || pOld->aiOvfl[0]==pOld->aiOvfl[1]-1);
   58232       assert(nOverflow<3 || pOld->aiOvfl[1]==pOld->aiOvfl[2]-1);
   58233       if( i==iOverflow ){
   58234         isDivider = 1;
   58235         if( (--nOverflow)>0 ){
   58236           iOverflow++;
   58237         }
   58238       }
   58239 
   58240       if( i==cntNew[k] ){
   58241         /* Cell i is the cell immediately following the last cell on new
   58242         ** sibling page k. If the siblings are not leaf pages of an
   58243         ** intkey b-tree, then cell i is a divider cell.  */
   58244         pNew = apNew[++k];
   58245         if( !leafData ) continue;
   58246       }
   58247       assert( j<nOld );
   58248       assert( k<nNew );
   58249 
   58250       /* If the cell was originally divider cell (and is not now) or
   58251       ** an overflow cell, or if the cell was located on a different sibling
   58252       ** page before the balancing, then the pointer map entries associated
   58253       ** with any child or overflow pages need to be updated.  */
   58254       if( isDivider || pOld->pgno!=pNew->pgno ){
   58255         if( !leafCorrection ){
   58256           ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
   58257         }
   58258         if( szCell[i]>pNew->minLocal ){
   58259           ptrmapPutOvflPtr(pNew, apCell[i], &rc);
   58260         }
   58261       }
   58262     }
   58263 
   58264     if( !leafCorrection ){
   58265       for(i=0; i<nNew; i++){
   58266         u32 key = get4byte(&apNew[i]->aData[8]);
   58267         ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
   58268       }
   58269     }
   58270 
   58271 #if 0
   58272     /* The ptrmapCheckPages() contains assert() statements that verify that
   58273     ** all pointer map pages are set correctly. This is helpful while
   58274     ** debugging. This is usually disabled because a corrupt database may
   58275     ** cause an assert() statement to fail.  */
   58276     ptrmapCheckPages(apNew, nNew);
   58277     ptrmapCheckPages(&pParent, 1);
   58278 #endif
   58279   }
   58280 
   58281   assert( pParent->isInit );
   58282   TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
   58283           nOld, nNew, nCell));
   58284 
   58285   /*
   58286   ** Cleanup before returning.
   58287   */
   58288 balance_cleanup:
   58289   sqlite3ScratchFree(apCell);
   58290   for(i=0; i<nOld; i++){
   58291     releasePage(apOld[i]);
   58292   }
   58293   for(i=0; i<nNew; i++){
   58294     releasePage(apNew[i]);
   58295   }
   58296 
   58297   return rc;
   58298 }
   58299 #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
   58300 #pragma optimize("", on)
   58301 #endif
   58302 
   58303 
   58304 /*
   58305 ** This function is called when the root page of a b-tree structure is
   58306 ** overfull (has one or more overflow pages).
   58307 **
   58308 ** A new child page is allocated and the contents of the current root
   58309 ** page, including overflow cells, are copied into the child. The root
   58310 ** page is then overwritten to make it an empty page with the right-child
   58311 ** pointer pointing to the new page.
   58312 **
   58313 ** Before returning, all pointer-map entries corresponding to pages
   58314 ** that the new child-page now contains pointers to are updated. The
   58315 ** entry corresponding to the new right-child pointer of the root
   58316 ** page is also updated.
   58317 **
   58318 ** If successful, *ppChild is set to contain a reference to the child
   58319 ** page and SQLITE_OK is returned. In this case the caller is required
   58320 ** to call releasePage() on *ppChild exactly once. If an error occurs,
   58321 ** an error code is returned and *ppChild is set to 0.
   58322 */
   58323 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
   58324   int rc;                        /* Return value from subprocedures */
   58325   MemPage *pChild = 0;           /* Pointer to a new child page */
   58326   Pgno pgnoChild = 0;            /* Page number of the new child page */
   58327   BtShared *pBt = pRoot->pBt;    /* The BTree */
   58328 
   58329   assert( pRoot->nOverflow>0 );
   58330   assert( sqlite3_mutex_held(pBt->mutex) );
   58331 
   58332   /* Make pRoot, the root page of the b-tree, writable. Allocate a new
   58333   ** page that will become the new right-child of pPage. Copy the contents
   58334   ** of the node stored on pRoot into the new child page.
   58335   */
   58336   rc = sqlite3PagerWrite(pRoot->pDbPage);
   58337   if( rc==SQLITE_OK ){
   58338     rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
   58339     copyNodeContent(pRoot, pChild, &rc);
   58340     if( ISAUTOVACUUM ){
   58341       ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
   58342     }
   58343   }
   58344   if( rc ){
   58345     *ppChild = 0;
   58346     releasePage(pChild);
   58347     return rc;
   58348   }
   58349   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
   58350   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
   58351   assert( pChild->nCell==pRoot->nCell );
   58352 
   58353   TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
   58354 
   58355   /* Copy the overflow cells from pRoot to pChild */
   58356   memcpy(pChild->aiOvfl, pRoot->aiOvfl,
   58357          pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
   58358   memcpy(pChild->apOvfl, pRoot->apOvfl,
   58359          pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
   58360   pChild->nOverflow = pRoot->nOverflow;
   58361 
   58362   /* Zero the contents of pRoot. Then install pChild as the right-child. */
   58363   zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
   58364   put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
   58365 
   58366   *ppChild = pChild;
   58367   return SQLITE_OK;
   58368 }
   58369 
   58370 /*
   58371 ** The page that pCur currently points to has just been modified in
   58372 ** some way. This function figures out if this modification means the
   58373 ** tree needs to be balanced, and if so calls the appropriate balancing
   58374 ** routine. Balancing routines are:
   58375 **
   58376 **   balance_quick()
   58377 **   balance_deeper()
   58378 **   balance_nonroot()
   58379 */
   58380 static int balance(BtCursor *pCur){
   58381   int rc = SQLITE_OK;
   58382   const int nMin = pCur->pBt->usableSize * 2 / 3;
   58383   u8 aBalanceQuickSpace[13];
   58384   u8 *pFree = 0;
   58385 
   58386   TESTONLY( int balance_quick_called = 0 );
   58387   TESTONLY( int balance_deeper_called = 0 );
   58388 
   58389   do {
   58390     int iPage = pCur->iPage;
   58391     MemPage *pPage = pCur->apPage[iPage];
   58392 
   58393     if( iPage==0 ){
   58394       if( pPage->nOverflow ){
   58395         /* The root page of the b-tree is overfull. In this case call the
   58396         ** balance_deeper() function to create a new child for the root-page
   58397         ** and copy the current contents of the root-page to it. The
   58398         ** next iteration of the do-loop will balance the child page.
   58399         */
   58400         assert( (balance_deeper_called++)==0 );
   58401         rc = balance_deeper(pPage, &pCur->apPage[1]);
   58402         if( rc==SQLITE_OK ){
   58403           pCur->iPage = 1;
   58404           pCur->aiIdx[0] = 0;
   58405           pCur->aiIdx[1] = 0;
   58406           assert( pCur->apPage[1]->nOverflow );
   58407         }
   58408       }else{
   58409         break;
   58410       }
   58411     }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
   58412       break;
   58413     }else{
   58414       MemPage * const pParent = pCur->apPage[iPage-1];
   58415       int const iIdx = pCur->aiIdx[iPage-1];
   58416 
   58417       rc = sqlite3PagerWrite(pParent->pDbPage);
   58418       if( rc==SQLITE_OK ){
   58419 #ifndef SQLITE_OMIT_QUICKBALANCE
   58420         if( pPage->hasData
   58421          && pPage->nOverflow==1
   58422          && pPage->aiOvfl[0]==pPage->nCell
   58423          && pParent->pgno!=1
   58424          && pParent->nCell==iIdx
   58425         ){
   58426           /* Call balance_quick() to create a new sibling of pPage on which
   58427           ** to store the overflow cell. balance_quick() inserts a new cell
   58428           ** into pParent, which may cause pParent overflow. If this
   58429           ** happens, the next interation of the do-loop will balance pParent
   58430           ** use either balance_nonroot() or balance_deeper(). Until this
   58431           ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
   58432           ** buffer.
   58433           **
   58434           ** The purpose of the following assert() is to check that only a
   58435           ** single call to balance_quick() is made for each call to this
   58436           ** function. If this were not verified, a subtle bug involving reuse
   58437           ** of the aBalanceQuickSpace[] might sneak in.
   58438           */
   58439           assert( (balance_quick_called++)==0 );
   58440           rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
   58441         }else
   58442 #endif
   58443         {
   58444           /* In this case, call balance_nonroot() to redistribute cells
   58445           ** between pPage and up to 2 of its sibling pages. This involves
   58446           ** modifying the contents of pParent, which may cause pParent to
   58447           ** become overfull or underfull. The next iteration of the do-loop
   58448           ** will balance the parent page to correct this.
   58449           **
   58450           ** If the parent page becomes overfull, the overflow cell or cells
   58451           ** are stored in the pSpace buffer allocated immediately below.
   58452           ** A subsequent iteration of the do-loop will deal with this by
   58453           ** calling balance_nonroot() (balance_deeper() may be called first,
   58454           ** but it doesn't deal with overflow cells - just moves them to a
   58455           ** different page). Once this subsequent call to balance_nonroot()
   58456           ** has completed, it is safe to release the pSpace buffer used by
   58457           ** the previous call, as the overflow cell data will have been
   58458           ** copied either into the body of a database page or into the new
   58459           ** pSpace buffer passed to the latter call to balance_nonroot().
   58460           */
   58461           u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
   58462           rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1, pCur->hints);
   58463           if( pFree ){
   58464             /* If pFree is not NULL, it points to the pSpace buffer used
   58465             ** by a previous call to balance_nonroot(). Its contents are
   58466             ** now stored either on real database pages or within the
   58467             ** new pSpace buffer, so it may be safely freed here. */
   58468             sqlite3PageFree(pFree);
   58469           }
   58470 
   58471           /* The pSpace buffer will be freed after the next call to
   58472           ** balance_nonroot(), or just before this function returns, whichever
   58473           ** comes first. */
   58474           pFree = pSpace;
   58475         }
   58476       }
   58477 
   58478       pPage->nOverflow = 0;
   58479 
   58480       /* The next iteration of the do-loop balances the parent page. */
   58481       releasePage(pPage);
   58482       pCur->iPage--;
   58483     }
   58484   }while( rc==SQLITE_OK );
   58485 
   58486   if( pFree ){
   58487     sqlite3PageFree(pFree);
   58488   }
   58489   return rc;
   58490 }
   58491 
   58492 
   58493 /*
   58494 ** Insert a new record into the BTree.  The key is given by (pKey,nKey)
   58495 ** and the data is given by (pData,nData).  The cursor is used only to
   58496 ** define what table the record should be inserted into.  The cursor
   58497 ** is left pointing at a random location.
   58498 **
   58499 ** For an INTKEY table, only the nKey value of the key is used.  pKey is
   58500 ** ignored.  For a ZERODATA table, the pData and nData are both ignored.
   58501 **
   58502 ** If the seekResult parameter is non-zero, then a successful call to
   58503 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
   58504 ** been performed. seekResult is the search result returned (a negative
   58505 ** number if pCur points at an entry that is smaller than (pKey, nKey), or
   58506 ** a positive value if pCur points at an etry that is larger than
   58507 ** (pKey, nKey)).
   58508 **
   58509 ** If the seekResult parameter is non-zero, then the caller guarantees that
   58510 ** cursor pCur is pointing at the existing copy of a row that is to be
   58511 ** overwritten.  If the seekResult parameter is 0, then cursor pCur may
   58512 ** point to any entry or to no entry at all and so this function has to seek
   58513 ** the cursor before the new key can be inserted.
   58514 */
   58515 SQLITE_PRIVATE int sqlite3BtreeInsert(
   58516   BtCursor *pCur,                /* Insert data into the table of this cursor */
   58517   const void *pKey, i64 nKey,    /* The key of the new record */
   58518   const void *pData, int nData,  /* The data of the new record */
   58519   int nZero,                     /* Number of extra 0 bytes to append to data */
   58520   int appendBias,                /* True if this is likely an append */
   58521   int seekResult                 /* Result of prior MovetoUnpacked() call */
   58522 ){
   58523   int rc;
   58524   int loc = seekResult;          /* -1: before desired location  +1: after */
   58525   int szNew = 0;
   58526   int idx;
   58527   MemPage *pPage;
   58528   Btree *p = pCur->pBtree;
   58529   BtShared *pBt = p->pBt;
   58530   unsigned char *oldCell;
   58531   unsigned char *newCell = 0;
   58532 
   58533   if( pCur->eState==CURSOR_FAULT ){
   58534     assert( pCur->skipNext!=SQLITE_OK );
   58535     return pCur->skipNext;
   58536   }
   58537 
   58538   assert( cursorHoldsMutex(pCur) );
   58539   assert( (pCur->curFlags & BTCF_WriteFlag)!=0 && pBt->inTransaction==TRANS_WRITE
   58540               && (pBt->btsFlags & BTS_READ_ONLY)==0 );
   58541   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
   58542 
   58543   /* Assert that the caller has been consistent. If this cursor was opened
   58544   ** expecting an index b-tree, then the caller should be inserting blob
   58545   ** keys with no associated data. If the cursor was opened expecting an
   58546   ** intkey table, the caller should be inserting integer keys with a
   58547   ** blob of associated data.  */
   58548   assert( (pKey==0)==(pCur->pKeyInfo==0) );
   58549 
   58550   /* Save the positions of any other cursors open on this table.
   58551   **
   58552   ** In some cases, the call to btreeMoveto() below is a no-op. For
   58553   ** example, when inserting data into a table with auto-generated integer
   58554   ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
   58555   ** integer key to use. It then calls this function to actually insert the
   58556   ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
   58557   ** that the cursor is already where it needs to be and returns without
   58558   ** doing any work. To avoid thwarting these optimizations, it is important
   58559   ** not to clear the cursor here.
   58560   */
   58561   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
   58562   if( rc ) return rc;
   58563 
   58564   if( pCur->pKeyInfo==0 ){
   58565     /* If this is an insert into a table b-tree, invalidate any incrblob
   58566     ** cursors open on the row being replaced */
   58567     invalidateIncrblobCursors(p, nKey, 0);
   58568 
   58569     /* If the cursor is currently on the last row and we are appending a
   58570     ** new row onto the end, set the "loc" to avoid an unnecessary btreeMoveto()
   58571     ** call */
   58572     if( (pCur->curFlags&BTCF_ValidNKey)!=0 && nKey>0 && pCur->info.nKey==nKey-1 ){
   58573       loc = -1;
   58574     }
   58575   }
   58576 
   58577   if( !loc ){
   58578     rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
   58579     if( rc ) return rc;
   58580   }
   58581   assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
   58582 
   58583   pPage = pCur->apPage[pCur->iPage];
   58584   assert( pPage->intKey || nKey>=0 );
   58585   assert( pPage->leaf || !pPage->intKey );
   58586 
   58587   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
   58588           pCur->pgnoRoot, nKey, nData, pPage->pgno,
   58589           loc==0 ? "overwrite" : "new entry"));
   58590   assert( pPage->isInit );
   58591   allocateTempSpace(pBt);
   58592   newCell = pBt->pTmpSpace;
   58593   if( newCell==0 ) return SQLITE_NOMEM;
   58594   rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
   58595   if( rc ) goto end_insert;
   58596   assert( szNew==cellSizePtr(pPage, newCell) );
   58597   assert( szNew <= MX_CELL_SIZE(pBt) );
   58598   idx = pCur->aiIdx[pCur->iPage];
   58599   if( loc==0 ){
   58600     u16 szOld;
   58601     assert( idx<pPage->nCell );
   58602     rc = sqlite3PagerWrite(pPage->pDbPage);
   58603     if( rc ){
   58604       goto end_insert;
   58605     }
   58606     oldCell = findCell(pPage, idx);
   58607     if( !pPage->leaf ){
   58608       memcpy(newCell, oldCell, 4);
   58609     }
   58610     szOld = cellSizePtr(pPage, oldCell);
   58611     rc = clearCell(pPage, oldCell);
   58612     dropCell(pPage, idx, szOld, &rc);
   58613     if( rc ) goto end_insert;
   58614   }else if( loc<0 && pPage->nCell>0 ){
   58615     assert( pPage->leaf );
   58616     idx = ++pCur->aiIdx[pCur->iPage];
   58617   }else{
   58618     assert( pPage->leaf );
   58619   }
   58620   insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
   58621   assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
   58622 
   58623   /* If no error has occurred and pPage has an overflow cell, call balance()
   58624   ** to redistribute the cells within the tree. Since balance() may move
   58625   ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
   58626   ** variables.
   58627   **
   58628   ** Previous versions of SQLite called moveToRoot() to move the cursor
   58629   ** back to the root page as balance() used to invalidate the contents
   58630   ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
   58631   ** set the cursor state to "invalid". This makes common insert operations
   58632   ** slightly faster.
   58633   **
   58634   ** There is a subtle but important optimization here too. When inserting
   58635   ** multiple records into an intkey b-tree using a single cursor (as can
   58636   ** happen while processing an "INSERT INTO ... SELECT" statement), it
   58637   ** is advantageous to leave the cursor pointing to the last entry in
   58638   ** the b-tree if possible. If the cursor is left pointing to the last
   58639   ** entry in the table, and the next row inserted has an integer key
   58640   ** larger than the largest existing key, it is possible to insert the
   58641   ** row without seeking the cursor. This can be a big performance boost.
   58642   */
   58643   pCur->info.nSize = 0;
   58644   if( rc==SQLITE_OK && pPage->nOverflow ){
   58645     pCur->curFlags &= ~(BTCF_ValidNKey);
   58646     rc = balance(pCur);
   58647 
   58648     /* Must make sure nOverflow is reset to zero even if the balance()
   58649     ** fails. Internal data structure corruption will result otherwise.
   58650     ** Also, set the cursor state to invalid. This stops saveCursorPosition()
   58651     ** from trying to save the current position of the cursor.  */
   58652     pCur->apPage[pCur->iPage]->nOverflow = 0;
   58653     pCur->eState = CURSOR_INVALID;
   58654   }
   58655   assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
   58656 
   58657 end_insert:
   58658   return rc;
   58659 }
   58660 
   58661 /*
   58662 ** Delete the entry that the cursor is pointing to.  The cursor
   58663 ** is left pointing at a arbitrary location.
   58664 */
   58665 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
   58666   Btree *p = pCur->pBtree;
   58667   BtShared *pBt = p->pBt;
   58668   int rc;                              /* Return code */
   58669   MemPage *pPage;                      /* Page to delete cell from */
   58670   unsigned char *pCell;                /* Pointer to cell to delete */
   58671   int iCellIdx;                        /* Index of cell to delete */
   58672   int iCellDepth;                      /* Depth of node containing pCell */
   58673 
   58674   assert( cursorHoldsMutex(pCur) );
   58675   assert( pBt->inTransaction==TRANS_WRITE );
   58676   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
   58677   assert( pCur->curFlags & BTCF_WriteFlag );
   58678   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
   58679   assert( !hasReadConflicts(p, pCur->pgnoRoot) );
   58680 
   58681   if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
   58682    || NEVER(pCur->eState!=CURSOR_VALID)
   58683   ){
   58684     return SQLITE_ERROR;  /* Something has gone awry. */
   58685   }
   58686 
   58687   iCellDepth = pCur->iPage;
   58688   iCellIdx = pCur->aiIdx[iCellDepth];
   58689   pPage = pCur->apPage[iCellDepth];
   58690   pCell = findCell(pPage, iCellIdx);
   58691 
   58692   /* If the page containing the entry to delete is not a leaf page, move
   58693   ** the cursor to the largest entry in the tree that is smaller than
   58694   ** the entry being deleted. This cell will replace the cell being deleted
   58695   ** from the internal node. The 'previous' entry is used for this instead
   58696   ** of the 'next' entry, as the previous entry is always a part of the
   58697   ** sub-tree headed by the child page of the cell being deleted. This makes
   58698   ** balancing the tree following the delete operation easier.  */
   58699   if( !pPage->leaf ){
   58700     int notUsed = 0;
   58701     rc = sqlite3BtreePrevious(pCur, &notUsed);
   58702     if( rc ) return rc;
   58703   }
   58704 
   58705   /* Save the positions of any other cursors open on this table before
   58706   ** making any modifications. Make the page containing the entry to be
   58707   ** deleted writable. Then free any overflow pages associated with the
   58708   ** entry and finally remove the cell itself from within the page.
   58709   */
   58710   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
   58711   if( rc ) return rc;
   58712 
   58713   /* If this is a delete operation to remove a row from a table b-tree,
   58714   ** invalidate any incrblob cursors open on the row being deleted.  */
   58715   if( pCur->pKeyInfo==0 ){
   58716     invalidateIncrblobCursors(p, pCur->info.nKey, 0);
   58717   }
   58718 
   58719   rc = sqlite3PagerWrite(pPage->pDbPage);
   58720   if( rc ) return rc;
   58721   rc = clearCell(pPage, pCell);
   58722   dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
   58723   if( rc ) return rc;
   58724 
   58725   /* If the cell deleted was not located on a leaf page, then the cursor
   58726   ** is currently pointing to the largest entry in the sub-tree headed
   58727   ** by the child-page of the cell that was just deleted from an internal
   58728   ** node. The cell from the leaf node needs to be moved to the internal
   58729   ** node to replace the deleted cell.  */
   58730   if( !pPage->leaf ){
   58731     MemPage *pLeaf = pCur->apPage[pCur->iPage];
   58732     int nCell;
   58733     Pgno n = pCur->apPage[iCellDepth+1]->pgno;
   58734     unsigned char *pTmp;
   58735 
   58736     pCell = findCell(pLeaf, pLeaf->nCell-1);
   58737     nCell = cellSizePtr(pLeaf, pCell);
   58738     assert( MX_CELL_SIZE(pBt) >= nCell );
   58739 
   58740     allocateTempSpace(pBt);
   58741     pTmp = pBt->pTmpSpace;
   58742 
   58743     rc = sqlite3PagerWrite(pLeaf->pDbPage);
   58744     insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
   58745     dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
   58746     if( rc ) return rc;
   58747   }
   58748 
   58749   /* Balance the tree. If the entry deleted was located on a leaf page,
   58750   ** then the cursor still points to that page. In this case the first
   58751   ** call to balance() repairs the tree, and the if(...) condition is
   58752   ** never true.
   58753   **
   58754   ** Otherwise, if the entry deleted was on an internal node page, then
   58755   ** pCur is pointing to the leaf page from which a cell was removed to
   58756   ** replace the cell deleted from the internal node. This is slightly
   58757   ** tricky as the leaf node may be underfull, and the internal node may
   58758   ** be either under or overfull. In this case run the balancing algorithm
   58759   ** on the leaf node first. If the balance proceeds far enough up the
   58760   ** tree that we can be sure that any problem in the internal node has
   58761   ** been corrected, so be it. Otherwise, after balancing the leaf node,
   58762   ** walk the cursor up the tree to the internal node and balance it as
   58763   ** well.  */
   58764   rc = balance(pCur);
   58765   if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
   58766     while( pCur->iPage>iCellDepth ){
   58767       releasePage(pCur->apPage[pCur->iPage--]);
   58768     }
   58769     rc = balance(pCur);
   58770   }
   58771 
   58772   if( rc==SQLITE_OK ){
   58773     moveToRoot(pCur);
   58774   }
   58775   return rc;
   58776 }
   58777 
   58778 /*
   58779 ** Create a new BTree table.  Write into *piTable the page
   58780 ** number for the root page of the new table.
   58781 **
   58782 ** The type of type is determined by the flags parameter.  Only the
   58783 ** following values of flags are currently in use.  Other values for
   58784 ** flags might not work:
   58785 **
   58786 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
   58787 **     BTREE_ZERODATA                  Used for SQL indices
   58788 */
   58789 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
   58790   BtShared *pBt = p->pBt;
   58791   MemPage *pRoot;
   58792   Pgno pgnoRoot;
   58793   int rc;
   58794   int ptfFlags;          /* Page-type flage for the root page of new table */
   58795 
   58796   assert( sqlite3BtreeHoldsMutex(p) );
   58797   assert( pBt->inTransaction==TRANS_WRITE );
   58798   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
   58799 
   58800 #ifdef SQLITE_OMIT_AUTOVACUUM
   58801   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
   58802   if( rc ){
   58803     return rc;
   58804   }
   58805 #else
   58806   if( pBt->autoVacuum ){
   58807     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
   58808     MemPage *pPageMove; /* The page to move to. */
   58809 
   58810     /* Creating a new table may probably require moving an existing database
   58811     ** to make room for the new tables root page. In case this page turns
   58812     ** out to be an overflow page, delete all overflow page-map caches
   58813     ** held by open cursors.
   58814     */
   58815     invalidateAllOverflowCache(pBt);
   58816 
   58817     /* Read the value of meta[3] from the database to determine where the
   58818     ** root page of the new table should go. meta[3] is the largest root-page
   58819     ** created so far, so the new root-page is (meta[3]+1).
   58820     */
   58821     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
   58822     pgnoRoot++;
   58823 
   58824     /* The new root-page may not be allocated on a pointer-map page, or the
   58825     ** PENDING_BYTE page.
   58826     */
   58827     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
   58828         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
   58829       pgnoRoot++;
   58830     }
   58831     assert( pgnoRoot>=3 );
   58832 
   58833     /* Allocate a page. The page that currently resides at pgnoRoot will
   58834     ** be moved to the allocated page (unless the allocated page happens
   58835     ** to reside at pgnoRoot).
   58836     */
   58837     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
   58838     if( rc!=SQLITE_OK ){
   58839       return rc;
   58840     }
   58841 
   58842     if( pgnoMove!=pgnoRoot ){
   58843       /* pgnoRoot is the page that will be used for the root-page of
   58844       ** the new table (assuming an error did not occur). But we were
   58845       ** allocated pgnoMove. If required (i.e. if it was not allocated
   58846       ** by extending the file), the current page at position pgnoMove
   58847       ** is already journaled.
   58848       */
   58849       u8 eType = 0;
   58850       Pgno iPtrPage = 0;
   58851 
   58852       /* Save the positions of any open cursors. This is required in
   58853       ** case they are holding a reference to an xFetch reference
   58854       ** corresponding to page pgnoRoot.  */
   58855       rc = saveAllCursors(pBt, 0, 0);
   58856       releasePage(pPageMove);
   58857       if( rc!=SQLITE_OK ){
   58858         return rc;
   58859       }
   58860 
   58861       /* Move the page currently at pgnoRoot to pgnoMove. */
   58862       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
   58863       if( rc!=SQLITE_OK ){
   58864         return rc;
   58865       }
   58866       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
   58867       if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
   58868         rc = SQLITE_CORRUPT_BKPT;
   58869       }
   58870       if( rc!=SQLITE_OK ){
   58871         releasePage(pRoot);
   58872         return rc;
   58873       }
   58874       assert( eType!=PTRMAP_ROOTPAGE );
   58875       assert( eType!=PTRMAP_FREEPAGE );
   58876       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
   58877       releasePage(pRoot);
   58878 
   58879       /* Obtain the page at pgnoRoot */
   58880       if( rc!=SQLITE_OK ){
   58881         return rc;
   58882       }
   58883       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
   58884       if( rc!=SQLITE_OK ){
   58885         return rc;
   58886       }
   58887       rc = sqlite3PagerWrite(pRoot->pDbPage);
   58888       if( rc!=SQLITE_OK ){
   58889         releasePage(pRoot);
   58890         return rc;
   58891       }
   58892     }else{
   58893       pRoot = pPageMove;
   58894     }
   58895 
   58896     /* Update the pointer-map and meta-data with the new root-page number. */
   58897     ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
   58898     if( rc ){
   58899       releasePage(pRoot);
   58900       return rc;
   58901     }
   58902 
   58903     /* When the new root page was allocated, page 1 was made writable in
   58904     ** order either to increase the database filesize, or to decrement the
   58905     ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
   58906     */
   58907     assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
   58908     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
   58909     if( NEVER(rc) ){
   58910       releasePage(pRoot);
   58911       return rc;
   58912     }
   58913 
   58914   }else{
   58915     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
   58916     if( rc ) return rc;
   58917   }
   58918 #endif
   58919   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
   58920   if( createTabFlags & BTREE_INTKEY ){
   58921     ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
   58922   }else{
   58923     ptfFlags = PTF_ZERODATA | PTF_LEAF;
   58924   }
   58925   zeroPage(pRoot, ptfFlags);
   58926   sqlite3PagerUnref(pRoot->pDbPage);
   58927   assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
   58928   *piTable = (int)pgnoRoot;
   58929   return SQLITE_OK;
   58930 }
   58931 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
   58932   int rc;
   58933   sqlite3BtreeEnter(p);
   58934   rc = btreeCreateTable(p, piTable, flags);
   58935   sqlite3BtreeLeave(p);
   58936   return rc;
   58937 }
   58938 
   58939 /*
   58940 ** Erase the given database page and all its children.  Return
   58941 ** the page to the freelist.
   58942 */
   58943 static int clearDatabasePage(
   58944   BtShared *pBt,           /* The BTree that contains the table */
   58945   Pgno pgno,               /* Page number to clear */
   58946   int freePageFlag,        /* Deallocate page if true */
   58947   int *pnChange            /* Add number of Cells freed to this counter */
   58948 ){
   58949   MemPage *pPage;
   58950   int rc;
   58951   unsigned char *pCell;
   58952   int i;
   58953   int hdr;
   58954 
   58955   assert( sqlite3_mutex_held(pBt->mutex) );
   58956   if( pgno>btreePagecount(pBt) ){
   58957     return SQLITE_CORRUPT_BKPT;
   58958   }
   58959 
   58960   rc = getAndInitPage(pBt, pgno, &pPage, 0);
   58961   if( rc ) return rc;
   58962   hdr = pPage->hdrOffset;
   58963   for(i=0; i<pPage->nCell; i++){
   58964     pCell = findCell(pPage, i);
   58965     if( !pPage->leaf ){
   58966       rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
   58967       if( rc ) goto cleardatabasepage_out;
   58968     }
   58969     rc = clearCell(pPage, pCell);
   58970     if( rc ) goto cleardatabasepage_out;
   58971   }
   58972   if( !pPage->leaf ){
   58973     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
   58974     if( rc ) goto cleardatabasepage_out;
   58975   }else if( pnChange ){
   58976     assert( pPage->intKey );
   58977     *pnChange += pPage->nCell;
   58978   }
   58979   if( freePageFlag ){
   58980     freePage(pPage, &rc);
   58981   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
   58982     zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
   58983   }
   58984 
   58985 cleardatabasepage_out:
   58986   releasePage(pPage);
   58987   return rc;
   58988 }
   58989 
   58990 /*
   58991 ** Delete all information from a single table in the database.  iTable is
   58992 ** the page number of the root of the table.  After this routine returns,
   58993 ** the root page is empty, but still exists.
   58994 **
   58995 ** This routine will fail with SQLITE_LOCKED if there are any open
   58996 ** read cursors on the table.  Open write cursors are moved to the
   58997 ** root of the table.
   58998 **
   58999 ** If pnChange is not NULL, then table iTable must be an intkey table. The
   59000 ** integer value pointed to by pnChange is incremented by the number of
   59001 ** entries in the table.
   59002 */
   59003 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
   59004   int rc;
   59005   BtShared *pBt = p->pBt;
   59006   sqlite3BtreeEnter(p);
   59007   assert( p->inTrans==TRANS_WRITE );
   59008 
   59009   rc = saveAllCursors(pBt, (Pgno)iTable, 0);
   59010 
   59011   if( SQLITE_OK==rc ){
   59012     /* Invalidate all incrblob cursors open on table iTable (assuming iTable
   59013     ** is the root of a table b-tree - if it is not, the following call is
   59014     ** a no-op).  */
   59015     invalidateIncrblobCursors(p, 0, 1);
   59016     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
   59017   }
   59018   sqlite3BtreeLeave(p);
   59019   return rc;
   59020 }
   59021 
   59022 /*
   59023 ** Delete all information from the single table that pCur is open on.
   59024 **
   59025 ** This routine only work for pCur on an ephemeral table.
   59026 */
   59027 SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
   59028   return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
   59029 }
   59030 
   59031 /*
   59032 ** Erase all information in a table and add the root of the table to
   59033 ** the freelist.  Except, the root of the principle table (the one on
   59034 ** page 1) is never added to the freelist.
   59035 **
   59036 ** This routine will fail with SQLITE_LOCKED if there are any open
   59037 ** cursors on the table.
   59038 **
   59039 ** If AUTOVACUUM is enabled and the page at iTable is not the last
   59040 ** root page in the database file, then the last root page
   59041 ** in the database file is moved into the slot formerly occupied by
   59042 ** iTable and that last slot formerly occupied by the last root page
   59043 ** is added to the freelist instead of iTable.  In this say, all
   59044 ** root pages are kept at the beginning of the database file, which
   59045 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the
   59046 ** page number that used to be the last root page in the file before
   59047 ** the move.  If no page gets moved, *piMoved is set to 0.
   59048 ** The last root page is recorded in meta[3] and the value of
   59049 ** meta[3] is updated by this procedure.
   59050 */
   59051 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
   59052   int rc;
   59053   MemPage *pPage = 0;
   59054   BtShared *pBt = p->pBt;
   59055 
   59056   assert( sqlite3BtreeHoldsMutex(p) );
   59057   assert( p->inTrans==TRANS_WRITE );
   59058 
   59059   /* It is illegal to drop a table if any cursors are open on the
   59060   ** database. This is because in auto-vacuum mode the backend may
   59061   ** need to move another root-page to fill a gap left by the deleted
   59062   ** root page. If an open cursor was using this page a problem would
   59063   ** occur.
   59064   **
   59065   ** This error is caught long before control reaches this point.
   59066   */
   59067   if( NEVER(pBt->pCursor) ){
   59068     sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
   59069     return SQLITE_LOCKED_SHAREDCACHE;
   59070   }
   59071 
   59072   rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
   59073   if( rc ) return rc;
   59074   rc = sqlite3BtreeClearTable(p, iTable, 0);
   59075   if( rc ){
   59076     releasePage(pPage);
   59077     return rc;
   59078   }
   59079 
   59080   *piMoved = 0;
   59081 
   59082   if( iTable>1 ){
   59083 #ifdef SQLITE_OMIT_AUTOVACUUM
   59084     freePage(pPage, &rc);
   59085     releasePage(pPage);
   59086 #else
   59087     if( pBt->autoVacuum ){
   59088       Pgno maxRootPgno;
   59089       sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
   59090 
   59091       if( iTable==maxRootPgno ){
   59092         /* If the table being dropped is the table with the largest root-page
   59093         ** number in the database, put the root page on the free list.
   59094         */
   59095         freePage(pPage, &rc);
   59096         releasePage(pPage);
   59097         if( rc!=SQLITE_OK ){
   59098           return rc;
   59099         }
   59100       }else{
   59101         /* The table being dropped does not have the largest root-page
   59102         ** number in the database. So move the page that does into the
   59103         ** gap left by the deleted root-page.
   59104         */
   59105         MemPage *pMove;
   59106         releasePage(pPage);
   59107         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
   59108         if( rc!=SQLITE_OK ){
   59109           return rc;
   59110         }
   59111         rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
   59112         releasePage(pMove);
   59113         if( rc!=SQLITE_OK ){
   59114           return rc;
   59115         }
   59116         pMove = 0;
   59117         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
   59118         freePage(pMove, &rc);
   59119         releasePage(pMove);
   59120         if( rc!=SQLITE_OK ){
   59121           return rc;
   59122         }
   59123         *piMoved = maxRootPgno;
   59124       }
   59125 
   59126       /* Set the new 'max-root-page' value in the database header. This
   59127       ** is the old value less one, less one more if that happens to
   59128       ** be a root-page number, less one again if that is the
   59129       ** PENDING_BYTE_PAGE.
   59130       */
   59131       maxRootPgno--;
   59132       while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
   59133              || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
   59134         maxRootPgno--;
   59135       }
   59136       assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
   59137 
   59138       rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
   59139     }else{
   59140       freePage(pPage, &rc);
   59141       releasePage(pPage);
   59142     }
   59143 #endif
   59144   }else{
   59145     /* If sqlite3BtreeDropTable was called on page 1.
   59146     ** This really never should happen except in a corrupt
   59147     ** database.
   59148     */
   59149     zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
   59150     releasePage(pPage);
   59151   }
   59152   return rc;
   59153 }
   59154 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
   59155   int rc;
   59156   sqlite3BtreeEnter(p);
   59157   rc = btreeDropTable(p, iTable, piMoved);
   59158   sqlite3BtreeLeave(p);
   59159   return rc;
   59160 }
   59161 
   59162 
   59163 /*
   59164 ** This function may only be called if the b-tree connection already
   59165 ** has a read or write transaction open on the database.
   59166 **
   59167 ** Read the meta-information out of a database file.  Meta[0]
   59168 ** is the number of free pages currently in the database.  Meta[1]
   59169 ** through meta[15] are available for use by higher layers.  Meta[0]
   59170 ** is read-only, the others are read/write.
   59171 **
   59172 ** The schema layer numbers meta values differently.  At the schema
   59173 ** layer (and the SetCookie and ReadCookie opcodes) the number of
   59174 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
   59175 */
   59176 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
   59177   BtShared *pBt = p->pBt;
   59178 
   59179   sqlite3BtreeEnter(p);
   59180   assert( p->inTrans>TRANS_NONE );
   59181   assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
   59182   assert( pBt->pPage1 );
   59183   assert( idx>=0 && idx<=15 );
   59184 
   59185   *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
   59186 
   59187   /* If auto-vacuum is disabled in this build and this is an auto-vacuum
   59188   ** database, mark the database as read-only.  */
   59189 #ifdef SQLITE_OMIT_AUTOVACUUM
   59190   if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
   59191     pBt->btsFlags |= BTS_READ_ONLY;
   59192   }
   59193 #endif
   59194 
   59195   sqlite3BtreeLeave(p);
   59196 }
   59197 
   59198 /*
   59199 ** Write meta-information back into the database.  Meta[0] is
   59200 ** read-only and may not be written.
   59201 */
   59202 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
   59203   BtShared *pBt = p->pBt;
   59204   unsigned char *pP1;
   59205   int rc;
   59206   assert( idx>=1 && idx<=15 );
   59207   sqlite3BtreeEnter(p);
   59208   assert( p->inTrans==TRANS_WRITE );
   59209   assert( pBt->pPage1!=0 );
   59210   pP1 = pBt->pPage1->aData;
   59211   rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
   59212   if( rc==SQLITE_OK ){
   59213     put4byte(&pP1[36 + idx*4], iMeta);
   59214 #ifndef SQLITE_OMIT_AUTOVACUUM
   59215     if( idx==BTREE_INCR_VACUUM ){
   59216       assert( pBt->autoVacuum || iMeta==0 );
   59217       assert( iMeta==0 || iMeta==1 );
   59218       pBt->incrVacuum = (u8)iMeta;
   59219     }
   59220 #endif
   59221   }
   59222   sqlite3BtreeLeave(p);
   59223   return rc;
   59224 }
   59225 
   59226 #ifndef SQLITE_OMIT_BTREECOUNT
   59227 /*
   59228 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
   59229 ** number of entries in the b-tree and write the result to *pnEntry.
   59230 **
   59231 ** SQLITE_OK is returned if the operation is successfully executed.
   59232 ** Otherwise, if an error is encountered (i.e. an IO error or database
   59233 ** corruption) an SQLite error code is returned.
   59234 */
   59235 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
   59236   i64 nEntry = 0;                      /* Value to return in *pnEntry */
   59237   int rc;                              /* Return code */
   59238 
   59239   if( pCur->pgnoRoot==0 ){
   59240     *pnEntry = 0;
   59241     return SQLITE_OK;
   59242   }
   59243   rc = moveToRoot(pCur);
   59244 
   59245   /* Unless an error occurs, the following loop runs one iteration for each
   59246   ** page in the B-Tree structure (not including overflow pages).
   59247   */
   59248   while( rc==SQLITE_OK ){
   59249     int iIdx;                          /* Index of child node in parent */
   59250     MemPage *pPage;                    /* Current page of the b-tree */
   59251 
   59252     /* If this is a leaf page or the tree is not an int-key tree, then
   59253     ** this page contains countable entries. Increment the entry counter
   59254     ** accordingly.
   59255     */
   59256     pPage = pCur->apPage[pCur->iPage];
   59257     if( pPage->leaf || !pPage->intKey ){
   59258       nEntry += pPage->nCell;
   59259     }
   59260 
   59261     /* pPage is a leaf node. This loop navigates the cursor so that it
   59262     ** points to the first interior cell that it points to the parent of
   59263     ** the next page in the tree that has not yet been visited. The
   59264     ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
   59265     ** of the page, or to the number of cells in the page if the next page
   59266     ** to visit is the right-child of its parent.
   59267     **
   59268     ** If all pages in the tree have been visited, return SQLITE_OK to the
   59269     ** caller.
   59270     */
   59271     if( pPage->leaf ){
   59272       do {
   59273         if( pCur->iPage==0 ){
   59274           /* All pages of the b-tree have been visited. Return successfully. */
   59275           *pnEntry = nEntry;
   59276           return SQLITE_OK;
   59277         }
   59278         moveToParent(pCur);
   59279       }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
   59280 
   59281       pCur->aiIdx[pCur->iPage]++;
   59282       pPage = pCur->apPage[pCur->iPage];
   59283     }
   59284 
   59285     /* Descend to the child node of the cell that the cursor currently
   59286     ** points at. This is the right-child if (iIdx==pPage->nCell).
   59287     */
   59288     iIdx = pCur->aiIdx[pCur->iPage];
   59289     if( iIdx==pPage->nCell ){
   59290       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
   59291     }else{
   59292       rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
   59293     }
   59294   }
   59295 
   59296   /* An error has occurred. Return an error code. */
   59297   return rc;
   59298 }
   59299 #endif
   59300 
   59301 /*
   59302 ** Return the pager associated with a BTree.  This routine is used for
   59303 ** testing and debugging only.
   59304 */
   59305 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
   59306   return p->pBt->pPager;
   59307 }
   59308 
   59309 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
   59310 /*
   59311 ** Append a message to the error message string.
   59312 */
   59313 static void checkAppendMsg(
   59314   IntegrityCk *pCheck,
   59315   char *zMsg1,
   59316   const char *zFormat,
   59317   ...
   59318 ){
   59319   va_list ap;
   59320   if( !pCheck->mxErr ) return;
   59321   pCheck->mxErr--;
   59322   pCheck->nErr++;
   59323   va_start(ap, zFormat);
   59324   if( pCheck->errMsg.nChar ){
   59325     sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
   59326   }
   59327   if( zMsg1 ){
   59328     sqlite3StrAccumAppendAll(&pCheck->errMsg, zMsg1);
   59329   }
   59330   sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
   59331   va_end(ap);
   59332   if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
   59333     pCheck->mallocFailed = 1;
   59334   }
   59335 }
   59336 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
   59337 
   59338 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
   59339 
   59340 /*
   59341 ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
   59342 ** corresponds to page iPg is already set.
   59343 */
   59344 static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
   59345   assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
   59346   return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
   59347 }
   59348 
   59349 /*
   59350 ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
   59351 */
   59352 static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
   59353   assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
   59354   pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
   59355 }
   59356 
   59357 
   59358 /*
   59359 ** Add 1 to the reference count for page iPage.  If this is the second
   59360 ** reference to the page, add an error message to pCheck->zErrMsg.
   59361 ** Return 1 if there are 2 ore more references to the page and 0 if
   59362 ** if this is the first reference to the page.
   59363 **
   59364 ** Also check that the page number is in bounds.
   59365 */
   59366 static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
   59367   if( iPage==0 ) return 1;
   59368   if( iPage>pCheck->nPage ){
   59369     checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
   59370     return 1;
   59371   }
   59372   if( getPageReferenced(pCheck, iPage) ){
   59373     checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
   59374     return 1;
   59375   }
   59376   setPageReferenced(pCheck, iPage);
   59377   return 0;
   59378 }
   59379 
   59380 #ifndef SQLITE_OMIT_AUTOVACUUM
   59381 /*
   59382 ** Check that the entry in the pointer-map for page iChild maps to
   59383 ** page iParent, pointer type ptrType. If not, append an error message
   59384 ** to pCheck.
   59385 */
   59386 static void checkPtrmap(
   59387   IntegrityCk *pCheck,   /* Integrity check context */
   59388   Pgno iChild,           /* Child page number */
   59389   u8 eType,              /* Expected pointer map type */
   59390   Pgno iParent,          /* Expected pointer map parent page number */
   59391   char *zContext         /* Context description (used for error msg) */
   59392 ){
   59393   int rc;
   59394   u8 ePtrmapType;
   59395   Pgno iPtrmapParent;
   59396 
   59397   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
   59398   if( rc!=SQLITE_OK ){
   59399     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
   59400     checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
   59401     return;
   59402   }
   59403 
   59404   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
   59405     checkAppendMsg(pCheck, zContext,
   59406       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
   59407       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
   59408   }
   59409 }
   59410 #endif
   59411 
   59412 /*
   59413 ** Check the integrity of the freelist or of an overflow page list.
   59414 ** Verify that the number of pages on the list is N.
   59415 */
   59416 static void checkList(
   59417   IntegrityCk *pCheck,  /* Integrity checking context */
   59418   int isFreeList,       /* True for a freelist.  False for overflow page list */
   59419   int iPage,            /* Page number for first page in the list */
   59420   int N,                /* Expected number of pages in the list */
   59421   char *zContext        /* Context for error messages */
   59422 ){
   59423   int i;
   59424   int expected = N;
   59425   int iFirst = iPage;
   59426   while( N-- > 0 && pCheck->mxErr ){
   59427     DbPage *pOvflPage;
   59428     unsigned char *pOvflData;
   59429     if( iPage<1 ){
   59430       checkAppendMsg(pCheck, zContext,
   59431          "%d of %d pages missing from overflow list starting at %d",
   59432           N+1, expected, iFirst);
   59433       break;
   59434     }
   59435     if( checkRef(pCheck, iPage, zContext) ) break;
   59436     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
   59437       checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
   59438       break;
   59439     }
   59440     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
   59441     if( isFreeList ){
   59442       int n = get4byte(&pOvflData[4]);
   59443 #ifndef SQLITE_OMIT_AUTOVACUUM
   59444       if( pCheck->pBt->autoVacuum ){
   59445         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
   59446       }
   59447 #endif
   59448       if( n>(int)pCheck->pBt->usableSize/4-2 ){
   59449         checkAppendMsg(pCheck, zContext,
   59450            "freelist leaf count too big on page %d", iPage);
   59451         N--;
   59452       }else{
   59453         for(i=0; i<n; i++){
   59454           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
   59455 #ifndef SQLITE_OMIT_AUTOVACUUM
   59456           if( pCheck->pBt->autoVacuum ){
   59457             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
   59458           }
   59459 #endif
   59460           checkRef(pCheck, iFreePage, zContext);
   59461         }
   59462         N -= n;
   59463       }
   59464     }
   59465 #ifndef SQLITE_OMIT_AUTOVACUUM
   59466     else{
   59467       /* If this database supports auto-vacuum and iPage is not the last
   59468       ** page in this overflow list, check that the pointer-map entry for
   59469       ** the following page matches iPage.
   59470       */
   59471       if( pCheck->pBt->autoVacuum && N>0 ){
   59472         i = get4byte(pOvflData);
   59473         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
   59474       }
   59475     }
   59476 #endif
   59477     iPage = get4byte(pOvflData);
   59478     sqlite3PagerUnref(pOvflPage);
   59479   }
   59480 }
   59481 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
   59482 
   59483 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
   59484 /*
   59485 ** Do various sanity checks on a single page of a tree.  Return
   59486 ** the tree depth.  Root pages return 0.  Parents of root pages
   59487 ** return 1, and so forth.
   59488 **
   59489 ** These checks are done:
   59490 **
   59491 **      1.  Make sure that cells and freeblocks do not overlap
   59492 **          but combine to completely cover the page.
   59493 **  NO  2.  Make sure cell keys are in order.
   59494 **  NO  3.  Make sure no key is less than or equal to zLowerBound.
   59495 **  NO  4.  Make sure no key is greater than or equal to zUpperBound.
   59496 **      5.  Check the integrity of overflow pages.
   59497 **      6.  Recursively call checkTreePage on all children.
   59498 **      7.  Verify that the depth of all children is the same.
   59499 **      8.  Make sure this page is at least 33% full or else it is
   59500 **          the root of the tree.
   59501 */
   59502 static int checkTreePage(
   59503   IntegrityCk *pCheck,  /* Context for the sanity check */
   59504   int iPage,            /* Page number of the page to check */
   59505   char *zParentContext, /* Parent context */
   59506   i64 *pnParentMinKey,
   59507   i64 *pnParentMaxKey
   59508 ){
   59509   MemPage *pPage;
   59510   int i, rc, depth, d2, pgno, cnt;
   59511   int hdr, cellStart;
   59512   int nCell;
   59513   u8 *data;
   59514   BtShared *pBt;
   59515   int usableSize;
   59516   char zContext[100];
   59517   char *hit = 0;
   59518   i64 nMinKey = 0;
   59519   i64 nMaxKey = 0;
   59520 
   59521   sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
   59522 
   59523   /* Check that the page exists
   59524   */
   59525   pBt = pCheck->pBt;
   59526   usableSize = pBt->usableSize;
   59527   if( iPage==0 ) return 0;
   59528   if( checkRef(pCheck, iPage, zParentContext) ) return 0;
   59529   if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
   59530     checkAppendMsg(pCheck, zContext,
   59531        "unable to get the page. error code=%d", rc);
   59532     return 0;
   59533   }
   59534 
   59535   /* Clear MemPage.isInit to make sure the corruption detection code in
   59536   ** btreeInitPage() is executed.  */
   59537   pPage->isInit = 0;
   59538   if( (rc = btreeInitPage(pPage))!=0 ){
   59539     assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
   59540     checkAppendMsg(pCheck, zContext,
   59541                    "btreeInitPage() returns error code %d", rc);
   59542     releasePage(pPage);
   59543     return 0;
   59544   }
   59545 
   59546   /* Check out all the cells.
   59547   */
   59548   depth = 0;
   59549   for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
   59550     u8 *pCell;
   59551     u32 sz;
   59552     CellInfo info;
   59553 
   59554     /* Check payload overflow pages
   59555     */
   59556     sqlite3_snprintf(sizeof(zContext), zContext,
   59557              "On tree page %d cell %d: ", iPage, i);
   59558     pCell = findCell(pPage,i);
   59559     btreeParseCellPtr(pPage, pCell, &info);
   59560     sz = info.nData;
   59561     if( !pPage->intKey ) sz += (int)info.nKey;
   59562     /* For intKey pages, check that the keys are in order.
   59563     */
   59564     else if( i==0 ) nMinKey = nMaxKey = info.nKey;
   59565     else{
   59566       if( info.nKey <= nMaxKey ){
   59567         checkAppendMsg(pCheck, zContext,
   59568             "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
   59569       }
   59570       nMaxKey = info.nKey;
   59571     }
   59572     assert( sz==info.nPayload );
   59573     if( (sz>info.nLocal)
   59574      && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
   59575     ){
   59576       int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
   59577       Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
   59578 #ifndef SQLITE_OMIT_AUTOVACUUM
   59579       if( pBt->autoVacuum ){
   59580         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
   59581       }
   59582 #endif
   59583       checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
   59584     }
   59585 
   59586     /* Check sanity of left child page.
   59587     */
   59588     if( !pPage->leaf ){
   59589       pgno = get4byte(pCell);
   59590 #ifndef SQLITE_OMIT_AUTOVACUUM
   59591       if( pBt->autoVacuum ){
   59592         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
   59593       }
   59594 #endif
   59595       d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
   59596       if( i>0 && d2!=depth ){
   59597         checkAppendMsg(pCheck, zContext, "Child page depth differs");
   59598       }
   59599       depth = d2;
   59600     }
   59601   }
   59602 
   59603   if( !pPage->leaf ){
   59604     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
   59605     sqlite3_snprintf(sizeof(zContext), zContext,
   59606                      "On page %d at right child: ", iPage);
   59607 #ifndef SQLITE_OMIT_AUTOVACUUM
   59608     if( pBt->autoVacuum ){
   59609       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
   59610     }
   59611 #endif
   59612     checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
   59613   }
   59614 
   59615   /* For intKey leaf pages, check that the min/max keys are in order
   59616   ** with any left/parent/right pages.
   59617   */
   59618   if( pPage->leaf && pPage->intKey ){
   59619     /* if we are a left child page */
   59620     if( pnParentMinKey ){
   59621       /* if we are the left most child page */
   59622       if( !pnParentMaxKey ){
   59623         if( nMaxKey > *pnParentMinKey ){
   59624           checkAppendMsg(pCheck, zContext,
   59625               "Rowid %lld out of order (max larger than parent min of %lld)",
   59626               nMaxKey, *pnParentMinKey);
   59627         }
   59628       }else{
   59629         if( nMinKey <= *pnParentMinKey ){
   59630           checkAppendMsg(pCheck, zContext,
   59631               "Rowid %lld out of order (min less than parent min of %lld)",
   59632               nMinKey, *pnParentMinKey);
   59633         }
   59634         if( nMaxKey > *pnParentMaxKey ){
   59635           checkAppendMsg(pCheck, zContext,
   59636               "Rowid %lld out of order (max larger than parent max of %lld)",
   59637               nMaxKey, *pnParentMaxKey);
   59638         }
   59639         *pnParentMinKey = nMaxKey;
   59640       }
   59641     /* else if we're a right child page */
   59642     } else if( pnParentMaxKey ){
   59643       if( nMinKey <= *pnParentMaxKey ){
   59644         checkAppendMsg(pCheck, zContext,
   59645             "Rowid %lld out of order (min less than parent max of %lld)",
   59646             nMinKey, *pnParentMaxKey);
   59647       }
   59648     }
   59649   }
   59650 
   59651   /* Check for complete coverage of the page
   59652   */
   59653   data = pPage->aData;
   59654   hdr = pPage->hdrOffset;
   59655   hit = sqlite3PageMalloc( pBt->pageSize );
   59656   if( hit==0 ){
   59657     pCheck->mallocFailed = 1;
   59658   }else{
   59659     int contentOffset = get2byteNotZero(&data[hdr+5]);
   59660     assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
   59661     memset(hit+contentOffset, 0, usableSize-contentOffset);
   59662     memset(hit, 1, contentOffset);
   59663     nCell = get2byte(&data[hdr+3]);
   59664     cellStart = hdr + 12 - 4*pPage->leaf;
   59665     for(i=0; i<nCell; i++){
   59666       int pc = get2byte(&data[cellStart+i*2]);
   59667       u32 size = 65536;
   59668       int j;
   59669       if( pc<=usableSize-4 ){
   59670         size = cellSizePtr(pPage, &data[pc]);
   59671       }
   59672       if( (int)(pc+size-1)>=usableSize ){
   59673         checkAppendMsg(pCheck, 0,
   59674             "Corruption detected in cell %d on page %d",i,iPage);
   59675       }else{
   59676         for(j=pc+size-1; j>=pc; j--) hit[j]++;
   59677       }
   59678     }
   59679     i = get2byte(&data[hdr+1]);
   59680     while( i>0 ){
   59681       int size, j;
   59682       assert( i<=usableSize-4 );     /* Enforced by btreeInitPage() */
   59683       size = get2byte(&data[i+2]);
   59684       assert( i+size<=usableSize );  /* Enforced by btreeInitPage() */
   59685       for(j=i+size-1; j>=i; j--) hit[j]++;
   59686       j = get2byte(&data[i]);
   59687       assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
   59688       assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */
   59689       i = j;
   59690     }
   59691     for(i=cnt=0; i<usableSize; i++){
   59692       if( hit[i]==0 ){
   59693         cnt++;
   59694       }else if( hit[i]>1 ){
   59695         checkAppendMsg(pCheck, 0,
   59696           "Multiple uses for byte %d of page %d", i, iPage);
   59697         break;
   59698       }
   59699     }
   59700     if( cnt!=data[hdr+7] ){
   59701       checkAppendMsg(pCheck, 0,
   59702           "Fragmentation of %d bytes reported as %d on page %d",
   59703           cnt, data[hdr+7], iPage);
   59704     }
   59705   }
   59706   sqlite3PageFree(hit);
   59707   releasePage(pPage);
   59708   return depth+1;
   59709 }
   59710 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
   59711 
   59712 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
   59713 /*
   59714 ** This routine does a complete check of the given BTree file.  aRoot[] is
   59715 ** an array of pages numbers were each page number is the root page of
   59716 ** a table.  nRoot is the number of entries in aRoot.
   59717 **
   59718 ** A read-only or read-write transaction must be opened before calling
   59719 ** this function.
   59720 **
   59721 ** Write the number of error seen in *pnErr.  Except for some memory
   59722 ** allocation errors,  an error message held in memory obtained from
   59723 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
   59724 ** returned.  If a memory allocation error occurs, NULL is returned.
   59725 */
   59726 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
   59727   Btree *p,     /* The btree to be checked */
   59728   int *aRoot,   /* An array of root pages numbers for individual trees */
   59729   int nRoot,    /* Number of entries in aRoot[] */
   59730   int mxErr,    /* Stop reporting errors after this many */
   59731   int *pnErr    /* Write number of errors seen to this variable */
   59732 ){
   59733   Pgno i;
   59734   int nRef;
   59735   IntegrityCk sCheck;
   59736   BtShared *pBt = p->pBt;
   59737   char zErr[100];
   59738 
   59739   sqlite3BtreeEnter(p);
   59740   assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
   59741   nRef = sqlite3PagerRefcount(pBt->pPager);
   59742   sCheck.pBt = pBt;
   59743   sCheck.pPager = pBt->pPager;
   59744   sCheck.nPage = btreePagecount(sCheck.pBt);
   59745   sCheck.mxErr = mxErr;
   59746   sCheck.nErr = 0;
   59747   sCheck.mallocFailed = 0;
   59748   *pnErr = 0;
   59749   if( sCheck.nPage==0 ){
   59750     sqlite3BtreeLeave(p);
   59751     return 0;
   59752   }
   59753 
   59754   sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
   59755   if( !sCheck.aPgRef ){
   59756     *pnErr = 1;
   59757     sqlite3BtreeLeave(p);
   59758     return 0;
   59759   }
   59760   i = PENDING_BYTE_PAGE(pBt);
   59761   if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
   59762   sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
   59763   sCheck.errMsg.useMalloc = 2;
   59764 
   59765   /* Check the integrity of the freelist
   59766   */
   59767   checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
   59768             get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
   59769 
   59770   /* Check all the tables.
   59771   */
   59772   for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
   59773     if( aRoot[i]==0 ) continue;
   59774 #ifndef SQLITE_OMIT_AUTOVACUUM
   59775     if( pBt->autoVacuum && aRoot[i]>1 ){
   59776       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
   59777     }
   59778 #endif
   59779     checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
   59780   }
   59781 
   59782   /* Make sure every page in the file is referenced
   59783   */
   59784   for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
   59785 #ifdef SQLITE_OMIT_AUTOVACUUM
   59786     if( getPageReferenced(&sCheck, i)==0 ){
   59787       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
   59788     }
   59789 #else
   59790     /* If the database supports auto-vacuum, make sure no tables contain
   59791     ** references to pointer-map pages.
   59792     */
   59793     if( getPageReferenced(&sCheck, i)==0 &&
   59794        (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
   59795       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
   59796     }
   59797     if( getPageReferenced(&sCheck, i)!=0 &&
   59798        (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
   59799       checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
   59800     }
   59801 #endif
   59802   }
   59803 
   59804   /* Make sure this analysis did not leave any unref() pages.
   59805   ** This is an internal consistency check; an integrity check
   59806   ** of the integrity check.
   59807   */
   59808   if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
   59809     checkAppendMsg(&sCheck, 0,
   59810       "Outstanding page count goes from %d to %d during this analysis",
   59811       nRef, sqlite3PagerRefcount(pBt->pPager)
   59812     );
   59813   }
   59814 
   59815   /* Clean  up and report errors.
   59816   */
   59817   sqlite3BtreeLeave(p);
   59818   sqlite3_free(sCheck.aPgRef);
   59819   if( sCheck.mallocFailed ){
   59820     sqlite3StrAccumReset(&sCheck.errMsg);
   59821     *pnErr = sCheck.nErr+1;
   59822     return 0;
   59823   }
   59824   *pnErr = sCheck.nErr;
   59825   if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
   59826   return sqlite3StrAccumFinish(&sCheck.errMsg);
   59827 }
   59828 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
   59829 
   59830 /*
   59831 ** Return the full pathname of the underlying database file.  Return
   59832 ** an empty string if the database is in-memory or a TEMP database.
   59833 **
   59834 ** The pager filename is invariant as long as the pager is
   59835 ** open so it is safe to access without the BtShared mutex.
   59836 */
   59837 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
   59838   assert( p->pBt->pPager!=0 );
   59839   return sqlite3PagerFilename(p->pBt->pPager, 1);
   59840 }
   59841 
   59842 /*
   59843 ** Return the pathname of the journal file for this database. The return
   59844 ** value of this routine is the same regardless of whether the journal file
   59845 ** has been created or not.
   59846 **
   59847 ** The pager journal filename is invariant as long as the pager is
   59848 ** open so it is safe to access without the BtShared mutex.
   59849 */
   59850 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
   59851   assert( p->pBt->pPager!=0 );
   59852   return sqlite3PagerJournalname(p->pBt->pPager);
   59853 }
   59854 
   59855 /*
   59856 ** Return non-zero if a transaction is active.
   59857 */
   59858 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
   59859   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
   59860   return (p && (p->inTrans==TRANS_WRITE));
   59861 }
   59862 
   59863 #ifndef SQLITE_OMIT_WAL
   59864 /*
   59865 ** Run a checkpoint on the Btree passed as the first argument.
   59866 **
   59867 ** Return SQLITE_LOCKED if this or any other connection has an open
   59868 ** transaction on the shared-cache the argument Btree is connected to.
   59869 **
   59870 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
   59871 */
   59872 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
   59873   int rc = SQLITE_OK;
   59874   if( p ){
   59875     BtShared *pBt = p->pBt;
   59876     sqlite3BtreeEnter(p);
   59877     if( pBt->inTransaction!=TRANS_NONE ){
   59878       rc = SQLITE_LOCKED;
   59879     }else{
   59880       rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
   59881     }
   59882     sqlite3BtreeLeave(p);
   59883   }
   59884   return rc;
   59885 }
   59886 #endif
   59887 
   59888 /*
   59889 ** Return non-zero if a read (or write) transaction is active.
   59890 */
   59891 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
   59892   assert( p );
   59893   assert( sqlite3_mutex_held(p->db->mutex) );
   59894   return p->inTrans!=TRANS_NONE;
   59895 }
   59896 
   59897 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
   59898   assert( p );
   59899   assert( sqlite3_mutex_held(p->db->mutex) );
   59900   return p->nBackup!=0;
   59901 }
   59902 
   59903 /*
   59904 ** This function returns a pointer to a blob of memory associated with
   59905 ** a single shared-btree. The memory is used by client code for its own
   59906 ** purposes (for example, to store a high-level schema associated with
   59907 ** the shared-btree). The btree layer manages reference counting issues.
   59908 **
   59909 ** The first time this is called on a shared-btree, nBytes bytes of memory
   59910 ** are allocated, zeroed, and returned to the caller. For each subsequent
   59911 ** call the nBytes parameter is ignored and a pointer to the same blob
   59912 ** of memory returned.
   59913 **
   59914 ** If the nBytes parameter is 0 and the blob of memory has not yet been
   59915 ** allocated, a null pointer is returned. If the blob has already been
   59916 ** allocated, it is returned as normal.
   59917 **
   59918 ** Just before the shared-btree is closed, the function passed as the
   59919 ** xFree argument when the memory allocation was made is invoked on the
   59920 ** blob of allocated memory. The xFree function should not call sqlite3_free()
   59921 ** on the memory, the btree layer does that.
   59922 */
   59923 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
   59924   BtShared *pBt = p->pBt;
   59925   sqlite3BtreeEnter(p);
   59926   if( !pBt->pSchema && nBytes ){
   59927     pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
   59928     pBt->xFreeSchema = xFree;
   59929   }
   59930   sqlite3BtreeLeave(p);
   59931   return pBt->pSchema;
   59932 }
   59933 
   59934 /*
   59935 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
   59936 ** btree as the argument handle holds an exclusive lock on the
   59937 ** sqlite_master table. Otherwise SQLITE_OK.
   59938 */
   59939 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
   59940   int rc;
   59941   assert( sqlite3_mutex_held(p->db->mutex) );
   59942   sqlite3BtreeEnter(p);
   59943   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
   59944   assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
   59945   sqlite3BtreeLeave(p);
   59946   return rc;
   59947 }
   59948 
   59949 
   59950 #ifndef SQLITE_OMIT_SHARED_CACHE
   59951 /*
   59952 ** Obtain a lock on the table whose root page is iTab.  The
   59953 ** lock is a write lock if isWritelock is true or a read lock
   59954 ** if it is false.
   59955 */
   59956 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
   59957   int rc = SQLITE_OK;
   59958   assert( p->inTrans!=TRANS_NONE );
   59959   if( p->sharable ){
   59960     u8 lockType = READ_LOCK + isWriteLock;
   59961     assert( READ_LOCK+1==WRITE_LOCK );
   59962     assert( isWriteLock==0 || isWriteLock==1 );
   59963 
   59964     sqlite3BtreeEnter(p);
   59965     rc = querySharedCacheTableLock(p, iTab, lockType);
   59966     if( rc==SQLITE_OK ){
   59967       rc = setSharedCacheTableLock(p, iTab, lockType);
   59968     }
   59969     sqlite3BtreeLeave(p);
   59970   }
   59971   return rc;
   59972 }
   59973 #endif
   59974 
   59975 #ifndef SQLITE_OMIT_INCRBLOB
   59976 /*
   59977 ** Argument pCsr must be a cursor opened for writing on an
   59978 ** INTKEY table currently pointing at a valid table entry.
   59979 ** This function modifies the data stored as part of that entry.
   59980 **
   59981 ** Only the data content may only be modified, it is not possible to
   59982 ** change the length of the data stored. If this function is called with
   59983 ** parameters that attempt to write past the end of the existing data,
   59984 ** no modifications are made and SQLITE_CORRUPT is returned.
   59985 */
   59986 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
   59987   int rc;
   59988   assert( cursorHoldsMutex(pCsr) );
   59989   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
   59990   assert( pCsr->curFlags & BTCF_Incrblob );
   59991 
   59992   rc = restoreCursorPosition(pCsr);
   59993   if( rc!=SQLITE_OK ){
   59994     return rc;
   59995   }
   59996   assert( pCsr->eState!=CURSOR_REQUIRESEEK );
   59997   if( pCsr->eState!=CURSOR_VALID ){
   59998     return SQLITE_ABORT;
   59999   }
   60000 
   60001   /* Save the positions of all other cursors open on this table. This is
   60002   ** required in case any of them are holding references to an xFetch
   60003   ** version of the b-tree page modified by the accessPayload call below.
   60004   **
   60005   ** Note that pCsr must be open on a BTREE_INTKEY table and saveCursorPosition()
   60006   ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
   60007   ** saveAllCursors can only return SQLITE_OK.
   60008   */
   60009   VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
   60010   assert( rc==SQLITE_OK );
   60011 
   60012   /* Check some assumptions:
   60013   **   (a) the cursor is open for writing,
   60014   **   (b) there is a read/write transaction open,
   60015   **   (c) the connection holds a write-lock on the table (if required),
   60016   **   (d) there are no conflicting read-locks, and
   60017   **   (e) the cursor points at a valid row of an intKey table.
   60018   */
   60019   if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
   60020     return SQLITE_READONLY;
   60021   }
   60022   assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
   60023               && pCsr->pBt->inTransaction==TRANS_WRITE );
   60024   assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
   60025   assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
   60026   assert( pCsr->apPage[pCsr->iPage]->intKey );
   60027 
   60028   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
   60029 }
   60030 
   60031 /*
   60032 ** Mark this cursor as an incremental blob cursor.
   60033 */
   60034 SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
   60035   pCur->curFlags |= BTCF_Incrblob;
   60036 }
   60037 #endif
   60038 
   60039 /*
   60040 ** Set both the "read version" (single byte at byte offset 18) and
   60041 ** "write version" (single byte at byte offset 19) fields in the database
   60042 ** header to iVersion.
   60043 */
   60044 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
   60045   BtShared *pBt = pBtree->pBt;
   60046   int rc;                         /* Return code */
   60047 
   60048   assert( iVersion==1 || iVersion==2 );
   60049 
   60050   /* If setting the version fields to 1, do not automatically open the
   60051   ** WAL connection, even if the version fields are currently set to 2.
   60052   */
   60053   pBt->btsFlags &= ~BTS_NO_WAL;
   60054   if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
   60055 
   60056   rc = sqlite3BtreeBeginTrans(pBtree, 0);
   60057   if( rc==SQLITE_OK ){
   60058     u8 *aData = pBt->pPage1->aData;
   60059     if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
   60060       rc = sqlite3BtreeBeginTrans(pBtree, 2);
   60061       if( rc==SQLITE_OK ){
   60062         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
   60063         if( rc==SQLITE_OK ){
   60064           aData[18] = (u8)iVersion;
   60065           aData[19] = (u8)iVersion;
   60066         }
   60067       }
   60068     }
   60069   }
   60070 
   60071   pBt->btsFlags &= ~BTS_NO_WAL;
   60072   return rc;
   60073 }
   60074 
   60075 /*
   60076 ** set the mask of hint flags for cursor pCsr. Currently the only valid
   60077 ** values are 0 and BTREE_BULKLOAD.
   60078 */
   60079 SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *pCsr, unsigned int mask){
   60080   assert( mask==BTREE_BULKLOAD || mask==0 );
   60081   pCsr->hints = mask;
   60082 }
   60083 
   60084 /*
   60085 ** Return true if the given Btree is read-only.
   60086 */
   60087 SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *p){
   60088   return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
   60089 }
   60090 
   60091 /************** End of btree.c ***********************************************/
   60092 /************** Begin file backup.c ******************************************/
   60093 /*
   60094 ** 2009 January 28
   60095 **
   60096 ** The author disclaims copyright to this source code.  In place of
   60097 ** a legal notice, here is a blessing:
   60098 **
   60099 **    May you do good and not evil.
   60100 **    May you find forgiveness for yourself and forgive others.
   60101 **    May you share freely, never taking more than you give.
   60102 **
   60103 *************************************************************************
   60104 ** This file contains the implementation of the sqlite3_backup_XXX()
   60105 ** API functions and the related features.
   60106 */
   60107 
   60108 /*
   60109 ** Structure allocated for each backup operation.
   60110 */
   60111 struct sqlite3_backup {
   60112   sqlite3* pDestDb;        /* Destination database handle */
   60113   Btree *pDest;            /* Destination b-tree file */
   60114   u32 iDestSchema;         /* Original schema cookie in destination */
   60115   int bDestLocked;         /* True once a write-transaction is open on pDest */
   60116 
   60117   Pgno iNext;              /* Page number of the next source page to copy */
   60118   sqlite3* pSrcDb;         /* Source database handle */
   60119   Btree *pSrc;             /* Source b-tree file */
   60120 
   60121   int rc;                  /* Backup process error code */
   60122 
   60123   /* These two variables are set by every call to backup_step(). They are
   60124   ** read by calls to backup_remaining() and backup_pagecount().
   60125   */
   60126   Pgno nRemaining;         /* Number of pages left to copy */
   60127   Pgno nPagecount;         /* Total number of pages to copy */
   60128 
   60129   int isAttached;          /* True once backup has been registered with pager */
   60130   sqlite3_backup *pNext;   /* Next backup associated with source pager */
   60131 };
   60132 
   60133 /*
   60134 ** THREAD SAFETY NOTES:
   60135 **
   60136 **   Once it has been created using backup_init(), a single sqlite3_backup
   60137 **   structure may be accessed via two groups of thread-safe entry points:
   60138 **
   60139 **     * Via the sqlite3_backup_XXX() API function backup_step() and
   60140 **       backup_finish(). Both these functions obtain the source database
   60141 **       handle mutex and the mutex associated with the source BtShared
   60142 **       structure, in that order.
   60143 **
   60144 **     * Via the BackupUpdate() and BackupRestart() functions, which are
   60145 **       invoked by the pager layer to report various state changes in
   60146 **       the page cache associated with the source database. The mutex
   60147 **       associated with the source database BtShared structure will always
   60148 **       be held when either of these functions are invoked.
   60149 **
   60150 **   The other sqlite3_backup_XXX() API functions, backup_remaining() and
   60151 **   backup_pagecount() are not thread-safe functions. If they are called
   60152 **   while some other thread is calling backup_step() or backup_finish(),
   60153 **   the values returned may be invalid. There is no way for a call to
   60154 **   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
   60155 **   or backup_pagecount().
   60156 **
   60157 **   Depending on the SQLite configuration, the database handles and/or
   60158 **   the Btree objects may have their own mutexes that require locking.
   60159 **   Non-sharable Btrees (in-memory databases for example), do not have
   60160 **   associated mutexes.
   60161 */
   60162 
   60163 /*
   60164 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
   60165 ** in connection handle pDb. If such a database cannot be found, return
   60166 ** a NULL pointer and write an error message to pErrorDb.
   60167 **
   60168 ** If the "temp" database is requested, it may need to be opened by this
   60169 ** function. If an error occurs while doing so, return 0 and write an
   60170 ** error message to pErrorDb.
   60171 */
   60172 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
   60173   int i = sqlite3FindDbName(pDb, zDb);
   60174 
   60175   if( i==1 ){
   60176     Parse *pParse;
   60177     int rc = 0;
   60178     pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
   60179     if( pParse==0 ){
   60180       sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
   60181       rc = SQLITE_NOMEM;
   60182     }else{
   60183       pParse->db = pDb;
   60184       if( sqlite3OpenTempDatabase(pParse) ){
   60185         sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
   60186         rc = SQLITE_ERROR;
   60187       }
   60188       sqlite3DbFree(pErrorDb, pParse->zErrMsg);
   60189       sqlite3ParserReset(pParse);
   60190       sqlite3StackFree(pErrorDb, pParse);
   60191     }
   60192     if( rc ){
   60193       return 0;
   60194     }
   60195   }
   60196 
   60197   if( i<0 ){
   60198     sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
   60199     return 0;
   60200   }
   60201 
   60202   return pDb->aDb[i].pBt;
   60203 }
   60204 
   60205 /*
   60206 ** Attempt to set the page size of the destination to match the page size
   60207 ** of the source.
   60208 */
   60209 static int setDestPgsz(sqlite3_backup *p){
   60210   int rc;
   60211   rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
   60212   return rc;
   60213 }
   60214 
   60215 /*
   60216 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
   60217 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
   60218 ** a pointer to the new sqlite3_backup object.
   60219 **
   60220 ** If an error occurs, NULL is returned and an error code and error message
   60221 ** stored in database handle pDestDb.
   60222 */
   60223 SQLITE_API sqlite3_backup *sqlite3_backup_init(
   60224   sqlite3* pDestDb,                     /* Database to write to */
   60225   const char *zDestDb,                  /* Name of database within pDestDb */
   60226   sqlite3* pSrcDb,                      /* Database connection to read from */
   60227   const char *zSrcDb                    /* Name of database within pSrcDb */
   60228 ){
   60229   sqlite3_backup *p;                    /* Value to return */
   60230 
   60231   /* Lock the source database handle. The destination database
   60232   ** handle is not locked in this routine, but it is locked in
   60233   ** sqlite3_backup_step(). The user is required to ensure that no
   60234   ** other thread accesses the destination handle for the duration
   60235   ** of the backup operation.  Any attempt to use the destination
   60236   ** database connection while a backup is in progress may cause
   60237   ** a malfunction or a deadlock.
   60238   */
   60239   sqlite3_mutex_enter(pSrcDb->mutex);
   60240   sqlite3_mutex_enter(pDestDb->mutex);
   60241 
   60242   if( pSrcDb==pDestDb ){
   60243     sqlite3Error(
   60244         pDestDb, SQLITE_ERROR, "source and destination must be distinct"
   60245     );
   60246     p = 0;
   60247   }else {
   60248     /* Allocate space for a new sqlite3_backup object...
   60249     ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
   60250     ** call to sqlite3_backup_init() and is destroyed by a call to
   60251     ** sqlite3_backup_finish(). */
   60252     p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
   60253     if( !p ){
   60254       sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
   60255     }
   60256   }
   60257 
   60258   /* If the allocation succeeded, populate the new object. */
   60259   if( p ){
   60260     p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
   60261     p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
   60262     p->pDestDb = pDestDb;
   60263     p->pSrcDb = pSrcDb;
   60264     p->iNext = 1;
   60265     p->isAttached = 0;
   60266 
   60267     if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){
   60268       /* One (or both) of the named databases did not exist or an OOM
   60269       ** error was hit.  The error has already been written into the
   60270       ** pDestDb handle.  All that is left to do here is free the
   60271       ** sqlite3_backup structure.
   60272       */
   60273       sqlite3_free(p);
   60274       p = 0;
   60275     }
   60276   }
   60277   if( p ){
   60278     p->pSrc->nBackup++;
   60279   }
   60280 
   60281   sqlite3_mutex_leave(pDestDb->mutex);
   60282   sqlite3_mutex_leave(pSrcDb->mutex);
   60283   return p;
   60284 }
   60285 
   60286 /*
   60287 ** Argument rc is an SQLite error code. Return true if this error is
   60288 ** considered fatal if encountered during a backup operation. All errors
   60289 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
   60290 */
   60291 static int isFatalError(int rc){
   60292   return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
   60293 }
   60294 
   60295 /*
   60296 ** Parameter zSrcData points to a buffer containing the data for
   60297 ** page iSrcPg from the source database. Copy this data into the
   60298 ** destination database.
   60299 */
   60300 static int backupOnePage(
   60301   sqlite3_backup *p,              /* Backup handle */
   60302   Pgno iSrcPg,                    /* Source database page to backup */
   60303   const u8 *zSrcData,             /* Source database page data */
   60304   int bUpdate                     /* True for an update, false otherwise */
   60305 ){
   60306   Pager * const pDestPager = sqlite3BtreePager(p->pDest);
   60307   const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
   60308   int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
   60309   const int nCopy = MIN(nSrcPgsz, nDestPgsz);
   60310   const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
   60311 #ifdef SQLITE_HAS_CODEC
   60312   /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
   60313   ** guaranteed that the shared-mutex is held by this thread, handle
   60314   ** p->pSrc may not actually be the owner.  */
   60315   int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
   60316   int nDestReserve = sqlite3BtreeGetReserve(p->pDest);
   60317 #endif
   60318   int rc = SQLITE_OK;
   60319   i64 iOff;
   60320 
   60321   assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
   60322   assert( p->bDestLocked );
   60323   assert( !isFatalError(p->rc) );
   60324   assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
   60325   assert( zSrcData );
   60326 
   60327   /* Catch the case where the destination is an in-memory database and the
   60328   ** page sizes of the source and destination differ.
   60329   */
   60330   if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
   60331     rc = SQLITE_READONLY;
   60332   }
   60333 
   60334 #ifdef SQLITE_HAS_CODEC
   60335   /* Backup is not possible if the page size of the destination is changing
   60336   ** and a codec is in use.
   60337   */
   60338   if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
   60339     rc = SQLITE_READONLY;
   60340   }
   60341 
   60342   /* Backup is not possible if the number of bytes of reserve space differ
   60343   ** between source and destination.  If there is a difference, try to
   60344   ** fix the destination to agree with the source.  If that is not possible,
   60345   ** then the backup cannot proceed.
   60346   */
   60347   if( nSrcReserve!=nDestReserve ){
   60348     u32 newPgsz = nSrcPgsz;
   60349     rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
   60350     if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
   60351   }
   60352 #endif
   60353 
   60354   /* This loop runs once for each destination page spanned by the source
   60355   ** page. For each iteration, variable iOff is set to the byte offset
   60356   ** of the destination page.
   60357   */
   60358   for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
   60359     DbPage *pDestPg = 0;
   60360     Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
   60361     if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
   60362     if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
   60363      && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
   60364     ){
   60365       const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
   60366       u8 *zDestData = sqlite3PagerGetData(pDestPg);
   60367       u8 *zOut = &zDestData[iOff%nDestPgsz];
   60368 
   60369       /* Copy the data from the source page into the destination page.
   60370       ** Then clear the Btree layer MemPage.isInit flag. Both this module
   60371       ** and the pager code use this trick (clearing the first byte
   60372       ** of the page 'extra' space to invalidate the Btree layers
   60373       ** cached parse of the page). MemPage.isInit is marked
   60374       ** "MUST BE FIRST" for this purpose.
   60375       */
   60376       memcpy(zOut, zIn, nCopy);
   60377       ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
   60378       if( iOff==0 && bUpdate==0 ){
   60379         sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
   60380       }
   60381     }
   60382     sqlite3PagerUnref(pDestPg);
   60383   }
   60384 
   60385   return rc;
   60386 }
   60387 
   60388 /*
   60389 ** If pFile is currently larger than iSize bytes, then truncate it to
   60390 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
   60391 ** this function is a no-op.
   60392 **
   60393 ** Return SQLITE_OK if everything is successful, or an SQLite error
   60394 ** code if an error occurs.
   60395 */
   60396 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
   60397   i64 iCurrent;
   60398   int rc = sqlite3OsFileSize(pFile, &iCurrent);
   60399   if( rc==SQLITE_OK && iCurrent>iSize ){
   60400     rc = sqlite3OsTruncate(pFile, iSize);
   60401   }
   60402   return rc;
   60403 }
   60404 
   60405 /*
   60406 ** Register this backup object with the associated source pager for
   60407 ** callbacks when pages are changed or the cache invalidated.
   60408 */
   60409 static void attachBackupObject(sqlite3_backup *p){
   60410   sqlite3_backup **pp;
   60411   assert( sqlite3BtreeHoldsMutex(p->pSrc) );
   60412   pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
   60413   p->pNext = *pp;
   60414   *pp = p;
   60415   p->isAttached = 1;
   60416 }
   60417 
   60418 /*
   60419 ** Copy nPage pages from the source b-tree to the destination.
   60420 */
   60421 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
   60422   int rc;
   60423   int destMode;       /* Destination journal mode */
   60424   int pgszSrc = 0;    /* Source page size */
   60425   int pgszDest = 0;   /* Destination page size */
   60426 
   60427   sqlite3_mutex_enter(p->pSrcDb->mutex);
   60428   sqlite3BtreeEnter(p->pSrc);
   60429   if( p->pDestDb ){
   60430     sqlite3_mutex_enter(p->pDestDb->mutex);
   60431   }
   60432 
   60433   rc = p->rc;
   60434   if( !isFatalError(rc) ){
   60435     Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
   60436     Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
   60437     int ii;                            /* Iterator variable */
   60438     int nSrcPage = -1;                 /* Size of source db in pages */
   60439     int bCloseTrans = 0;               /* True if src db requires unlocking */
   60440 
   60441     /* If the source pager is currently in a write-transaction, return
   60442     ** SQLITE_BUSY immediately.
   60443     */
   60444     if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
   60445       rc = SQLITE_BUSY;
   60446     }else{
   60447       rc = SQLITE_OK;
   60448     }
   60449 
   60450     /* Lock the destination database, if it is not locked already. */
   60451     if( SQLITE_OK==rc && p->bDestLocked==0
   60452      && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
   60453     ){
   60454       p->bDestLocked = 1;
   60455       sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
   60456     }
   60457 
   60458     /* If there is no open read-transaction on the source database, open
   60459     ** one now. If a transaction is opened here, then it will be closed
   60460     ** before this function exits.
   60461     */
   60462     if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
   60463       rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
   60464       bCloseTrans = 1;
   60465     }
   60466 
   60467     /* Do not allow backup if the destination database is in WAL mode
   60468     ** and the page sizes are different between source and destination */
   60469     pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
   60470     pgszDest = sqlite3BtreeGetPageSize(p->pDest);
   60471     destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
   60472     if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
   60473       rc = SQLITE_READONLY;
   60474     }
   60475 
   60476     /* Now that there is a read-lock on the source database, query the
   60477     ** source pager for the number of pages in the database.
   60478     */
   60479     nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
   60480     assert( nSrcPage>=0 );
   60481     for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
   60482       const Pgno iSrcPg = p->iNext;                 /* Source page number */
   60483       if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
   60484         DbPage *pSrcPg;                             /* Source page object */
   60485         rc = sqlite3PagerAcquire(pSrcPager, iSrcPg, &pSrcPg,
   60486                                  PAGER_GET_READONLY);
   60487         if( rc==SQLITE_OK ){
   60488           rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
   60489           sqlite3PagerUnref(pSrcPg);
   60490         }
   60491       }
   60492       p->iNext++;
   60493     }
   60494     if( rc==SQLITE_OK ){
   60495       p->nPagecount = nSrcPage;
   60496       p->nRemaining = nSrcPage+1-p->iNext;
   60497       if( p->iNext>(Pgno)nSrcPage ){
   60498         rc = SQLITE_DONE;
   60499       }else if( !p->isAttached ){
   60500         attachBackupObject(p);
   60501       }
   60502     }
   60503 
   60504     /* Update the schema version field in the destination database. This
   60505     ** is to make sure that the schema-version really does change in
   60506     ** the case where the source and destination databases have the
   60507     ** same schema version.
   60508     */
   60509     if( rc==SQLITE_DONE ){
   60510       if( nSrcPage==0 ){
   60511         rc = sqlite3BtreeNewDb(p->pDest);
   60512         nSrcPage = 1;
   60513       }
   60514       if( rc==SQLITE_OK || rc==SQLITE_DONE ){
   60515         rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
   60516       }
   60517       if( rc==SQLITE_OK ){
   60518         if( p->pDestDb ){
   60519           sqlite3ResetAllSchemasOfConnection(p->pDestDb);
   60520         }
   60521         if( destMode==PAGER_JOURNALMODE_WAL ){
   60522           rc = sqlite3BtreeSetVersion(p->pDest, 2);
   60523         }
   60524       }
   60525       if( rc==SQLITE_OK ){
   60526         int nDestTruncate;
   60527         /* Set nDestTruncate to the final number of pages in the destination
   60528         ** database. The complication here is that the destination page
   60529         ** size may be different to the source page size.
   60530         **
   60531         ** If the source page size is smaller than the destination page size,
   60532         ** round up. In this case the call to sqlite3OsTruncate() below will
   60533         ** fix the size of the file. However it is important to call
   60534         ** sqlite3PagerTruncateImage() here so that any pages in the
   60535         ** destination file that lie beyond the nDestTruncate page mark are
   60536         ** journalled by PagerCommitPhaseOne() before they are destroyed
   60537         ** by the file truncation.
   60538         */
   60539         assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
   60540         assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
   60541         if( pgszSrc<pgszDest ){
   60542           int ratio = pgszDest/pgszSrc;
   60543           nDestTruncate = (nSrcPage+ratio-1)/ratio;
   60544           if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
   60545             nDestTruncate--;
   60546           }
   60547         }else{
   60548           nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
   60549         }
   60550         assert( nDestTruncate>0 );
   60551 
   60552         if( pgszSrc<pgszDest ){
   60553           /* If the source page-size is smaller than the destination page-size,
   60554           ** two extra things may need to happen:
   60555           **
   60556           **   * The destination may need to be truncated, and
   60557           **
   60558           **   * Data stored on the pages immediately following the
   60559           **     pending-byte page in the source database may need to be
   60560           **     copied into the destination database.
   60561           */
   60562           const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
   60563           sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
   60564           Pgno iPg;
   60565           int nDstPage;
   60566           i64 iOff;
   60567           i64 iEnd;
   60568 
   60569           assert( pFile );
   60570           assert( nDestTruncate==0
   60571               || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
   60572                 nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
   60573              && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
   60574           ));
   60575 
   60576           /* This block ensures that all data required to recreate the original
   60577           ** database has been stored in the journal for pDestPager and the
   60578           ** journal synced to disk. So at this point we may safely modify
   60579           ** the database file in any way, knowing that if a power failure
   60580           ** occurs, the original database will be reconstructed from the
   60581           ** journal file.  */
   60582           sqlite3PagerPagecount(pDestPager, &nDstPage);
   60583           for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
   60584             if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
   60585               DbPage *pPg;
   60586               rc = sqlite3PagerGet(pDestPager, iPg, &pPg);
   60587               if( rc==SQLITE_OK ){
   60588                 rc = sqlite3PagerWrite(pPg);
   60589                 sqlite3PagerUnref(pPg);
   60590               }
   60591             }
   60592           }
   60593           if( rc==SQLITE_OK ){
   60594             rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
   60595           }
   60596 
   60597           /* Write the extra pages and truncate the database file as required */
   60598           iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
   60599           for(
   60600             iOff=PENDING_BYTE+pgszSrc;
   60601             rc==SQLITE_OK && iOff<iEnd;
   60602             iOff+=pgszSrc
   60603           ){
   60604             PgHdr *pSrcPg = 0;
   60605             const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
   60606             rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
   60607             if( rc==SQLITE_OK ){
   60608               u8 *zData = sqlite3PagerGetData(pSrcPg);
   60609               rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
   60610             }
   60611             sqlite3PagerUnref(pSrcPg);
   60612           }
   60613           if( rc==SQLITE_OK ){
   60614             rc = backupTruncateFile(pFile, iSize);
   60615           }
   60616 
   60617           /* Sync the database file to disk. */
   60618           if( rc==SQLITE_OK ){
   60619             rc = sqlite3PagerSync(pDestPager, 0);
   60620           }
   60621         }else{
   60622           sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
   60623           rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
   60624         }
   60625 
   60626         /* Finish committing the transaction to the destination database. */
   60627         if( SQLITE_OK==rc
   60628          && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
   60629         ){
   60630           rc = SQLITE_DONE;
   60631         }
   60632       }
   60633     }
   60634 
   60635     /* If bCloseTrans is true, then this function opened a read transaction
   60636     ** on the source database. Close the read transaction here. There is
   60637     ** no need to check the return values of the btree methods here, as
   60638     ** "committing" a read-only transaction cannot fail.
   60639     */
   60640     if( bCloseTrans ){
   60641       TESTONLY( int rc2 );
   60642       TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
   60643       TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
   60644       assert( rc2==SQLITE_OK );
   60645     }
   60646 
   60647     if( rc==SQLITE_IOERR_NOMEM ){
   60648       rc = SQLITE_NOMEM;
   60649     }
   60650     p->rc = rc;
   60651   }
   60652   if( p->pDestDb ){
   60653     sqlite3_mutex_leave(p->pDestDb->mutex);
   60654   }
   60655   sqlite3BtreeLeave(p->pSrc);
   60656   sqlite3_mutex_leave(p->pSrcDb->mutex);
   60657   return rc;
   60658 }
   60659 
   60660 /*
   60661 ** Release all resources associated with an sqlite3_backup* handle.
   60662 */
   60663 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
   60664   sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
   60665   sqlite3 *pSrcDb;                     /* Source database connection */
   60666   int rc;                              /* Value to return */
   60667 
   60668   /* Enter the mutexes */
   60669   if( p==0 ) return SQLITE_OK;
   60670   pSrcDb = p->pSrcDb;
   60671   sqlite3_mutex_enter(pSrcDb->mutex);
   60672   sqlite3BtreeEnter(p->pSrc);
   60673   if( p->pDestDb ){
   60674     sqlite3_mutex_enter(p->pDestDb->mutex);
   60675   }
   60676 
   60677   /* Detach this backup from the source pager. */
   60678   if( p->pDestDb ){
   60679     p->pSrc->nBackup--;
   60680   }
   60681   if( p->isAttached ){
   60682     pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
   60683     while( *pp!=p ){
   60684       pp = &(*pp)->pNext;
   60685     }
   60686     *pp = p->pNext;
   60687   }
   60688 
   60689   /* If a transaction is still open on the Btree, roll it back. */
   60690   sqlite3BtreeRollback(p->pDest, SQLITE_OK);
   60691 
   60692   /* Set the error code of the destination database handle. */
   60693   rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
   60694   if( p->pDestDb ){
   60695     sqlite3Error(p->pDestDb, rc, 0);
   60696 
   60697     /* Exit the mutexes and free the backup context structure. */
   60698     sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
   60699   }
   60700   sqlite3BtreeLeave(p->pSrc);
   60701   if( p->pDestDb ){
   60702     /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
   60703     ** call to sqlite3_backup_init() and is destroyed by a call to
   60704     ** sqlite3_backup_finish(). */
   60705     sqlite3_free(p);
   60706   }
   60707   sqlite3LeaveMutexAndCloseZombie(pSrcDb);
   60708   return rc;
   60709 }
   60710 
   60711 /*
   60712 ** Return the number of pages still to be backed up as of the most recent
   60713 ** call to sqlite3_backup_step().
   60714 */
   60715 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
   60716   return p->nRemaining;
   60717 }
   60718 
   60719 /*
   60720 ** Return the total number of pages in the source database as of the most
   60721 ** recent call to sqlite3_backup_step().
   60722 */
   60723 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
   60724   return p->nPagecount;
   60725 }
   60726 
   60727 /*
   60728 ** This function is called after the contents of page iPage of the
   60729 ** source database have been modified. If page iPage has already been
   60730 ** copied into the destination database, then the data written to the
   60731 ** destination is now invalidated. The destination copy of iPage needs
   60732 ** to be updated with the new data before the backup operation is
   60733 ** complete.
   60734 **
   60735 ** It is assumed that the mutex associated with the BtShared object
   60736 ** corresponding to the source database is held when this function is
   60737 ** called.
   60738 */
   60739 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
   60740   sqlite3_backup *p;                   /* Iterator variable */
   60741   for(p=pBackup; p; p=p->pNext){
   60742     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
   60743     if( !isFatalError(p->rc) && iPage<p->iNext ){
   60744       /* The backup process p has already copied page iPage. But now it
   60745       ** has been modified by a transaction on the source pager. Copy
   60746       ** the new data into the backup.
   60747       */
   60748       int rc;
   60749       assert( p->pDestDb );
   60750       sqlite3_mutex_enter(p->pDestDb->mutex);
   60751       rc = backupOnePage(p, iPage, aData, 1);
   60752       sqlite3_mutex_leave(p->pDestDb->mutex);
   60753       assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
   60754       if( rc!=SQLITE_OK ){
   60755         p->rc = rc;
   60756       }
   60757     }
   60758   }
   60759 }
   60760 
   60761 /*
   60762 ** Restart the backup process. This is called when the pager layer
   60763 ** detects that the database has been modified by an external database
   60764 ** connection. In this case there is no way of knowing which of the
   60765 ** pages that have been copied into the destination database are still
   60766 ** valid and which are not, so the entire process needs to be restarted.
   60767 **
   60768 ** It is assumed that the mutex associated with the BtShared object
   60769 ** corresponding to the source database is held when this function is
   60770 ** called.
   60771 */
   60772 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
   60773   sqlite3_backup *p;                   /* Iterator variable */
   60774   for(p=pBackup; p; p=p->pNext){
   60775     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
   60776     p->iNext = 1;
   60777   }
   60778 }
   60779 
   60780 #ifndef SQLITE_OMIT_VACUUM
   60781 /*
   60782 ** Copy the complete content of pBtFrom into pBtTo.  A transaction
   60783 ** must be active for both files.
   60784 **
   60785 ** The size of file pTo may be reduced by this operation. If anything
   60786 ** goes wrong, the transaction on pTo is rolled back. If successful, the
   60787 ** transaction is committed before returning.
   60788 */
   60789 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
   60790   int rc;
   60791   sqlite3_file *pFd;              /* File descriptor for database pTo */
   60792   sqlite3_backup b;
   60793   sqlite3BtreeEnter(pTo);
   60794   sqlite3BtreeEnter(pFrom);
   60795 
   60796   assert( sqlite3BtreeIsInTrans(pTo) );
   60797   pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
   60798   if( pFd->pMethods ){
   60799     i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
   60800     rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
   60801     if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
   60802     if( rc ) goto copy_finished;
   60803   }
   60804 
   60805   /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
   60806   ** to 0. This is used by the implementations of sqlite3_backup_step()
   60807   ** and sqlite3_backup_finish() to detect that they are being called
   60808   ** from this function, not directly by the user.
   60809   */
   60810   memset(&b, 0, sizeof(b));
   60811   b.pSrcDb = pFrom->db;
   60812   b.pSrc = pFrom;
   60813   b.pDest = pTo;
   60814   b.iNext = 1;
   60815 
   60816   /* 0x7FFFFFFF is the hard limit for the number of pages in a database
   60817   ** file. By passing this as the number of pages to copy to
   60818   ** sqlite3_backup_step(), we can guarantee that the copy finishes
   60819   ** within a single call (unless an error occurs). The assert() statement
   60820   ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
   60821   ** or an error code.
   60822   */
   60823   sqlite3_backup_step(&b, 0x7FFFFFFF);
   60824   assert( b.rc!=SQLITE_OK );
   60825   rc = sqlite3_backup_finish(&b);
   60826   if( rc==SQLITE_OK ){
   60827     pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
   60828   }else{
   60829     sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
   60830   }
   60831 
   60832   assert( sqlite3BtreeIsInTrans(pTo)==0 );
   60833 copy_finished:
   60834   sqlite3BtreeLeave(pFrom);
   60835   sqlite3BtreeLeave(pTo);
   60836   return rc;
   60837 }
   60838 #endif /* SQLITE_OMIT_VACUUM */
   60839 
   60840 /************** End of backup.c **********************************************/
   60841 /************** Begin file vdbemem.c *****************************************/
   60842 /*
   60843 ** 2004 May 26
   60844 **
   60845 ** The author disclaims copyright to this source code.  In place of
   60846 ** a legal notice, here is a blessing:
   60847 **
   60848 **    May you do good and not evil.
   60849 **    May you find forgiveness for yourself and forgive others.
   60850 **    May you share freely, never taking more than you give.
   60851 **
   60852 *************************************************************************
   60853 **
   60854 ** This file contains code use to manipulate "Mem" structure.  A "Mem"
   60855 ** stores a single value in the VDBE.  Mem is an opaque structure visible
   60856 ** only within the VDBE.  Interface routines refer to a Mem using the
   60857 ** name sqlite_value
   60858 */
   60859 
   60860 #ifdef SQLITE_DEBUG
   60861 /*
   60862 ** Check invariants on a Mem object.
   60863 **
   60864 ** This routine is intended for use inside of assert() statements, like
   60865 ** this:    assert( sqlite3VdbeCheckMemInvariants(pMem) );
   60866 */
   60867 SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
   60868   /* The MEM_Dyn bit is set if and only if Mem.xDel is a non-NULL destructor
   60869   ** function for Mem.z
   60870   */
   60871   assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
   60872   assert( (p->flags & MEM_Dyn)!=0 || p->xDel==0 );
   60873 
   60874   /* If p holds a string or blob, the Mem.z must point to exactly
   60875   ** one of the following:
   60876   **
   60877   **   (1) Memory in Mem.zMalloc and managed by the Mem object
   60878   **   (2) Memory to be freed using Mem.xDel
   60879   **   (3) An ephermal string or blob
   60880   **   (4) A static string or blob
   60881   */
   60882   if( (p->flags & (MEM_Str|MEM_Blob)) && p->z!=0 ){
   60883     assert(
   60884       ((p->z==p->zMalloc)? 1 : 0) +
   60885       ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
   60886       ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
   60887       ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
   60888     );
   60889   }
   60890 
   60891   return 1;
   60892 }
   60893 #endif
   60894 
   60895 
   60896 /*
   60897 ** If pMem is an object with a valid string representation, this routine
   60898 ** ensures the internal encoding for the string representation is
   60899 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
   60900 **
   60901 ** If pMem is not a string object, or the encoding of the string
   60902 ** representation is already stored using the requested encoding, then this
   60903 ** routine is a no-op.
   60904 **
   60905 ** SQLITE_OK is returned if the conversion is successful (or not required).
   60906 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
   60907 ** between formats.
   60908 */
   60909 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
   60910 #ifndef SQLITE_OMIT_UTF16
   60911   int rc;
   60912 #endif
   60913   assert( (pMem->flags&MEM_RowSet)==0 );
   60914   assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
   60915            || desiredEnc==SQLITE_UTF16BE );
   60916   if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
   60917     return SQLITE_OK;
   60918   }
   60919   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   60920 #ifdef SQLITE_OMIT_UTF16
   60921   return SQLITE_ERROR;
   60922 #else
   60923 
   60924   /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
   60925   ** then the encoding of the value may not have changed.
   60926   */
   60927   rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
   60928   assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
   60929   assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
   60930   assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
   60931   return rc;
   60932 #endif
   60933 }
   60934 
   60935 /*
   60936 ** Make sure pMem->z points to a writable allocation of at least
   60937 ** min(n,32) bytes.
   60938 **
   60939 ** If the bPreserve argument is true, then copy of the content of
   60940 ** pMem->z into the new allocation.  pMem must be either a string or
   60941 ** blob if bPreserve is true.  If bPreserve is false, any prior content
   60942 ** in pMem->z is discarded.
   60943 */
   60944 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
   60945   assert( sqlite3VdbeCheckMemInvariants(pMem) );
   60946   assert( (pMem->flags&MEM_RowSet)==0 );
   60947 
   60948   /* If the bPreserve flag is set to true, then the memory cell must already
   60949   ** contain a valid string or blob value.  */
   60950   assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
   60951   testcase( bPreserve && pMem->z==0 );
   60952 
   60953   if( pMem->zMalloc==0 || sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
   60954     if( n<32 ) n = 32;
   60955     if( bPreserve && pMem->z==pMem->zMalloc ){
   60956       pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
   60957       bPreserve = 0;
   60958     }else{
   60959       sqlite3DbFree(pMem->db, pMem->zMalloc);
   60960       pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
   60961     }
   60962     if( pMem->zMalloc==0 ){
   60963       VdbeMemRelease(pMem);
   60964       pMem->z = 0;
   60965       pMem->flags = MEM_Null;
   60966       return SQLITE_NOMEM;
   60967     }
   60968   }
   60969 
   60970   if( pMem->z && bPreserve && pMem->z!=pMem->zMalloc ){
   60971     memcpy(pMem->zMalloc, pMem->z, pMem->n);
   60972   }
   60973   if( (pMem->flags&MEM_Dyn)!=0 ){
   60974     assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
   60975     pMem->xDel((void *)(pMem->z));
   60976   }
   60977 
   60978   pMem->z = pMem->zMalloc;
   60979   pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
   60980   pMem->xDel = 0;
   60981   return SQLITE_OK;
   60982 }
   60983 
   60984 /*
   60985 ** Make the given Mem object MEM_Dyn.  In other words, make it so
   60986 ** that any TEXT or BLOB content is stored in memory obtained from
   60987 ** malloc().  In this way, we know that the memory is safe to be
   60988 ** overwritten or altered.
   60989 **
   60990 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
   60991 */
   60992 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
   60993   int f;
   60994   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   60995   assert( (pMem->flags&MEM_RowSet)==0 );
   60996   ExpandBlob(pMem);
   60997   f = pMem->flags;
   60998   if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
   60999     if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
   61000       return SQLITE_NOMEM;
   61001     }
   61002     pMem->z[pMem->n] = 0;
   61003     pMem->z[pMem->n+1] = 0;
   61004     pMem->flags |= MEM_Term;
   61005 #ifdef SQLITE_DEBUG
   61006     pMem->pScopyFrom = 0;
   61007 #endif
   61008   }
   61009 
   61010   return SQLITE_OK;
   61011 }
   61012 
   61013 /*
   61014 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
   61015 ** blob stored in dynamically allocated space.
   61016 */
   61017 #ifndef SQLITE_OMIT_INCRBLOB
   61018 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
   61019   if( pMem->flags & MEM_Zero ){
   61020     int nByte;
   61021     assert( pMem->flags&MEM_Blob );
   61022     assert( (pMem->flags&MEM_RowSet)==0 );
   61023     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   61024 
   61025     /* Set nByte to the number of bytes required to store the expanded blob. */
   61026     nByte = pMem->n + pMem->u.nZero;
   61027     if( nByte<=0 ){
   61028       nByte = 1;
   61029     }
   61030     if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
   61031       return SQLITE_NOMEM;
   61032     }
   61033 
   61034     memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
   61035     pMem->n += pMem->u.nZero;
   61036     pMem->flags &= ~(MEM_Zero|MEM_Term);
   61037   }
   61038   return SQLITE_OK;
   61039 }
   61040 #endif
   61041 
   61042 
   61043 /*
   61044 ** Make sure the given Mem is \u0000 terminated.
   61045 */
   61046 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
   61047   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   61048   if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
   61049     return SQLITE_OK;   /* Nothing to do */
   61050   }
   61051   if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
   61052     return SQLITE_NOMEM;
   61053   }
   61054   pMem->z[pMem->n] = 0;
   61055   pMem->z[pMem->n+1] = 0;
   61056   pMem->flags |= MEM_Term;
   61057   return SQLITE_OK;
   61058 }
   61059 
   61060 /*
   61061 ** Add MEM_Str to the set of representations for the given Mem.  Numbers
   61062 ** are converted using sqlite3_snprintf().  Converting a BLOB to a string
   61063 ** is a no-op.
   61064 **
   61065 ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
   61066 **
   61067 ** A MEM_Null value will never be passed to this function. This function is
   61068 ** used for converting values to text for returning to the user (i.e. via
   61069 ** sqlite3_value_text()), or for ensuring that values to be used as btree
   61070 ** keys are strings. In the former case a NULL pointer is returned the
   61071 ** user and the later is an internal programming error.
   61072 */
   61073 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
   61074   int rc = SQLITE_OK;
   61075   int fg = pMem->flags;
   61076   const int nByte = 32;
   61077 
   61078   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   61079   assert( !(fg&MEM_Zero) );
   61080   assert( !(fg&(MEM_Str|MEM_Blob)) );
   61081   assert( fg&(MEM_Int|MEM_Real) );
   61082   assert( (pMem->flags&MEM_RowSet)==0 );
   61083   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   61084 
   61085 
   61086   if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
   61087     return SQLITE_NOMEM;
   61088   }
   61089 
   61090   /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
   61091   ** string representation of the value. Then, if the required encoding
   61092   ** is UTF-16le or UTF-16be do a translation.
   61093   **
   61094   ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
   61095   */
   61096   if( fg & MEM_Int ){
   61097     sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
   61098   }else{
   61099     assert( fg & MEM_Real );
   61100     sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
   61101   }
   61102   pMem->n = sqlite3Strlen30(pMem->z);
   61103   pMem->enc = SQLITE_UTF8;
   61104   pMem->flags |= MEM_Str|MEM_Term;
   61105   sqlite3VdbeChangeEncoding(pMem, enc);
   61106   return rc;
   61107 }
   61108 
   61109 /*
   61110 ** Memory cell pMem contains the context of an aggregate function.
   61111 ** This routine calls the finalize method for that function.  The
   61112 ** result of the aggregate is stored back into pMem.
   61113 **
   61114 ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
   61115 ** otherwise.
   61116 */
   61117 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
   61118   int rc = SQLITE_OK;
   61119   if( ALWAYS(pFunc && pFunc->xFinalize) ){
   61120     sqlite3_context ctx;
   61121     assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
   61122     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   61123     memset(&ctx, 0, sizeof(ctx));
   61124     ctx.s.flags = MEM_Null;
   61125     ctx.s.db = pMem->db;
   61126     ctx.pMem = pMem;
   61127     ctx.pFunc = pFunc;
   61128     pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
   61129     assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
   61130     sqlite3DbFree(pMem->db, pMem->zMalloc);
   61131     memcpy(pMem, &ctx.s, sizeof(ctx.s));
   61132     rc = ctx.isError;
   61133   }
   61134   return rc;
   61135 }
   61136 
   61137 /*
   61138 ** If the memory cell contains a string value that must be freed by
   61139 ** invoking an external callback, free it now. Calling this function
   61140 ** does not free any Mem.zMalloc buffer.
   61141 */
   61142 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
   61143   assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
   61144   if( p->flags&MEM_Agg ){
   61145     sqlite3VdbeMemFinalize(p, p->u.pDef);
   61146     assert( (p->flags & MEM_Agg)==0 );
   61147     sqlite3VdbeMemRelease(p);
   61148   }else if( p->flags&MEM_Dyn ){
   61149     assert( (p->flags&MEM_RowSet)==0 );
   61150     assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
   61151     p->xDel((void *)p->z);
   61152     p->xDel = 0;
   61153   }else if( p->flags&MEM_RowSet ){
   61154     sqlite3RowSetClear(p->u.pRowSet);
   61155   }else if( p->flags&MEM_Frame ){
   61156     sqlite3VdbeMemSetNull(p);
   61157   }
   61158 }
   61159 
   61160 /*
   61161 ** Release any memory held by the Mem. This may leave the Mem in an
   61162 ** inconsistent state, for example with (Mem.z==0) and
   61163 ** (Mem.flags==MEM_Str).
   61164 */
   61165 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
   61166   assert( sqlite3VdbeCheckMemInvariants(p) );
   61167   VdbeMemRelease(p);
   61168   if( p->zMalloc ){
   61169     sqlite3DbFree(p->db, p->zMalloc);
   61170     p->zMalloc = 0;
   61171   }
   61172   p->z = 0;
   61173   assert( p->xDel==0 );  /* Zeroed by VdbeMemRelease() above */
   61174 }
   61175 
   61176 /*
   61177 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
   61178 ** If the double is out of range of a 64-bit signed integer then
   61179 ** return the closest available 64-bit signed integer.
   61180 */
   61181 static i64 doubleToInt64(double r){
   61182 #ifdef SQLITE_OMIT_FLOATING_POINT
   61183   /* When floating-point is omitted, double and int64 are the same thing */
   61184   return r;
   61185 #else
   61186   /*
   61187   ** Many compilers we encounter do not define constants for the
   61188   ** minimum and maximum 64-bit integers, or they define them
   61189   ** inconsistently.  And many do not understand the "LL" notation.
   61190   ** So we define our own static constants here using nothing
   61191   ** larger than a 32-bit integer constant.
   61192   */
   61193   static const i64 maxInt = LARGEST_INT64;
   61194   static const i64 minInt = SMALLEST_INT64;
   61195 
   61196   if( r<=(double)minInt ){
   61197     return minInt;
   61198   }else if( r>=(double)maxInt ){
   61199     return maxInt;
   61200   }else{
   61201     return (i64)r;
   61202   }
   61203 #endif
   61204 }
   61205 
   61206 /*
   61207 ** Return some kind of integer value which is the best we can do
   61208 ** at representing the value that *pMem describes as an integer.
   61209 ** If pMem is an integer, then the value is exact.  If pMem is
   61210 ** a floating-point then the value returned is the integer part.
   61211 ** If pMem is a string or blob, then we make an attempt to convert
   61212 ** it into a integer and return that.  If pMem represents an
   61213 ** an SQL-NULL value, return 0.
   61214 **
   61215 ** If pMem represents a string value, its encoding might be changed.
   61216 */
   61217 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
   61218   int flags;
   61219   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   61220   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   61221   flags = pMem->flags;
   61222   if( flags & MEM_Int ){
   61223     return pMem->u.i;
   61224   }else if( flags & MEM_Real ){
   61225     return doubleToInt64(pMem->r);
   61226   }else if( flags & (MEM_Str|MEM_Blob) ){
   61227     i64 value = 0;
   61228     assert( pMem->z || pMem->n==0 );
   61229     testcase( pMem->z==0 );
   61230     sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
   61231     return value;
   61232   }else{
   61233     return 0;
   61234   }
   61235 }
   61236 
   61237 /*
   61238 ** Return the best representation of pMem that we can get into a
   61239 ** double.  If pMem is already a double or an integer, return its
   61240 ** value.  If it is a string or blob, try to convert it to a double.
   61241 ** If it is a NULL, return 0.0.
   61242 */
   61243 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
   61244   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   61245   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   61246   if( pMem->flags & MEM_Real ){
   61247     return pMem->r;
   61248   }else if( pMem->flags & MEM_Int ){
   61249     return (double)pMem->u.i;
   61250   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
   61251     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
   61252     double val = (double)0;
   61253     sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
   61254     return val;
   61255   }else{
   61256     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
   61257     return (double)0;
   61258   }
   61259 }
   61260 
   61261 /*
   61262 ** The MEM structure is already a MEM_Real.  Try to also make it a
   61263 ** MEM_Int if we can.
   61264 */
   61265 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
   61266   assert( pMem->flags & MEM_Real );
   61267   assert( (pMem->flags & MEM_RowSet)==0 );
   61268   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   61269   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   61270 
   61271   pMem->u.i = doubleToInt64(pMem->r);
   61272 
   61273   /* Only mark the value as an integer if
   61274   **
   61275   **    (1) the round-trip conversion real->int->real is a no-op, and
   61276   **    (2) The integer is neither the largest nor the smallest
   61277   **        possible integer (ticket #3922)
   61278   **
   61279   ** The second and third terms in the following conditional enforces
   61280   ** the second condition under the assumption that addition overflow causes
   61281   ** values to wrap around.
   61282   */
   61283   if( pMem->r==(double)pMem->u.i
   61284    && pMem->u.i>SMALLEST_INT64
   61285    && pMem->u.i<LARGEST_INT64
   61286   ){
   61287     pMem->flags |= MEM_Int;
   61288   }
   61289 }
   61290 
   61291 /*
   61292 ** Convert pMem to type integer.  Invalidate any prior representations.
   61293 */
   61294 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
   61295   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   61296   assert( (pMem->flags & MEM_RowSet)==0 );
   61297   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   61298 
   61299   pMem->u.i = sqlite3VdbeIntValue(pMem);
   61300   MemSetTypeFlag(pMem, MEM_Int);
   61301   return SQLITE_OK;
   61302 }
   61303 
   61304 /*
   61305 ** Convert pMem so that it is of type MEM_Real.
   61306 ** Invalidate any prior representations.
   61307 */
   61308 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
   61309   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   61310   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   61311 
   61312   pMem->r = sqlite3VdbeRealValue(pMem);
   61313   MemSetTypeFlag(pMem, MEM_Real);
   61314   return SQLITE_OK;
   61315 }
   61316 
   61317 /*
   61318 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
   61319 ** Invalidate any prior representations.
   61320 **
   61321 ** Every effort is made to force the conversion, even if the input
   61322 ** is a string that does not look completely like a number.  Convert
   61323 ** as much of the string as we can and ignore the rest.
   61324 */
   61325 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
   61326   if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
   61327     assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
   61328     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   61329     if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
   61330       MemSetTypeFlag(pMem, MEM_Int);
   61331     }else{
   61332       pMem->r = sqlite3VdbeRealValue(pMem);
   61333       MemSetTypeFlag(pMem, MEM_Real);
   61334       sqlite3VdbeIntegerAffinity(pMem);
   61335     }
   61336   }
   61337   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
   61338   pMem->flags &= ~(MEM_Str|MEM_Blob);
   61339   return SQLITE_OK;
   61340 }
   61341 
   61342 /*
   61343 ** Delete any previous value and set the value stored in *pMem to NULL.
   61344 */
   61345 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
   61346   if( pMem->flags & MEM_Frame ){
   61347     VdbeFrame *pFrame = pMem->u.pFrame;
   61348     pFrame->pParent = pFrame->v->pDelFrame;
   61349     pFrame->v->pDelFrame = pFrame;
   61350   }
   61351   if( pMem->flags & MEM_RowSet ){
   61352     sqlite3RowSetClear(pMem->u.pRowSet);
   61353   }
   61354   MemSetTypeFlag(pMem, MEM_Null);
   61355 }
   61356 SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){
   61357   sqlite3VdbeMemSetNull((Mem*)p);
   61358 }
   61359 
   61360 /*
   61361 ** Delete any previous value and set the value to be a BLOB of length
   61362 ** n containing all zeros.
   61363 */
   61364 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
   61365   sqlite3VdbeMemRelease(pMem);
   61366   pMem->flags = MEM_Blob|MEM_Zero;
   61367   pMem->n = 0;
   61368   if( n<0 ) n = 0;
   61369   pMem->u.nZero = n;
   61370   pMem->enc = SQLITE_UTF8;
   61371 
   61372 #ifdef SQLITE_OMIT_INCRBLOB
   61373   sqlite3VdbeMemGrow(pMem, n, 0);
   61374   if( pMem->z ){
   61375     pMem->n = n;
   61376     memset(pMem->z, 0, n);
   61377   }
   61378 #endif
   61379 }
   61380 
   61381 /*
   61382 ** Delete any previous value and set the value stored in *pMem to val,
   61383 ** manifest type INTEGER.
   61384 */
   61385 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
   61386   sqlite3VdbeMemRelease(pMem);
   61387   pMem->u.i = val;
   61388   pMem->flags = MEM_Int;
   61389 }
   61390 
   61391 #ifndef SQLITE_OMIT_FLOATING_POINT
   61392 /*
   61393 ** Delete any previous value and set the value stored in *pMem to val,
   61394 ** manifest type REAL.
   61395 */
   61396 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
   61397   if( sqlite3IsNaN(val) ){
   61398     sqlite3VdbeMemSetNull(pMem);
   61399   }else{
   61400     sqlite3VdbeMemRelease(pMem);
   61401     pMem->r = val;
   61402     pMem->flags = MEM_Real;
   61403   }
   61404 }
   61405 #endif
   61406 
   61407 /*
   61408 ** Delete any previous value and set the value of pMem to be an
   61409 ** empty boolean index.
   61410 */
   61411 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
   61412   sqlite3 *db = pMem->db;
   61413   assert( db!=0 );
   61414   assert( (pMem->flags & MEM_RowSet)==0 );
   61415   sqlite3VdbeMemRelease(pMem);
   61416   pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
   61417   if( db->mallocFailed ){
   61418     pMem->flags = MEM_Null;
   61419   }else{
   61420     assert( pMem->zMalloc );
   61421     pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc,
   61422                                        sqlite3DbMallocSize(db, pMem->zMalloc));
   61423     assert( pMem->u.pRowSet!=0 );
   61424     pMem->flags = MEM_RowSet;
   61425   }
   61426 }
   61427 
   61428 /*
   61429 ** Return true if the Mem object contains a TEXT or BLOB that is
   61430 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
   61431 */
   61432 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
   61433   assert( p->db!=0 );
   61434   if( p->flags & (MEM_Str|MEM_Blob) ){
   61435     int n = p->n;
   61436     if( p->flags & MEM_Zero ){
   61437       n += p->u.nZero;
   61438     }
   61439     return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
   61440   }
   61441   return 0;
   61442 }
   61443 
   61444 #ifdef SQLITE_DEBUG
   61445 /*
   61446 ** This routine prepares a memory cell for modication by breaking
   61447 ** its link to a shallow copy and by marking any current shallow
   61448 ** copies of this cell as invalid.
   61449 **
   61450 ** This is used for testing and debugging only - to make sure shallow
   61451 ** copies are not misused.
   61452 */
   61453 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
   61454   int i;
   61455   Mem *pX;
   61456   for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
   61457     if( pX->pScopyFrom==pMem ){
   61458       pX->flags |= MEM_Undefined;
   61459       pX->pScopyFrom = 0;
   61460     }
   61461   }
   61462   pMem->pScopyFrom = 0;
   61463 }
   61464 #endif /* SQLITE_DEBUG */
   61465 
   61466 /*
   61467 ** Size of struct Mem not including the Mem.zMalloc member.
   61468 */
   61469 #define MEMCELLSIZE offsetof(Mem,zMalloc)
   61470 
   61471 /*
   61472 ** Make an shallow copy of pFrom into pTo.  Prior contents of
   61473 ** pTo are freed.  The pFrom->z field is not duplicated.  If
   61474 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
   61475 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
   61476 */
   61477 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
   61478   assert( (pFrom->flags & MEM_RowSet)==0 );
   61479   VdbeMemRelease(pTo);
   61480   memcpy(pTo, pFrom, MEMCELLSIZE);
   61481   pTo->xDel = 0;
   61482   if( (pFrom->flags&MEM_Static)==0 ){
   61483     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
   61484     assert( srcType==MEM_Ephem || srcType==MEM_Static );
   61485     pTo->flags |= srcType;
   61486   }
   61487 }
   61488 
   61489 /*
   61490 ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
   61491 ** freed before the copy is made.
   61492 */
   61493 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
   61494   int rc = SQLITE_OK;
   61495 
   61496   assert( (pFrom->flags & MEM_RowSet)==0 );
   61497   VdbeMemRelease(pTo);
   61498   memcpy(pTo, pFrom, MEMCELLSIZE);
   61499   pTo->flags &= ~MEM_Dyn;
   61500   pTo->xDel = 0;
   61501 
   61502   if( pTo->flags&(MEM_Str|MEM_Blob) ){
   61503     if( 0==(pFrom->flags&MEM_Static) ){
   61504       pTo->flags |= MEM_Ephem;
   61505       rc = sqlite3VdbeMemMakeWriteable(pTo);
   61506     }
   61507   }
   61508 
   61509   return rc;
   61510 }
   61511 
   61512 /*
   61513 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
   61514 ** freed. If pFrom contains ephemeral data, a copy is made.
   61515 **
   61516 ** pFrom contains an SQL NULL when this routine returns.
   61517 */
   61518 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
   61519   assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
   61520   assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
   61521   assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
   61522 
   61523   sqlite3VdbeMemRelease(pTo);
   61524   memcpy(pTo, pFrom, sizeof(Mem));
   61525   pFrom->flags = MEM_Null;
   61526   pFrom->xDel = 0;
   61527   pFrom->zMalloc = 0;
   61528 }
   61529 
   61530 /*
   61531 ** Change the value of a Mem to be a string or a BLOB.
   61532 **
   61533 ** The memory management strategy depends on the value of the xDel
   61534 ** parameter. If the value passed is SQLITE_TRANSIENT, then the
   61535 ** string is copied into a (possibly existing) buffer managed by the
   61536 ** Mem structure. Otherwise, any existing buffer is freed and the
   61537 ** pointer copied.
   61538 **
   61539 ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
   61540 ** size limit) then no memory allocation occurs.  If the string can be
   61541 ** stored without allocating memory, then it is.  If a memory allocation
   61542 ** is required to store the string, then value of pMem is unchanged.  In
   61543 ** either case, SQLITE_TOOBIG is returned.
   61544 */
   61545 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
   61546   Mem *pMem,          /* Memory cell to set to string value */
   61547   const char *z,      /* String pointer */
   61548   int n,              /* Bytes in string, or negative */
   61549   u8 enc,             /* Encoding of z.  0 for BLOBs */
   61550   void (*xDel)(void*) /* Destructor function */
   61551 ){
   61552   int nByte = n;      /* New value for pMem->n */
   61553   int iLimit;         /* Maximum allowed string or blob size */
   61554   u16 flags = 0;      /* New value for pMem->flags */
   61555 
   61556   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   61557   assert( (pMem->flags & MEM_RowSet)==0 );
   61558 
   61559   /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
   61560   if( !z ){
   61561     sqlite3VdbeMemSetNull(pMem);
   61562     return SQLITE_OK;
   61563   }
   61564 
   61565   if( pMem->db ){
   61566     iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
   61567   }else{
   61568     iLimit = SQLITE_MAX_LENGTH;
   61569   }
   61570   flags = (enc==0?MEM_Blob:MEM_Str);
   61571   if( nByte<0 ){
   61572     assert( enc!=0 );
   61573     if( enc==SQLITE_UTF8 ){
   61574       for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
   61575     }else{
   61576       for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
   61577     }
   61578     flags |= MEM_Term;
   61579   }
   61580 
   61581   /* The following block sets the new values of Mem.z and Mem.xDel. It
   61582   ** also sets a flag in local variable "flags" to indicate the memory
   61583   ** management (one of MEM_Dyn or MEM_Static).
   61584   */
   61585   if( xDel==SQLITE_TRANSIENT ){
   61586     int nAlloc = nByte;
   61587     if( flags&MEM_Term ){
   61588       nAlloc += (enc==SQLITE_UTF8?1:2);
   61589     }
   61590     if( nByte>iLimit ){
   61591       return SQLITE_TOOBIG;
   61592     }
   61593     if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
   61594       return SQLITE_NOMEM;
   61595     }
   61596     memcpy(pMem->z, z, nAlloc);
   61597   }else if( xDel==SQLITE_DYNAMIC ){
   61598     sqlite3VdbeMemRelease(pMem);
   61599     pMem->zMalloc = pMem->z = (char *)z;
   61600     pMem->xDel = 0;
   61601   }else{
   61602     sqlite3VdbeMemRelease(pMem);
   61603     pMem->z = (char *)z;
   61604     pMem->xDel = xDel;
   61605     flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
   61606   }
   61607 
   61608   pMem->n = nByte;
   61609   pMem->flags = flags;
   61610   pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
   61611 
   61612 #ifndef SQLITE_OMIT_UTF16
   61613   if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
   61614     return SQLITE_NOMEM;
   61615   }
   61616 #endif
   61617 
   61618   if( nByte>iLimit ){
   61619     return SQLITE_TOOBIG;
   61620   }
   61621 
   61622   return SQLITE_OK;
   61623 }
   61624 
   61625 /*
   61626 ** Move data out of a btree key or data field and into a Mem structure.
   61627 ** The data or key is taken from the entry that pCur is currently pointing
   61628 ** to.  offset and amt determine what portion of the data or key to retrieve.
   61629 ** key is true to get the key or false to get data.  The result is written
   61630 ** into the pMem element.
   61631 **
   61632 ** The pMem structure is assumed to be uninitialized.  Any prior content
   61633 ** is overwritten without being freed.
   61634 **
   61635 ** If this routine fails for any reason (malloc returns NULL or unable
   61636 ** to read from the disk) then the pMem is left in an inconsistent state.
   61637 */
   61638 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
   61639   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
   61640   u32 offset,       /* Offset from the start of data to return bytes from. */
   61641   u32 amt,          /* Number of bytes to return. */
   61642   int key,          /* If true, retrieve from the btree key, not data. */
   61643   Mem *pMem         /* OUT: Return data in this Mem structure. */
   61644 ){
   61645   char *zData;        /* Data from the btree layer */
   61646   u32 available = 0;  /* Number of bytes available on the local btree page */
   61647   int rc = SQLITE_OK; /* Return code */
   61648 
   61649   assert( sqlite3BtreeCursorIsValid(pCur) );
   61650 
   61651   /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
   61652   ** that both the BtShared and database handle mutexes are held. */
   61653   assert( (pMem->flags & MEM_RowSet)==0 );
   61654   if( key ){
   61655     zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
   61656   }else{
   61657     zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
   61658   }
   61659   assert( zData!=0 );
   61660 
   61661   if( offset+amt<=available ){
   61662     sqlite3VdbeMemRelease(pMem);
   61663     pMem->z = &zData[offset];
   61664     pMem->flags = MEM_Blob|MEM_Ephem;
   61665     pMem->n = (int)amt;
   61666   }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
   61667     if( key ){
   61668       rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
   61669     }else{
   61670       rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
   61671     }
   61672     if( rc==SQLITE_OK ){
   61673       pMem->z[amt] = 0;
   61674       pMem->z[amt+1] = 0;
   61675       pMem->flags = MEM_Blob|MEM_Term;
   61676       pMem->n = (int)amt;
   61677     }else{
   61678       sqlite3VdbeMemRelease(pMem);
   61679     }
   61680   }
   61681 
   61682   return rc;
   61683 }
   61684 
   61685 /* This function is only available internally, it is not part of the
   61686 ** external API. It works in a similar way to sqlite3_value_text(),
   61687 ** except the data returned is in the encoding specified by the second
   61688 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
   61689 ** SQLITE_UTF8.
   61690 **
   61691 ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
   61692 ** If that is the case, then the result must be aligned on an even byte
   61693 ** boundary.
   61694 */
   61695 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
   61696   if( !pVal ) return 0;
   61697 
   61698   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
   61699   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
   61700   assert( (pVal->flags & MEM_RowSet)==0 );
   61701 
   61702   if( pVal->flags&MEM_Null ){
   61703     return 0;
   61704   }
   61705   assert( (MEM_Blob>>3) == MEM_Str );
   61706   pVal->flags |= (pVal->flags & MEM_Blob)>>3;
   61707   ExpandBlob(pVal);
   61708   if( pVal->flags&MEM_Str ){
   61709     sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
   61710     if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
   61711       assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
   61712       if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
   61713         return 0;
   61714       }
   61715     }
   61716     sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
   61717   }else{
   61718     assert( (pVal->flags&MEM_Blob)==0 );
   61719     sqlite3VdbeMemStringify(pVal, enc);
   61720     assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
   61721   }
   61722   assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
   61723               || pVal->db->mallocFailed );
   61724   if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
   61725     return pVal->z;
   61726   }else{
   61727     return 0;
   61728   }
   61729 }
   61730 
   61731 /*
   61732 ** Create a new sqlite3_value object.
   61733 */
   61734 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
   61735   Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
   61736   if( p ){
   61737     p->flags = MEM_Null;
   61738     p->db = db;
   61739   }
   61740   return p;
   61741 }
   61742 
   61743 /*
   61744 ** Context object passed by sqlite3Stat4ProbeSetValue() through to
   61745 ** valueNew(). See comments above valueNew() for details.
   61746 */
   61747 struct ValueNewStat4Ctx {
   61748   Parse *pParse;
   61749   Index *pIdx;
   61750   UnpackedRecord **ppRec;
   61751   int iVal;
   61752 };
   61753 
   61754 /*
   61755 ** Allocate and return a pointer to a new sqlite3_value object. If
   61756 ** the second argument to this function is NULL, the object is allocated
   61757 ** by calling sqlite3ValueNew().
   61758 **
   61759 ** Otherwise, if the second argument is non-zero, then this function is
   61760 ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
   61761 ** already been allocated, allocate the UnpackedRecord structure that
   61762 ** that function will return to its caller here. Then return a pointer
   61763 ** an sqlite3_value within the UnpackedRecord.a[] array.
   61764 */
   61765 static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
   61766 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   61767   if( p ){
   61768     UnpackedRecord *pRec = p->ppRec[0];
   61769 
   61770     if( pRec==0 ){
   61771       Index *pIdx = p->pIdx;      /* Index being probed */
   61772       int nByte;                  /* Bytes of space to allocate */
   61773       int i;                      /* Counter variable */
   61774       int nCol = pIdx->nColumn;   /* Number of index columns including rowid */
   61775 
   61776       nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
   61777       pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
   61778       if( pRec ){
   61779         pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
   61780         if( pRec->pKeyInfo ){
   61781           assert( pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField==nCol );
   61782           assert( pRec->pKeyInfo->enc==ENC(db) );
   61783           pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
   61784           for(i=0; i<nCol; i++){
   61785             pRec->aMem[i].flags = MEM_Null;
   61786             pRec->aMem[i].db = db;
   61787           }
   61788         }else{
   61789           sqlite3DbFree(db, pRec);
   61790           pRec = 0;
   61791         }
   61792       }
   61793       if( pRec==0 ) return 0;
   61794       p->ppRec[0] = pRec;
   61795     }
   61796 
   61797     pRec->nField = p->iVal+1;
   61798     return &pRec->aMem[p->iVal];
   61799   }
   61800 #else
   61801   UNUSED_PARAMETER(p);
   61802 #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
   61803   return sqlite3ValueNew(db);
   61804 }
   61805 
   61806 /*
   61807 ** Extract a value from the supplied expression in the manner described
   61808 ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
   61809 ** using valueNew().
   61810 **
   61811 ** If pCtx is NULL and an error occurs after the sqlite3_value object
   61812 ** has been allocated, it is freed before returning. Or, if pCtx is not
   61813 ** NULL, it is assumed that the caller will free any allocated object
   61814 ** in all cases.
   61815 */
   61816 static int valueFromExpr(
   61817   sqlite3 *db,                    /* The database connection */
   61818   Expr *pExpr,                    /* The expression to evaluate */
   61819   u8 enc,                         /* Encoding to use */
   61820   u8 affinity,                    /* Affinity to use */
   61821   sqlite3_value **ppVal,          /* Write the new value here */
   61822   struct ValueNewStat4Ctx *pCtx   /* Second argument for valueNew() */
   61823 ){
   61824   int op;
   61825   char *zVal = 0;
   61826   sqlite3_value *pVal = 0;
   61827   int negInt = 1;
   61828   const char *zNeg = "";
   61829   int rc = SQLITE_OK;
   61830 
   61831   if( !pExpr ){
   61832     *ppVal = 0;
   61833     return SQLITE_OK;
   61834   }
   61835   op = pExpr->op;
   61836   if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
   61837 
   61838   /* Handle negative integers in a single step.  This is needed in the
   61839   ** case when the value is -9223372036854775808.
   61840   */
   61841   if( op==TK_UMINUS
   61842    && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
   61843     pExpr = pExpr->pLeft;
   61844     op = pExpr->op;
   61845     negInt = -1;
   61846     zNeg = "-";
   61847   }
   61848 
   61849   if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
   61850     pVal = valueNew(db, pCtx);
   61851     if( pVal==0 ) goto no_mem;
   61852     if( ExprHasProperty(pExpr, EP_IntValue) ){
   61853       sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
   61854     }else{
   61855       zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
   61856       if( zVal==0 ) goto no_mem;
   61857       sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
   61858     }
   61859     if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
   61860       sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
   61861     }else{
   61862       sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
   61863     }
   61864     if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
   61865     if( enc!=SQLITE_UTF8 ){
   61866       rc = sqlite3VdbeChangeEncoding(pVal, enc);
   61867     }
   61868   }else if( op==TK_UMINUS ) {
   61869     /* This branch happens for multiple negative signs.  Ex: -(-5) */
   61870     if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal)
   61871      && pVal!=0
   61872     ){
   61873       sqlite3VdbeMemNumerify(pVal);
   61874       if( pVal->u.i==SMALLEST_INT64 ){
   61875         pVal->flags &= ~MEM_Int;
   61876         pVal->flags |= MEM_Real;
   61877         pVal->r = (double)SMALLEST_INT64;
   61878       }else{
   61879         pVal->u.i = -pVal->u.i;
   61880       }
   61881       pVal->r = -pVal->r;
   61882       sqlite3ValueApplyAffinity(pVal, affinity, enc);
   61883     }
   61884   }else if( op==TK_NULL ){
   61885     pVal = valueNew(db, pCtx);
   61886     if( pVal==0 ) goto no_mem;
   61887   }
   61888 #ifndef SQLITE_OMIT_BLOB_LITERAL
   61889   else if( op==TK_BLOB ){
   61890     int nVal;
   61891     assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
   61892     assert( pExpr->u.zToken[1]=='\'' );
   61893     pVal = valueNew(db, pCtx);
   61894     if( !pVal ) goto no_mem;
   61895     zVal = &pExpr->u.zToken[2];
   61896     nVal = sqlite3Strlen30(zVal)-1;
   61897     assert( zVal[nVal]=='\'' );
   61898     sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
   61899                          0, SQLITE_DYNAMIC);
   61900   }
   61901 #endif
   61902 
   61903   *ppVal = pVal;
   61904   return rc;
   61905 
   61906 no_mem:
   61907   db->mallocFailed = 1;
   61908   sqlite3DbFree(db, zVal);
   61909   assert( *ppVal==0 );
   61910 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   61911   if( pCtx==0 ) sqlite3ValueFree(pVal);
   61912 #else
   61913   assert( pCtx==0 ); sqlite3ValueFree(pVal);
   61914 #endif
   61915   return SQLITE_NOMEM;
   61916 }
   61917 
   61918 /*
   61919 ** Create a new sqlite3_value object, containing the value of pExpr.
   61920 **
   61921 ** This only works for very simple expressions that consist of one constant
   61922 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
   61923 ** be converted directly into a value, then the value is allocated and
   61924 ** a pointer written to *ppVal. The caller is responsible for deallocating
   61925 ** the value by passing it to sqlite3ValueFree() later on. If the expression
   61926 ** cannot be converted to a value, then *ppVal is set to NULL.
   61927 */
   61928 SQLITE_PRIVATE int sqlite3ValueFromExpr(
   61929   sqlite3 *db,              /* The database connection */
   61930   Expr *pExpr,              /* The expression to evaluate */
   61931   u8 enc,                   /* Encoding to use */
   61932   u8 affinity,              /* Affinity to use */
   61933   sqlite3_value **ppVal     /* Write the new value here */
   61934 ){
   61935   return valueFromExpr(db, pExpr, enc, affinity, ppVal, 0);
   61936 }
   61937 
   61938 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   61939 /*
   61940 ** The implementation of the sqlite_record() function. This function accepts
   61941 ** a single argument of any type. The return value is a formatted database
   61942 ** record (a blob) containing the argument value.
   61943 **
   61944 ** This is used to convert the value stored in the 'sample' column of the
   61945 ** sqlite_stat3 table to the record format SQLite uses internally.
   61946 */
   61947 static void recordFunc(
   61948   sqlite3_context *context,
   61949   int argc,
   61950   sqlite3_value **argv
   61951 ){
   61952   const int file_format = 1;
   61953   int iSerial;                    /* Serial type */
   61954   int nSerial;                    /* Bytes of space for iSerial as varint */
   61955   int nVal;                       /* Bytes of space required for argv[0] */
   61956   int nRet;
   61957   sqlite3 *db;
   61958   u8 *aRet;
   61959 
   61960   UNUSED_PARAMETER( argc );
   61961   iSerial = sqlite3VdbeSerialType(argv[0], file_format);
   61962   nSerial = sqlite3VarintLen(iSerial);
   61963   nVal = sqlite3VdbeSerialTypeLen(iSerial);
   61964   db = sqlite3_context_db_handle(context);
   61965 
   61966   nRet = 1 + nSerial + nVal;
   61967   aRet = sqlite3DbMallocRaw(db, nRet);
   61968   if( aRet==0 ){
   61969     sqlite3_result_error_nomem(context);
   61970   }else{
   61971     aRet[0] = nSerial+1;
   61972     sqlite3PutVarint(&aRet[1], iSerial);
   61973     sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial);
   61974     sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
   61975     sqlite3DbFree(db, aRet);
   61976   }
   61977 }
   61978 
   61979 /*
   61980 ** Register built-in functions used to help read ANALYZE data.
   61981 */
   61982 SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
   61983   static SQLITE_WSD FuncDef aAnalyzeTableFuncs[] = {
   61984     FUNCTION(sqlite_record,   1, 0, 0, recordFunc),
   61985   };
   61986   int i;
   61987   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
   61988   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAnalyzeTableFuncs);
   61989   for(i=0; i<ArraySize(aAnalyzeTableFuncs); i++){
   61990     sqlite3FuncDefInsert(pHash, &aFunc[i]);
   61991   }
   61992 }
   61993 
   61994 /*
   61995 ** Attempt to extract a value from pExpr and use it to construct *ppVal.
   61996 **
   61997 ** If pAlloc is not NULL, then an UnpackedRecord object is created for
   61998 ** pAlloc if one does not exist and the new value is added to the
   61999 ** UnpackedRecord object.
   62000 **
   62001 ** A value is extracted in the following cases:
   62002 **
   62003 **  * (pExpr==0). In this case the value is assumed to be an SQL NULL,
   62004 **
   62005 **  * The expression is a bound variable, and this is a reprepare, or
   62006 **
   62007 **  * The expression is a literal value.
   62008 **
   62009 ** On success, *ppVal is made to point to the extracted value.  The caller
   62010 ** is responsible for ensuring that the value is eventually freed.
   62011 */
   62012 static int stat4ValueFromExpr(
   62013   Parse *pParse,                  /* Parse context */
   62014   Expr *pExpr,                    /* The expression to extract a value from */
   62015   u8 affinity,                    /* Affinity to use */
   62016   struct ValueNewStat4Ctx *pAlloc,/* How to allocate space.  Or NULL */
   62017   sqlite3_value **ppVal           /* OUT: New value object (or NULL) */
   62018 ){
   62019   int rc = SQLITE_OK;
   62020   sqlite3_value *pVal = 0;
   62021   sqlite3 *db = pParse->db;
   62022 
   62023   /* Skip over any TK_COLLATE nodes */
   62024   pExpr = sqlite3ExprSkipCollate(pExpr);
   62025 
   62026   if( !pExpr ){
   62027     pVal = valueNew(db, pAlloc);
   62028     if( pVal ){
   62029       sqlite3VdbeMemSetNull((Mem*)pVal);
   62030     }
   62031   }else if( pExpr->op==TK_VARIABLE
   62032         || NEVER(pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
   62033   ){
   62034     Vdbe *v;
   62035     int iBindVar = pExpr->iColumn;
   62036     sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
   62037     if( (v = pParse->pReprepare)!=0 ){
   62038       pVal = valueNew(db, pAlloc);
   62039       if( pVal ){
   62040         rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
   62041         if( rc==SQLITE_OK ){
   62042           sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
   62043         }
   62044         pVal->db = pParse->db;
   62045       }
   62046     }
   62047   }else{
   62048     rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);
   62049   }
   62050 
   62051   assert( pVal==0 || pVal->db==db );
   62052   *ppVal = pVal;
   62053   return rc;
   62054 }
   62055 
   62056 /*
   62057 ** This function is used to allocate and populate UnpackedRecord
   62058 ** structures intended to be compared against sample index keys stored
   62059 ** in the sqlite_stat4 table.
   62060 **
   62061 ** A single call to this function attempts to populates field iVal (leftmost
   62062 ** is 0 etc.) of the unpacked record with a value extracted from expression
   62063 ** pExpr. Extraction of values is possible if:
   62064 **
   62065 **  * (pExpr==0). In this case the value is assumed to be an SQL NULL,
   62066 **
   62067 **  * The expression is a bound variable, and this is a reprepare, or
   62068 **
   62069 **  * The sqlite3ValueFromExpr() function is able to extract a value
   62070 **    from the expression (i.e. the expression is a literal value).
   62071 **
   62072 ** If a value can be extracted, the affinity passed as the 5th argument
   62073 ** is applied to it before it is copied into the UnpackedRecord. Output
   62074 ** parameter *pbOk is set to true if a value is extracted, or false
   62075 ** otherwise.
   62076 **
   62077 ** When this function is called, *ppRec must either point to an object
   62078 ** allocated by an earlier call to this function, or must be NULL. If it
   62079 ** is NULL and a value can be successfully extracted, a new UnpackedRecord
   62080 ** is allocated (and *ppRec set to point to it) before returning.
   62081 **
   62082 ** Unless an error is encountered, SQLITE_OK is returned. It is not an
   62083 ** error if a value cannot be extracted from pExpr. If an error does
   62084 ** occur, an SQLite error code is returned.
   62085 */
   62086 SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
   62087   Parse *pParse,                  /* Parse context */
   62088   Index *pIdx,                    /* Index being probed */
   62089   UnpackedRecord **ppRec,         /* IN/OUT: Probe record */
   62090   Expr *pExpr,                    /* The expression to extract a value from */
   62091   u8 affinity,                    /* Affinity to use */
   62092   int iVal,                       /* Array element to populate */
   62093   int *pbOk                       /* OUT: True if value was extracted */
   62094 ){
   62095   int rc;
   62096   sqlite3_value *pVal = 0;
   62097   struct ValueNewStat4Ctx alloc;
   62098 
   62099   alloc.pParse = pParse;
   62100   alloc.pIdx = pIdx;
   62101   alloc.ppRec = ppRec;
   62102   alloc.iVal = iVal;
   62103 
   62104   rc = stat4ValueFromExpr(pParse, pExpr, affinity, &alloc, &pVal);
   62105   assert( pVal==0 || pVal->db==pParse->db );
   62106   *pbOk = (pVal!=0);
   62107   return rc;
   62108 }
   62109 
   62110 /*
   62111 ** Attempt to extract a value from expression pExpr using the methods
   62112 ** as described for sqlite3Stat4ProbeSetValue() above.
   62113 **
   62114 ** If successful, set *ppVal to point to a new value object and return
   62115 ** SQLITE_OK. If no value can be extracted, but no other error occurs
   62116 ** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
   62117 ** does occur, return an SQLite error code. The final value of *ppVal
   62118 ** is undefined in this case.
   62119 */
   62120 SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(
   62121   Parse *pParse,                  /* Parse context */
   62122   Expr *pExpr,                    /* The expression to extract a value from */
   62123   u8 affinity,                    /* Affinity to use */
   62124   sqlite3_value **ppVal           /* OUT: New value object (or NULL) */
   62125 ){
   62126   return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);
   62127 }
   62128 
   62129 /*
   62130 ** Extract the iCol-th column from the nRec-byte record in pRec.  Write
   62131 ** the column value into *ppVal.  If *ppVal is initially NULL then a new
   62132 ** sqlite3_value object is allocated.
   62133 **
   62134 ** If *ppVal is initially NULL then the caller is responsible for
   62135 ** ensuring that the value written into *ppVal is eventually freed.
   62136 */
   62137 SQLITE_PRIVATE int sqlite3Stat4Column(
   62138   sqlite3 *db,                    /* Database handle */
   62139   const void *pRec,               /* Pointer to buffer containing record */
   62140   int nRec,                       /* Size of buffer pRec in bytes */
   62141   int iCol,                       /* Column to extract */
   62142   sqlite3_value **ppVal           /* OUT: Extracted value */
   62143 ){
   62144   u32 t;                          /* a column type code */
   62145   int nHdr;                       /* Size of the header in the record */
   62146   int iHdr;                       /* Next unread header byte */
   62147   int iField;                     /* Next unread data byte */
   62148   int szField;                    /* Size of the current data field */
   62149   int i;                          /* Column index */
   62150   u8 *a = (u8*)pRec;              /* Typecast byte array */
   62151   Mem *pMem = *ppVal;             /* Write result into this Mem object */
   62152 
   62153   assert( iCol>0 );
   62154   iHdr = getVarint32(a, nHdr);
   62155   if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
   62156   iField = nHdr;
   62157   for(i=0; i<=iCol; i++){
   62158     iHdr += getVarint32(&a[iHdr], t);
   62159     testcase( iHdr==nHdr );
   62160     testcase( iHdr==nHdr+1 );
   62161     if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
   62162     szField = sqlite3VdbeSerialTypeLen(t);
   62163     iField += szField;
   62164   }
   62165   testcase( iField==nRec );
   62166   testcase( iField==nRec+1 );
   62167   if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
   62168   if( pMem==0 ){
   62169     pMem = *ppVal = sqlite3ValueNew(db);
   62170     if( pMem==0 ) return SQLITE_NOMEM;
   62171   }
   62172   sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
   62173   pMem->enc = ENC(db);
   62174   return SQLITE_OK;
   62175 }
   62176 
   62177 /*
   62178 ** Unless it is NULL, the argument must be an UnpackedRecord object returned
   62179 ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
   62180 ** the object.
   62181 */
   62182 SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
   62183   if( pRec ){
   62184     int i;
   62185     int nCol = pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField;
   62186     Mem *aMem = pRec->aMem;
   62187     sqlite3 *db = aMem[0].db;
   62188     for(i=0; i<nCol; i++){
   62189       sqlite3DbFree(db, aMem[i].zMalloc);
   62190     }
   62191     sqlite3KeyInfoUnref(pRec->pKeyInfo);
   62192     sqlite3DbFree(db, pRec);
   62193   }
   62194 }
   62195 #endif /* ifdef SQLITE_ENABLE_STAT4 */
   62196 
   62197 /*
   62198 ** Change the string value of an sqlite3_value object
   62199 */
   62200 SQLITE_PRIVATE void sqlite3ValueSetStr(
   62201   sqlite3_value *v,     /* Value to be set */
   62202   int n,                /* Length of string z */
   62203   const void *z,        /* Text of the new string */
   62204   u8 enc,               /* Encoding to use */
   62205   void (*xDel)(void*)   /* Destructor for the string */
   62206 ){
   62207   if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
   62208 }
   62209 
   62210 /*
   62211 ** Free an sqlite3_value object
   62212 */
   62213 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
   62214   if( !v ) return;
   62215   sqlite3VdbeMemRelease((Mem *)v);
   62216   sqlite3DbFree(((Mem*)v)->db, v);
   62217 }
   62218 
   62219 /*
   62220 ** Return the number of bytes in the sqlite3_value object assuming
   62221 ** that it uses the encoding "enc"
   62222 */
   62223 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
   62224   Mem *p = (Mem*)pVal;
   62225   if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
   62226     if( p->flags & MEM_Zero ){
   62227       return p->n + p->u.nZero;
   62228     }else{
   62229       return p->n;
   62230     }
   62231   }
   62232   return 0;
   62233 }
   62234 
   62235 /************** End of vdbemem.c *********************************************/
   62236 /************** Begin file vdbeaux.c *****************************************/
   62237 /*
   62238 ** 2003 September 6
   62239 **
   62240 ** The author disclaims copyright to this source code.  In place of
   62241 ** a legal notice, here is a blessing:
   62242 **
   62243 **    May you do good and not evil.
   62244 **    May you find forgiveness for yourself and forgive others.
   62245 **    May you share freely, never taking more than you give.
   62246 **
   62247 *************************************************************************
   62248 ** This file contains code used for creating, destroying, and populating
   62249 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
   62250 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
   62251 ** But that file was getting too big so this subroutines were split out.
   62252 */
   62253 
   62254 /*
   62255 ** Create a new virtual database engine.
   62256 */
   62257 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){
   62258   sqlite3 *db = pParse->db;
   62259   Vdbe *p;
   62260   p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
   62261   if( p==0 ) return 0;
   62262   p->db = db;
   62263   if( db->pVdbe ){
   62264     db->pVdbe->pPrev = p;
   62265   }
   62266   p->pNext = db->pVdbe;
   62267   p->pPrev = 0;
   62268   db->pVdbe = p;
   62269   p->magic = VDBE_MAGIC_INIT;
   62270   p->pParse = pParse;
   62271   assert( pParse->aLabel==0 );
   62272   assert( pParse->nLabel==0 );
   62273   assert( pParse->nOpAlloc==0 );
   62274   return p;
   62275 }
   62276 
   62277 /*
   62278 ** Remember the SQL string for a prepared statement.
   62279 */
   62280 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
   62281   assert( isPrepareV2==1 || isPrepareV2==0 );
   62282   if( p==0 ) return;
   62283 #if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
   62284   if( !isPrepareV2 ) return;
   62285 #endif
   62286   assert( p->zSql==0 );
   62287   p->zSql = sqlite3DbStrNDup(p->db, z, n);
   62288   p->isPrepareV2 = (u8)isPrepareV2;
   62289 }
   62290 
   62291 /*
   62292 ** Return the SQL associated with a prepared statement
   62293 */
   62294 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
   62295   Vdbe *p = (Vdbe *)pStmt;
   62296   return (p && p->isPrepareV2) ? p->zSql : 0;
   62297 }
   62298 
   62299 /*
   62300 ** Swap all content between two VDBE structures.
   62301 */
   62302 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
   62303   Vdbe tmp, *pTmp;
   62304   char *zTmp;
   62305   tmp = *pA;
   62306   *pA = *pB;
   62307   *pB = tmp;
   62308   pTmp = pA->pNext;
   62309   pA->pNext = pB->pNext;
   62310   pB->pNext = pTmp;
   62311   pTmp = pA->pPrev;
   62312   pA->pPrev = pB->pPrev;
   62313   pB->pPrev = pTmp;
   62314   zTmp = pA->zSql;
   62315   pA->zSql = pB->zSql;
   62316   pB->zSql = zTmp;
   62317   pB->isPrepareV2 = pA->isPrepareV2;
   62318 }
   62319 
   62320 /*
   62321 ** Resize the Vdbe.aOp array so that it is at least nOp elements larger
   62322 ** than its current size. nOp is guaranteed to be less than or equal
   62323 ** to 1024/sizeof(Op).
   62324 **
   62325 ** If an out-of-memory error occurs while resizing the array, return
   62326 ** SQLITE_NOMEM. In this case Vdbe.aOp and Parse.nOpAlloc remain
   62327 ** unchanged (this is so that any opcodes already allocated can be
   62328 ** correctly deallocated along with the rest of the Vdbe).
   62329 */
   62330 static int growOpArray(Vdbe *v, int nOp){
   62331   VdbeOp *pNew;
   62332   Parse *p = v->pParse;
   62333 
   62334   /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
   62335   ** more frequent reallocs and hence provide more opportunities for
   62336   ** simulated OOM faults.  SQLITE_TEST_REALLOC_STRESS is generally used
   62337   ** during testing only.  With SQLITE_TEST_REALLOC_STRESS grow the op array
   62338   ** by the minimum* amount required until the size reaches 512.  Normal
   62339   ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
   62340   ** size of the op array or add 1KB of space, whichever is smaller. */
   62341 #ifdef SQLITE_TEST_REALLOC_STRESS
   62342   int nNew = (p->nOpAlloc>=512 ? p->nOpAlloc*2 : p->nOpAlloc+nOp);
   62343 #else
   62344   int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
   62345   UNUSED_PARAMETER(nOp);
   62346 #endif
   62347 
   62348   assert( nOp<=(1024/sizeof(Op)) );
   62349   assert( nNew>=(p->nOpAlloc+nOp) );
   62350   pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
   62351   if( pNew ){
   62352     p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
   62353     v->aOp = pNew;
   62354   }
   62355   return (pNew ? SQLITE_OK : SQLITE_NOMEM);
   62356 }
   62357 
   62358 #ifdef SQLITE_DEBUG
   62359 /* This routine is just a convenient place to set a breakpoint that will
   62360 ** fire after each opcode is inserted and displayed using
   62361 ** "PRAGMA vdbe_addoptrace=on".
   62362 */
   62363 static void test_addop_breakpoint(void){
   62364   static int n = 0;
   62365   n++;
   62366 }
   62367 #endif
   62368 
   62369 /*
   62370 ** Add a new instruction to the list of instructions current in the
   62371 ** VDBE.  Return the address of the new instruction.
   62372 **
   62373 ** Parameters:
   62374 **
   62375 **    p               Pointer to the VDBE
   62376 **
   62377 **    op              The opcode for this instruction
   62378 **
   62379 **    p1, p2, p3      Operands
   62380 **
   62381 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
   62382 ** the sqlite3VdbeChangeP4() function to change the value of the P4
   62383 ** operand.
   62384 */
   62385 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
   62386   int i;
   62387   VdbeOp *pOp;
   62388 
   62389   i = p->nOp;
   62390   assert( p->magic==VDBE_MAGIC_INIT );
   62391   assert( op>0 && op<0xff );
   62392   if( p->pParse->nOpAlloc<=i ){
   62393     if( growOpArray(p, 1) ){
   62394       return 1;
   62395     }
   62396   }
   62397   p->nOp++;
   62398   pOp = &p->aOp[i];
   62399   pOp->opcode = (u8)op;
   62400   pOp->p5 = 0;
   62401   pOp->p1 = p1;
   62402   pOp->p2 = p2;
   62403   pOp->p3 = p3;
   62404   pOp->p4.p = 0;
   62405   pOp->p4type = P4_NOTUSED;
   62406 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
   62407   pOp->zComment = 0;
   62408 #endif
   62409 #ifdef SQLITE_DEBUG
   62410   if( p->db->flags & SQLITE_VdbeAddopTrace ){
   62411     int jj, kk;
   62412     Parse *pParse = p->pParse;
   62413     for(jj=kk=0; jj<SQLITE_N_COLCACHE; jj++){
   62414       struct yColCache *x = pParse->aColCache + jj;
   62415       if( x->iLevel>pParse->iCacheLevel || x->iReg==0 ) continue;
   62416       printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn);
   62417       kk++;
   62418     }
   62419     if( kk ) printf("\n");
   62420     sqlite3VdbePrintOp(0, i, &p->aOp[i]);
   62421     test_addop_breakpoint();
   62422   }
   62423 #endif
   62424 #ifdef VDBE_PROFILE
   62425   pOp->cycles = 0;
   62426   pOp->cnt = 0;
   62427 #endif
   62428 #ifdef SQLITE_VDBE_COVERAGE
   62429   pOp->iSrcLine = 0;
   62430 #endif
   62431   return i;
   62432 }
   62433 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
   62434   return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
   62435 }
   62436 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
   62437   return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
   62438 }
   62439 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
   62440   return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
   62441 }
   62442 
   62443 
   62444 /*
   62445 ** Add an opcode that includes the p4 value as a pointer.
   62446 */
   62447 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
   62448   Vdbe *p,            /* Add the opcode to this VM */
   62449   int op,             /* The new opcode */
   62450   int p1,             /* The P1 operand */
   62451   int p2,             /* The P2 operand */
   62452   int p3,             /* The P3 operand */
   62453   const char *zP4,    /* The P4 operand */
   62454   int p4type          /* P4 operand type */
   62455 ){
   62456   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
   62457   sqlite3VdbeChangeP4(p, addr, zP4, p4type);
   62458   return addr;
   62459 }
   62460 
   62461 /*
   62462 ** Add an OP_ParseSchema opcode.  This routine is broken out from
   62463 ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
   62464 ** as having been used.
   62465 **
   62466 ** The zWhere string must have been obtained from sqlite3_malloc().
   62467 ** This routine will take ownership of the allocated memory.
   62468 */
   62469 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
   62470   int j;
   62471   int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
   62472   sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
   62473   for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
   62474 }
   62475 
   62476 /*
   62477 ** Add an opcode that includes the p4 value as an integer.
   62478 */
   62479 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
   62480   Vdbe *p,            /* Add the opcode to this VM */
   62481   int op,             /* The new opcode */
   62482   int p1,             /* The P1 operand */
   62483   int p2,             /* The P2 operand */
   62484   int p3,             /* The P3 operand */
   62485   int p4              /* The P4 operand as an integer */
   62486 ){
   62487   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
   62488   sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
   62489   return addr;
   62490 }
   62491 
   62492 /*
   62493 ** Create a new symbolic label for an instruction that has yet to be
   62494 ** coded.  The symbolic label is really just a negative number.  The
   62495 ** label can be used as the P2 value of an operation.  Later, when
   62496 ** the label is resolved to a specific address, the VDBE will scan
   62497 ** through its operation list and change all values of P2 which match
   62498 ** the label into the resolved address.
   62499 **
   62500 ** The VDBE knows that a P2 value is a label because labels are
   62501 ** always negative and P2 values are suppose to be non-negative.
   62502 ** Hence, a negative P2 value is a label that has yet to be resolved.
   62503 **
   62504 ** Zero is returned if a malloc() fails.
   62505 */
   62506 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *v){
   62507   Parse *p = v->pParse;
   62508   int i = p->nLabel++;
   62509   assert( v->magic==VDBE_MAGIC_INIT );
   62510   if( (i & (i-1))==0 ){
   62511     p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
   62512                                        (i*2+1)*sizeof(p->aLabel[0]));
   62513   }
   62514   if( p->aLabel ){
   62515     p->aLabel[i] = -1;
   62516   }
   62517   return -1-i;
   62518 }
   62519 
   62520 /*
   62521 ** Resolve label "x" to be the address of the next instruction to
   62522 ** be inserted.  The parameter "x" must have been obtained from
   62523 ** a prior call to sqlite3VdbeMakeLabel().
   62524 */
   62525 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){
   62526   Parse *p = v->pParse;
   62527   int j = -1-x;
   62528   assert( v->magic==VDBE_MAGIC_INIT );
   62529   assert( j<p->nLabel );
   62530   if( ALWAYS(j>=0) && p->aLabel ){
   62531     p->aLabel[j] = v->nOp;
   62532   }
   62533   p->iFixedOp = v->nOp - 1;
   62534 }
   62535 
   62536 /*
   62537 ** Mark the VDBE as one that can only be run one time.
   62538 */
   62539 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
   62540   p->runOnlyOnce = 1;
   62541 }
   62542 
   62543 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
   62544 
   62545 /*
   62546 ** The following type and function are used to iterate through all opcodes
   62547 ** in a Vdbe main program and each of the sub-programs (triggers) it may
   62548 ** invoke directly or indirectly. It should be used as follows:
   62549 **
   62550 **   Op *pOp;
   62551 **   VdbeOpIter sIter;
   62552 **
   62553 **   memset(&sIter, 0, sizeof(sIter));
   62554 **   sIter.v = v;                            // v is of type Vdbe*
   62555 **   while( (pOp = opIterNext(&sIter)) ){
   62556 **     // Do something with pOp
   62557 **   }
   62558 **   sqlite3DbFree(v->db, sIter.apSub);
   62559 **
   62560 */
   62561 typedef struct VdbeOpIter VdbeOpIter;
   62562 struct VdbeOpIter {
   62563   Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
   62564   SubProgram **apSub;        /* Array of subprograms */
   62565   int nSub;                  /* Number of entries in apSub */
   62566   int iAddr;                 /* Address of next instruction to return */
   62567   int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
   62568 };
   62569 static Op *opIterNext(VdbeOpIter *p){
   62570   Vdbe *v = p->v;
   62571   Op *pRet = 0;
   62572   Op *aOp;
   62573   int nOp;
   62574 
   62575   if( p->iSub<=p->nSub ){
   62576 
   62577     if( p->iSub==0 ){
   62578       aOp = v->aOp;
   62579       nOp = v->nOp;
   62580     }else{
   62581       aOp = p->apSub[p->iSub-1]->aOp;
   62582       nOp = p->apSub[p->iSub-1]->nOp;
   62583     }
   62584     assert( p->iAddr<nOp );
   62585 
   62586     pRet = &aOp[p->iAddr];
   62587     p->iAddr++;
   62588     if( p->iAddr==nOp ){
   62589       p->iSub++;
   62590       p->iAddr = 0;
   62591     }
   62592 
   62593     if( pRet->p4type==P4_SUBPROGRAM ){
   62594       int nByte = (p->nSub+1)*sizeof(SubProgram*);
   62595       int j;
   62596       for(j=0; j<p->nSub; j++){
   62597         if( p->apSub[j]==pRet->p4.pProgram ) break;
   62598       }
   62599       if( j==p->nSub ){
   62600         p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
   62601         if( !p->apSub ){
   62602           pRet = 0;
   62603         }else{
   62604           p->apSub[p->nSub++] = pRet->p4.pProgram;
   62605         }
   62606       }
   62607     }
   62608   }
   62609 
   62610   return pRet;
   62611 }
   62612 
   62613 /*
   62614 ** Check if the program stored in the VM associated with pParse may
   62615 ** throw an ABORT exception (causing the statement, but not entire transaction
   62616 ** to be rolled back). This condition is true if the main program or any
   62617 ** sub-programs contains any of the following:
   62618 **
   62619 **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
   62620 **   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
   62621 **   *  OP_Destroy
   62622 **   *  OP_VUpdate
   62623 **   *  OP_VRename
   62624 **   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
   62625 **
   62626 ** Then check that the value of Parse.mayAbort is true if an
   62627 ** ABORT may be thrown, or false otherwise. Return true if it does
   62628 ** match, or false otherwise. This function is intended to be used as
   62629 ** part of an assert statement in the compiler. Similar to:
   62630 **
   62631 **   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
   62632 */
   62633 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
   62634   int hasAbort = 0;
   62635   Op *pOp;
   62636   VdbeOpIter sIter;
   62637   memset(&sIter, 0, sizeof(sIter));
   62638   sIter.v = v;
   62639 
   62640   while( (pOp = opIterNext(&sIter))!=0 ){
   62641     int opcode = pOp->opcode;
   62642     if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
   62643 #ifndef SQLITE_OMIT_FOREIGN_KEY
   62644      || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1)
   62645 #endif
   62646      || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
   62647       && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
   62648     ){
   62649       hasAbort = 1;
   62650       break;
   62651     }
   62652   }
   62653   sqlite3DbFree(v->db, sIter.apSub);
   62654 
   62655   /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
   62656   ** If malloc failed, then the while() loop above may not have iterated
   62657   ** through all opcodes and hasAbort may be set incorrectly. Return
   62658   ** true for this case to prevent the assert() in the callers frame
   62659   ** from failing.  */
   62660   return ( v->db->mallocFailed || hasAbort==mayAbort );
   62661 }
   62662 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
   62663 
   62664 /*
   62665 ** Loop through the program looking for P2 values that are negative
   62666 ** on jump instructions.  Each such value is a label.  Resolve the
   62667 ** label by setting the P2 value to its correct non-zero value.
   62668 **
   62669 ** This routine is called once after all opcodes have been inserted.
   62670 **
   62671 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
   62672 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
   62673 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
   62674 **
   62675 ** The Op.opflags field is set on all opcodes.
   62676 */
   62677 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
   62678   int i;
   62679   int nMaxArgs = *pMaxFuncArgs;
   62680   Op *pOp;
   62681   Parse *pParse = p->pParse;
   62682   int *aLabel = pParse->aLabel;
   62683   p->readOnly = 1;
   62684   p->bIsReader = 0;
   62685   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
   62686     u8 opcode = pOp->opcode;
   62687 
   62688     /* NOTE: Be sure to update mkopcodeh.awk when adding or removing
   62689     ** cases from this switch! */
   62690     switch( opcode ){
   62691       case OP_Function:
   62692       case OP_AggStep: {
   62693         if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
   62694         break;
   62695       }
   62696       case OP_Transaction: {
   62697         if( pOp->p2!=0 ) p->readOnly = 0;
   62698         /* fall thru */
   62699       }
   62700       case OP_AutoCommit:
   62701       case OP_Savepoint: {
   62702         p->bIsReader = 1;
   62703         break;
   62704       }
   62705 #ifndef SQLITE_OMIT_WAL
   62706       case OP_Checkpoint:
   62707 #endif
   62708       case OP_Vacuum:
   62709       case OP_JournalMode: {
   62710         p->readOnly = 0;
   62711         p->bIsReader = 1;
   62712         break;
   62713       }
   62714 #ifndef SQLITE_OMIT_VIRTUALTABLE
   62715       case OP_VUpdate: {
   62716         if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
   62717         break;
   62718       }
   62719       case OP_VFilter: {
   62720         int n;
   62721         assert( p->nOp - i >= 3 );
   62722         assert( pOp[-1].opcode==OP_Integer );
   62723         n = pOp[-1].p1;
   62724         if( n>nMaxArgs ) nMaxArgs = n;
   62725         break;
   62726       }
   62727 #endif
   62728       case OP_Next:
   62729       case OP_NextIfOpen:
   62730       case OP_SorterNext: {
   62731         pOp->p4.xAdvance = sqlite3BtreeNext;
   62732         pOp->p4type = P4_ADVANCE;
   62733         break;
   62734       }
   62735       case OP_Prev:
   62736       case OP_PrevIfOpen: {
   62737         pOp->p4.xAdvance = sqlite3BtreePrevious;
   62738         pOp->p4type = P4_ADVANCE;
   62739         break;
   62740       }
   62741     }
   62742 
   62743     pOp->opflags = sqlite3OpcodeProperty[opcode];
   62744     if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
   62745       assert( -1-pOp->p2<pParse->nLabel );
   62746       pOp->p2 = aLabel[-1-pOp->p2];
   62747     }
   62748   }
   62749   sqlite3DbFree(p->db, pParse->aLabel);
   62750   pParse->aLabel = 0;
   62751   pParse->nLabel = 0;
   62752   *pMaxFuncArgs = nMaxArgs;
   62753   assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
   62754 }
   62755 
   62756 /*
   62757 ** Return the address of the next instruction to be inserted.
   62758 */
   62759 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
   62760   assert( p->magic==VDBE_MAGIC_INIT );
   62761   return p->nOp;
   62762 }
   62763 
   62764 /*
   62765 ** This function returns a pointer to the array of opcodes associated with
   62766 ** the Vdbe passed as the first argument. It is the callers responsibility
   62767 ** to arrange for the returned array to be eventually freed using the
   62768 ** vdbeFreeOpArray() function.
   62769 **
   62770 ** Before returning, *pnOp is set to the number of entries in the returned
   62771 ** array. Also, *pnMaxArg is set to the larger of its current value and
   62772 ** the number of entries in the Vdbe.apArg[] array required to execute the
   62773 ** returned program.
   62774 */
   62775 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
   62776   VdbeOp *aOp = p->aOp;
   62777   assert( aOp && !p->db->mallocFailed );
   62778 
   62779   /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
   62780   assert( DbMaskAllZero(p->btreeMask) );
   62781 
   62782   resolveP2Values(p, pnMaxArg);
   62783   *pnOp = p->nOp;
   62784   p->aOp = 0;
   62785   return aOp;
   62786 }
   62787 
   62788 /*
   62789 ** Add a whole list of operations to the operation stack.  Return the
   62790 ** address of the first operation added.
   62791 */
   62792 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp, int iLineno){
   62793   int addr;
   62794   assert( p->magic==VDBE_MAGIC_INIT );
   62795   if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p, nOp) ){
   62796     return 0;
   62797   }
   62798   addr = p->nOp;
   62799   if( ALWAYS(nOp>0) ){
   62800     int i;
   62801     VdbeOpList const *pIn = aOp;
   62802     for(i=0; i<nOp; i++, pIn++){
   62803       int p2 = pIn->p2;
   62804       VdbeOp *pOut = &p->aOp[i+addr];
   62805       pOut->opcode = pIn->opcode;
   62806       pOut->p1 = pIn->p1;
   62807       if( p2<0 ){
   62808         assert( sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP );
   62809         pOut->p2 = addr + ADDR(p2);
   62810       }else{
   62811         pOut->p2 = p2;
   62812       }
   62813       pOut->p3 = pIn->p3;
   62814       pOut->p4type = P4_NOTUSED;
   62815       pOut->p4.p = 0;
   62816       pOut->p5 = 0;
   62817 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
   62818       pOut->zComment = 0;
   62819 #endif
   62820 #ifdef SQLITE_VDBE_COVERAGE
   62821       pOut->iSrcLine = iLineno+i;
   62822 #else
   62823       (void)iLineno;
   62824 #endif
   62825 #ifdef SQLITE_DEBUG
   62826       if( p->db->flags & SQLITE_VdbeAddopTrace ){
   62827         sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
   62828       }
   62829 #endif
   62830     }
   62831     p->nOp += nOp;
   62832   }
   62833   return addr;
   62834 }
   62835 
   62836 /*
   62837 ** Change the value of the P1 operand for a specific instruction.
   62838 ** This routine is useful when a large program is loaded from a
   62839 ** static array using sqlite3VdbeAddOpList but we want to make a
   62840 ** few minor changes to the program.
   62841 */
   62842 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
   62843   assert( p!=0 );
   62844   if( ((u32)p->nOp)>addr ){
   62845     p->aOp[addr].p1 = val;
   62846   }
   62847 }
   62848 
   62849 /*
   62850 ** Change the value of the P2 operand for a specific instruction.
   62851 ** This routine is useful for setting a jump destination.
   62852 */
   62853 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
   62854   assert( p!=0 );
   62855   if( ((u32)p->nOp)>addr ){
   62856     p->aOp[addr].p2 = val;
   62857   }
   62858 }
   62859 
   62860 /*
   62861 ** Change the value of the P3 operand for a specific instruction.
   62862 */
   62863 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
   62864   assert( p!=0 );
   62865   if( ((u32)p->nOp)>addr ){
   62866     p->aOp[addr].p3 = val;
   62867   }
   62868 }
   62869 
   62870 /*
   62871 ** Change the value of the P5 operand for the most recently
   62872 ** added operation.
   62873 */
   62874 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
   62875   assert( p!=0 );
   62876   if( p->aOp ){
   62877     assert( p->nOp>0 );
   62878     p->aOp[p->nOp-1].p5 = val;
   62879   }
   62880 }
   62881 
   62882 /*
   62883 ** Change the P2 operand of instruction addr so that it points to
   62884 ** the address of the next instruction to be coded.
   62885 */
   62886 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
   62887   sqlite3VdbeChangeP2(p, addr, p->nOp);
   62888   p->pParse->iFixedOp = p->nOp - 1;
   62889 }
   62890 
   62891 
   62892 /*
   62893 ** If the input FuncDef structure is ephemeral, then free it.  If
   62894 ** the FuncDef is not ephermal, then do nothing.
   62895 */
   62896 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
   62897   if( ALWAYS(pDef) && (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
   62898     sqlite3DbFree(db, pDef);
   62899   }
   62900 }
   62901 
   62902 static void vdbeFreeOpArray(sqlite3 *, Op *, int);
   62903 
   62904 /*
   62905 ** Delete a P4 value if necessary.
   62906 */
   62907 static void freeP4(sqlite3 *db, int p4type, void *p4){
   62908   if( p4 ){
   62909     assert( db );
   62910     switch( p4type ){
   62911       case P4_REAL:
   62912       case P4_INT64:
   62913       case P4_DYNAMIC:
   62914       case P4_INTARRAY: {
   62915         sqlite3DbFree(db, p4);
   62916         break;
   62917       }
   62918       case P4_KEYINFO: {
   62919         if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
   62920         break;
   62921       }
   62922       case P4_MPRINTF: {
   62923         if( db->pnBytesFreed==0 ) sqlite3_free(p4);
   62924         break;
   62925       }
   62926       case P4_FUNCDEF: {
   62927         freeEphemeralFunction(db, (FuncDef*)p4);
   62928         break;
   62929       }
   62930       case P4_MEM: {
   62931         if( db->pnBytesFreed==0 ){
   62932           sqlite3ValueFree((sqlite3_value*)p4);
   62933         }else{
   62934           Mem *p = (Mem*)p4;
   62935           sqlite3DbFree(db, p->zMalloc);
   62936           sqlite3DbFree(db, p);
   62937         }
   62938         break;
   62939       }
   62940       case P4_VTAB : {
   62941         if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
   62942         break;
   62943       }
   62944     }
   62945   }
   62946 }
   62947 
   62948 /*
   62949 ** Free the space allocated for aOp and any p4 values allocated for the
   62950 ** opcodes contained within. If aOp is not NULL it is assumed to contain
   62951 ** nOp entries.
   62952 */
   62953 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
   62954   if( aOp ){
   62955     Op *pOp;
   62956     for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
   62957       freeP4(db, pOp->p4type, pOp->p4.p);
   62958 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
   62959       sqlite3DbFree(db, pOp->zComment);
   62960 #endif
   62961     }
   62962   }
   62963   sqlite3DbFree(db, aOp);
   62964 }
   62965 
   62966 /*
   62967 ** Link the SubProgram object passed as the second argument into the linked
   62968 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
   62969 ** objects when the VM is no longer required.
   62970 */
   62971 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
   62972   p->pNext = pVdbe->pProgram;
   62973   pVdbe->pProgram = p;
   62974 }
   62975 
   62976 /*
   62977 ** Change the opcode at addr into OP_Noop
   62978 */
   62979 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
   62980   if( addr<p->nOp ){
   62981     VdbeOp *pOp = &p->aOp[addr];
   62982     sqlite3 *db = p->db;
   62983     freeP4(db, pOp->p4type, pOp->p4.p);
   62984     memset(pOp, 0, sizeof(pOp[0]));
   62985     pOp->opcode = OP_Noop;
   62986     if( addr==p->nOp-1 ) p->nOp--;
   62987   }
   62988 }
   62989 
   62990 /*
   62991 ** Remove the last opcode inserted
   62992 */
   62993 SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
   62994   if( (p->nOp-1)>(p->pParse->iFixedOp) && p->aOp[p->nOp-1].opcode==op ){
   62995     sqlite3VdbeChangeToNoop(p, p->nOp-1);
   62996     return 1;
   62997   }else{
   62998     return 0;
   62999   }
   63000 }
   63001 
   63002 /*
   63003 ** Change the value of the P4 operand for a specific instruction.
   63004 ** This routine is useful when a large program is loaded from a
   63005 ** static array using sqlite3VdbeAddOpList but we want to make a
   63006 ** few minor changes to the program.
   63007 **
   63008 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
   63009 ** the string is made into memory obtained from sqlite3_malloc().
   63010 ** A value of n==0 means copy bytes of zP4 up to and including the
   63011 ** first null byte.  If n>0 then copy n+1 bytes of zP4.
   63012 **
   63013 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
   63014 ** to a string or structure that is guaranteed to exist for the lifetime of
   63015 ** the Vdbe. In these cases we can just copy the pointer.
   63016 **
   63017 ** If addr<0 then change P4 on the most recently inserted instruction.
   63018 */
   63019 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
   63020   Op *pOp;
   63021   sqlite3 *db;
   63022   assert( p!=0 );
   63023   db = p->db;
   63024   assert( p->magic==VDBE_MAGIC_INIT );
   63025   if( p->aOp==0 || db->mallocFailed ){
   63026     if( n!=P4_VTAB ){
   63027       freeP4(db, n, (void*)*(char**)&zP4);
   63028     }
   63029     return;
   63030   }
   63031   assert( p->nOp>0 );
   63032   assert( addr<p->nOp );
   63033   if( addr<0 ){
   63034     addr = p->nOp - 1;
   63035   }
   63036   pOp = &p->aOp[addr];
   63037   assert( pOp->p4type==P4_NOTUSED
   63038        || pOp->p4type==P4_INT32
   63039        || pOp->p4type==P4_KEYINFO );
   63040   freeP4(db, pOp->p4type, pOp->p4.p);
   63041   pOp->p4.p = 0;
   63042   if( n==P4_INT32 ){
   63043     /* Note: this cast is safe, because the origin data point was an int
   63044     ** that was cast to a (const char *). */
   63045     pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
   63046     pOp->p4type = P4_INT32;
   63047   }else if( zP4==0 ){
   63048     pOp->p4.p = 0;
   63049     pOp->p4type = P4_NOTUSED;
   63050   }else if( n==P4_KEYINFO ){
   63051     pOp->p4.p = (void*)zP4;
   63052     pOp->p4type = P4_KEYINFO;
   63053   }else if( n==P4_VTAB ){
   63054     pOp->p4.p = (void*)zP4;
   63055     pOp->p4type = P4_VTAB;
   63056     sqlite3VtabLock((VTable *)zP4);
   63057     assert( ((VTable *)zP4)->db==p->db );
   63058   }else if( n<0 ){
   63059     pOp->p4.p = (void*)zP4;
   63060     pOp->p4type = (signed char)n;
   63061   }else{
   63062     if( n==0 ) n = sqlite3Strlen30(zP4);
   63063     pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
   63064     pOp->p4type = P4_DYNAMIC;
   63065   }
   63066 }
   63067 
   63068 /*
   63069 ** Set the P4 on the most recently added opcode to the KeyInfo for the
   63070 ** index given.
   63071 */
   63072 SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
   63073   Vdbe *v = pParse->pVdbe;
   63074   assert( v!=0 );
   63075   assert( pIdx!=0 );
   63076   sqlite3VdbeChangeP4(v, -1, (char*)sqlite3KeyInfoOfIndex(pParse, pIdx),
   63077                       P4_KEYINFO);
   63078 }
   63079 
   63080 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
   63081 /*
   63082 ** Change the comment on the most recently coded instruction.  Or
   63083 ** insert a No-op and add the comment to that new instruction.  This
   63084 ** makes the code easier to read during debugging.  None of this happens
   63085 ** in a production build.
   63086 */
   63087 static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
   63088   assert( p->nOp>0 || p->aOp==0 );
   63089   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
   63090   if( p->nOp ){
   63091     assert( p->aOp );
   63092     sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
   63093     p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
   63094   }
   63095 }
   63096 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
   63097   va_list ap;
   63098   if( p ){
   63099     va_start(ap, zFormat);
   63100     vdbeVComment(p, zFormat, ap);
   63101     va_end(ap);
   63102   }
   63103 }
   63104 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
   63105   va_list ap;
   63106   if( p ){
   63107     sqlite3VdbeAddOp0(p, OP_Noop);
   63108     va_start(ap, zFormat);
   63109     vdbeVComment(p, zFormat, ap);
   63110     va_end(ap);
   63111   }
   63112 }
   63113 #endif  /* NDEBUG */
   63114 
   63115 #ifdef SQLITE_VDBE_COVERAGE
   63116 /*
   63117 ** Set the value if the iSrcLine field for the previously coded instruction.
   63118 */
   63119 SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
   63120   sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
   63121 }
   63122 #endif /* SQLITE_VDBE_COVERAGE */
   63123 
   63124 /*
   63125 ** Return the opcode for a given address.  If the address is -1, then
   63126 ** return the most recently inserted opcode.
   63127 **
   63128 ** If a memory allocation error has occurred prior to the calling of this
   63129 ** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
   63130 ** is readable but not writable, though it is cast to a writable value.
   63131 ** The return of a dummy opcode allows the call to continue functioning
   63132 ** after a OOM fault without having to check to see if the return from
   63133 ** this routine is a valid pointer.  But because the dummy.opcode is 0,
   63134 ** dummy will never be written to.  This is verified by code inspection and
   63135 ** by running with Valgrind.
   63136 */
   63137 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
   63138   /* C89 specifies that the constant "dummy" will be initialized to all
   63139   ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
   63140   static VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
   63141   assert( p->magic==VDBE_MAGIC_INIT );
   63142   if( addr<0 ){
   63143     addr = p->nOp - 1;
   63144   }
   63145   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
   63146   if( p->db->mallocFailed ){
   63147     return (VdbeOp*)&dummy;
   63148   }else{
   63149     return &p->aOp[addr];
   63150   }
   63151 }
   63152 
   63153 #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
   63154 /*
   63155 ** Return an integer value for one of the parameters to the opcode pOp
   63156 ** determined by character c.
   63157 */
   63158 static int translateP(char c, const Op *pOp){
   63159   if( c=='1' ) return pOp->p1;
   63160   if( c=='2' ) return pOp->p2;
   63161   if( c=='3' ) return pOp->p3;
   63162   if( c=='4' ) return pOp->p4.i;
   63163   return pOp->p5;
   63164 }
   63165 
   63166 /*
   63167 ** Compute a string for the "comment" field of a VDBE opcode listing.
   63168 **
   63169 ** The Synopsis: field in comments in the vdbe.c source file gets converted
   63170 ** to an extra string that is appended to the sqlite3OpcodeName().  In the
   63171 ** absence of other comments, this synopsis becomes the comment on the opcode.
   63172 ** Some translation occurs:
   63173 **
   63174 **       "PX"      ->  "r[X]"
   63175 **       "PX@PY"   ->  "r[X..X+Y-1]"  or "r[x]" if y is 0 or 1
   63176 **       "PX@PY+1" ->  "r[X..X+Y]"    or "r[x]" if y is 0
   63177 **       "PY..PY"  ->  "r[X..Y]"      or "r[x]" if y<=x
   63178 */
   63179 static int displayComment(
   63180   const Op *pOp,     /* The opcode to be commented */
   63181   const char *zP4,   /* Previously obtained value for P4 */
   63182   char *zTemp,       /* Write result here */
   63183   int nTemp          /* Space available in zTemp[] */
   63184 ){
   63185   const char *zOpName;
   63186   const char *zSynopsis;
   63187   int nOpName;
   63188   int ii, jj;
   63189   zOpName = sqlite3OpcodeName(pOp->opcode);
   63190   nOpName = sqlite3Strlen30(zOpName);
   63191   if( zOpName[nOpName+1] ){
   63192     int seenCom = 0;
   63193     char c;
   63194     zSynopsis = zOpName += nOpName + 1;
   63195     for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
   63196       if( c=='P' ){
   63197         c = zSynopsis[++ii];
   63198         if( c=='4' ){
   63199           sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
   63200         }else if( c=='X' ){
   63201           sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
   63202           seenCom = 1;
   63203         }else{
   63204           int v1 = translateP(c, pOp);
   63205           int v2;
   63206           sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
   63207           if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
   63208             ii += 3;
   63209             jj += sqlite3Strlen30(zTemp+jj);
   63210             v2 = translateP(zSynopsis[ii], pOp);
   63211             if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
   63212               ii += 2;
   63213               v2++;
   63214             }
   63215             if( v2>1 ){
   63216               sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
   63217             }
   63218           }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
   63219             ii += 4;
   63220           }
   63221         }
   63222         jj += sqlite3Strlen30(zTemp+jj);
   63223       }else{
   63224         zTemp[jj++] = c;
   63225       }
   63226     }
   63227     if( !seenCom && jj<nTemp-5 && pOp->zComment ){
   63228       sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
   63229       jj += sqlite3Strlen30(zTemp+jj);
   63230     }
   63231     if( jj<nTemp ) zTemp[jj] = 0;
   63232   }else if( pOp->zComment ){
   63233     sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
   63234     jj = sqlite3Strlen30(zTemp);
   63235   }else{
   63236     zTemp[0] = 0;
   63237     jj = 0;
   63238   }
   63239   return jj;
   63240 }
   63241 #endif /* SQLITE_DEBUG */
   63242 
   63243 
   63244 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
   63245      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
   63246 /*
   63247 ** Compute a string that describes the P4 parameter for an opcode.
   63248 ** Use zTemp for any required temporary buffer space.
   63249 */
   63250 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
   63251   char *zP4 = zTemp;
   63252   assert( nTemp>=20 );
   63253   switch( pOp->p4type ){
   63254     case P4_KEYINFO: {
   63255       int i, j;
   63256       KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
   63257       assert( pKeyInfo->aSortOrder!=0 );
   63258       sqlite3_snprintf(nTemp, zTemp, "k(%d", pKeyInfo->nField);
   63259       i = sqlite3Strlen30(zTemp);
   63260       for(j=0; j<pKeyInfo->nField; j++){
   63261         CollSeq *pColl = pKeyInfo->aColl[j];
   63262         const char *zColl = pColl ? pColl->zName : "nil";
   63263         int n = sqlite3Strlen30(zColl);
   63264         if( n==6 && memcmp(zColl,"BINARY",6)==0 ){
   63265           zColl = "B";
   63266           n = 1;
   63267         }
   63268         if( i+n>nTemp-6 ){
   63269           memcpy(&zTemp[i],",...",4);
   63270           break;
   63271         }
   63272         zTemp[i++] = ',';
   63273         if( pKeyInfo->aSortOrder[j] ){
   63274           zTemp[i++] = '-';
   63275         }
   63276         memcpy(&zTemp[i], zColl, n+1);
   63277         i += n;
   63278       }
   63279       zTemp[i++] = ')';
   63280       zTemp[i] = 0;
   63281       assert( i<nTemp );
   63282       break;
   63283     }
   63284     case P4_COLLSEQ: {
   63285       CollSeq *pColl = pOp->p4.pColl;
   63286       sqlite3_snprintf(nTemp, zTemp, "(%.20s)", pColl->zName);
   63287       break;
   63288     }
   63289     case P4_FUNCDEF: {
   63290       FuncDef *pDef = pOp->p4.pFunc;
   63291       sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
   63292       break;
   63293     }
   63294     case P4_INT64: {
   63295       sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
   63296       break;
   63297     }
   63298     case P4_INT32: {
   63299       sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
   63300       break;
   63301     }
   63302     case P4_REAL: {
   63303       sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
   63304       break;
   63305     }
   63306     case P4_MEM: {
   63307       Mem *pMem = pOp->p4.pMem;
   63308       if( pMem->flags & MEM_Str ){
   63309         zP4 = pMem->z;
   63310       }else if( pMem->flags & MEM_Int ){
   63311         sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
   63312       }else if( pMem->flags & MEM_Real ){
   63313         sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
   63314       }else if( pMem->flags & MEM_Null ){
   63315         sqlite3_snprintf(nTemp, zTemp, "NULL");
   63316       }else{
   63317         assert( pMem->flags & MEM_Blob );
   63318         zP4 = "(blob)";
   63319       }
   63320       break;
   63321     }
   63322 #ifndef SQLITE_OMIT_VIRTUALTABLE
   63323     case P4_VTAB: {
   63324       sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
   63325       sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
   63326       break;
   63327     }
   63328 #endif
   63329     case P4_INTARRAY: {
   63330       sqlite3_snprintf(nTemp, zTemp, "intarray");
   63331       break;
   63332     }
   63333     case P4_SUBPROGRAM: {
   63334       sqlite3_snprintf(nTemp, zTemp, "program");
   63335       break;
   63336     }
   63337     case P4_ADVANCE: {
   63338       zTemp[0] = 0;
   63339       break;
   63340     }
   63341     default: {
   63342       zP4 = pOp->p4.z;
   63343       if( zP4==0 ){
   63344         zP4 = zTemp;
   63345         zTemp[0] = 0;
   63346       }
   63347     }
   63348   }
   63349   assert( zP4!=0 );
   63350   return zP4;
   63351 }
   63352 #endif
   63353 
   63354 /*
   63355 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
   63356 **
   63357 ** The prepared statements need to know in advance the complete set of
   63358 ** attached databases that will be use.  A mask of these databases
   63359 ** is maintained in p->btreeMask.  The p->lockMask value is the subset of
   63360 ** p->btreeMask of databases that will require a lock.
   63361 */
   63362 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
   63363   assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
   63364   assert( i<(int)sizeof(p->btreeMask)*8 );
   63365   DbMaskSet(p->btreeMask, i);
   63366   if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
   63367     DbMaskSet(p->lockMask, i);
   63368   }
   63369 }
   63370 
   63371 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
   63372 /*
   63373 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
   63374 ** this routine obtains the mutex associated with each BtShared structure
   63375 ** that may be accessed by the VM passed as an argument. In doing so it also
   63376 ** sets the BtShared.db member of each of the BtShared structures, ensuring
   63377 ** that the correct busy-handler callback is invoked if required.
   63378 **
   63379 ** If SQLite is not threadsafe but does support shared-cache mode, then
   63380 ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
   63381 ** of all of BtShared structures accessible via the database handle
   63382 ** associated with the VM.
   63383 **
   63384 ** If SQLite is not threadsafe and does not support shared-cache mode, this
   63385 ** function is a no-op.
   63386 **
   63387 ** The p->btreeMask field is a bitmask of all btrees that the prepared
   63388 ** statement p will ever use.  Let N be the number of bits in p->btreeMask
   63389 ** corresponding to btrees that use shared cache.  Then the runtime of
   63390 ** this routine is N*N.  But as N is rarely more than 1, this should not
   63391 ** be a problem.
   63392 */
   63393 SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
   63394   int i;
   63395   sqlite3 *db;
   63396   Db *aDb;
   63397   int nDb;
   63398   if( DbMaskAllZero(p->lockMask) ) return;  /* The common case */
   63399   db = p->db;
   63400   aDb = db->aDb;
   63401   nDb = db->nDb;
   63402   for(i=0; i<nDb; i++){
   63403     if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
   63404       sqlite3BtreeEnter(aDb[i].pBt);
   63405     }
   63406   }
   63407 }
   63408 #endif
   63409 
   63410 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
   63411 /*
   63412 ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
   63413 */
   63414 SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
   63415   int i;
   63416   sqlite3 *db;
   63417   Db *aDb;
   63418   int nDb;
   63419   if( DbMaskAllZero(p->lockMask) ) return;  /* The common case */
   63420   db = p->db;
   63421   aDb = db->aDb;
   63422   nDb = db->nDb;
   63423   for(i=0; i<nDb; i++){
   63424     if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
   63425       sqlite3BtreeLeave(aDb[i].pBt);
   63426     }
   63427   }
   63428 }
   63429 #endif
   63430 
   63431 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
   63432 /*
   63433 ** Print a single opcode.  This routine is used for debugging only.
   63434 */
   63435 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
   63436   char *zP4;
   63437   char zPtr[50];
   63438   char zCom[100];
   63439   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
   63440   if( pOut==0 ) pOut = stdout;
   63441   zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
   63442 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
   63443   displayComment(pOp, zP4, zCom, sizeof(zCom));
   63444 #else
   63445   zCom[0] = 0;
   63446 #endif
   63447   /* NB:  The sqlite3OpcodeName() function is implemented by code created
   63448   ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
   63449   ** information from the vdbe.c source text */
   63450   fprintf(pOut, zFormat1, pc,
   63451       sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
   63452       zCom
   63453   );
   63454   fflush(pOut);
   63455 }
   63456 #endif
   63457 
   63458 /*
   63459 ** Release an array of N Mem elements
   63460 */
   63461 static void releaseMemArray(Mem *p, int N){
   63462   if( p && N ){
   63463     Mem *pEnd;
   63464     sqlite3 *db = p->db;
   63465     u8 malloc_failed = db->mallocFailed;
   63466     if( db->pnBytesFreed ){
   63467       for(pEnd=&p[N]; p<pEnd; p++){
   63468         sqlite3DbFree(db, p->zMalloc);
   63469       }
   63470       return;
   63471     }
   63472     for(pEnd=&p[N]; p<pEnd; p++){
   63473       assert( (&p[1])==pEnd || p[0].db==p[1].db );
   63474       assert( sqlite3VdbeCheckMemInvariants(p) );
   63475 
   63476       /* This block is really an inlined version of sqlite3VdbeMemRelease()
   63477       ** that takes advantage of the fact that the memory cell value is
   63478       ** being set to NULL after releasing any dynamic resources.
   63479       **
   63480       ** The justification for duplicating code is that according to
   63481       ** callgrind, this causes a certain test case to hit the CPU 4.7
   63482       ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
   63483       ** sqlite3MemRelease() were called from here. With -O2, this jumps
   63484       ** to 6.6 percent. The test case is inserting 1000 rows into a table
   63485       ** with no indexes using a single prepared INSERT statement, bind()
   63486       ** and reset(). Inserts are grouped into a transaction.
   63487       */
   63488       testcase( p->flags & MEM_Agg );
   63489       testcase( p->flags & MEM_Dyn );
   63490       testcase( p->flags & MEM_Frame );
   63491       testcase( p->flags & MEM_RowSet );
   63492       if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
   63493         sqlite3VdbeMemRelease(p);
   63494       }else if( p->zMalloc ){
   63495         sqlite3DbFree(db, p->zMalloc);
   63496         p->zMalloc = 0;
   63497       }
   63498 
   63499       p->flags = MEM_Undefined;
   63500     }
   63501     db->mallocFailed = malloc_failed;
   63502   }
   63503 }
   63504 
   63505 /*
   63506 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
   63507 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
   63508 */
   63509 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
   63510   int i;
   63511   Mem *aMem = VdbeFrameMem(p);
   63512   VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
   63513   for(i=0; i<p->nChildCsr; i++){
   63514     sqlite3VdbeFreeCursor(p->v, apCsr[i]);
   63515   }
   63516   releaseMemArray(aMem, p->nChildMem);
   63517   sqlite3DbFree(p->v->db, p);
   63518 }
   63519 
   63520 #ifndef SQLITE_OMIT_EXPLAIN
   63521 /*
   63522 ** Give a listing of the program in the virtual machine.
   63523 **
   63524 ** The interface is the same as sqlite3VdbeExec().  But instead of
   63525 ** running the code, it invokes the callback once for each instruction.
   63526 ** This feature is used to implement "EXPLAIN".
   63527 **
   63528 ** When p->explain==1, each instruction is listed.  When
   63529 ** p->explain==2, only OP_Explain instructions are listed and these
   63530 ** are shown in a different format.  p->explain==2 is used to implement
   63531 ** EXPLAIN QUERY PLAN.
   63532 **
   63533 ** When p->explain==1, first the main program is listed, then each of
   63534 ** the trigger subprograms are listed one by one.
   63535 */
   63536 SQLITE_PRIVATE int sqlite3VdbeList(
   63537   Vdbe *p                   /* The VDBE */
   63538 ){
   63539   int nRow;                            /* Stop when row count reaches this */
   63540   int nSub = 0;                        /* Number of sub-vdbes seen so far */
   63541   SubProgram **apSub = 0;              /* Array of sub-vdbes */
   63542   Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
   63543   sqlite3 *db = p->db;                 /* The database connection */
   63544   int i;                               /* Loop counter */
   63545   int rc = SQLITE_OK;                  /* Return code */
   63546   Mem *pMem = &p->aMem[1];             /* First Mem of result set */
   63547 
   63548   assert( p->explain );
   63549   assert( p->magic==VDBE_MAGIC_RUN );
   63550   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
   63551 
   63552   /* Even though this opcode does not use dynamic strings for
   63553   ** the result, result columns may become dynamic if the user calls
   63554   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
   63555   */
   63556   releaseMemArray(pMem, 8);
   63557   p->pResultSet = 0;
   63558 
   63559   if( p->rc==SQLITE_NOMEM ){
   63560     /* This happens if a malloc() inside a call to sqlite3_column_text() or
   63561     ** sqlite3_column_text16() failed.  */
   63562     db->mallocFailed = 1;
   63563     return SQLITE_ERROR;
   63564   }
   63565 
   63566   /* When the number of output rows reaches nRow, that means the
   63567   ** listing has finished and sqlite3_step() should return SQLITE_DONE.
   63568   ** nRow is the sum of the number of rows in the main program, plus
   63569   ** the sum of the number of rows in all trigger subprograms encountered
   63570   ** so far.  The nRow value will increase as new trigger subprograms are
   63571   ** encountered, but p->pc will eventually catch up to nRow.
   63572   */
   63573   nRow = p->nOp;
   63574   if( p->explain==1 ){
   63575     /* The first 8 memory cells are used for the result set.  So we will
   63576     ** commandeer the 9th cell to use as storage for an array of pointers
   63577     ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
   63578     ** cells.  */
   63579     assert( p->nMem>9 );
   63580     pSub = &p->aMem[9];
   63581     if( pSub->flags&MEM_Blob ){
   63582       /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
   63583       ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
   63584       nSub = pSub->n/sizeof(Vdbe*);
   63585       apSub = (SubProgram **)pSub->z;
   63586     }
   63587     for(i=0; i<nSub; i++){
   63588       nRow += apSub[i]->nOp;
   63589     }
   63590   }
   63591 
   63592   do{
   63593     i = p->pc++;
   63594   }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
   63595   if( i>=nRow ){
   63596     p->rc = SQLITE_OK;
   63597     rc = SQLITE_DONE;
   63598   }else if( db->u1.isInterrupted ){
   63599     p->rc = SQLITE_INTERRUPT;
   63600     rc = SQLITE_ERROR;
   63601     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
   63602   }else{
   63603     char *zP4;
   63604     Op *pOp;
   63605     if( i<p->nOp ){
   63606       /* The output line number is small enough that we are still in the
   63607       ** main program. */
   63608       pOp = &p->aOp[i];
   63609     }else{
   63610       /* We are currently listing subprograms.  Figure out which one and
   63611       ** pick up the appropriate opcode. */
   63612       int j;
   63613       i -= p->nOp;
   63614       for(j=0; i>=apSub[j]->nOp; j++){
   63615         i -= apSub[j]->nOp;
   63616       }
   63617       pOp = &apSub[j]->aOp[i];
   63618     }
   63619     if( p->explain==1 ){
   63620       pMem->flags = MEM_Int;
   63621       pMem->u.i = i;                                /* Program counter */
   63622       pMem++;
   63623 
   63624       pMem->flags = MEM_Static|MEM_Str|MEM_Term;
   63625       pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
   63626       assert( pMem->z!=0 );
   63627       pMem->n = sqlite3Strlen30(pMem->z);
   63628       pMem->enc = SQLITE_UTF8;
   63629       pMem++;
   63630 
   63631       /* When an OP_Program opcode is encounter (the only opcode that has
   63632       ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
   63633       ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
   63634       ** has not already been seen.
   63635       */
   63636       if( pOp->p4type==P4_SUBPROGRAM ){
   63637         int nByte = (nSub+1)*sizeof(SubProgram*);
   63638         int j;
   63639         for(j=0; j<nSub; j++){
   63640           if( apSub[j]==pOp->p4.pProgram ) break;
   63641         }
   63642         if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
   63643           apSub = (SubProgram **)pSub->z;
   63644           apSub[nSub++] = pOp->p4.pProgram;
   63645           pSub->flags |= MEM_Blob;
   63646           pSub->n = nSub*sizeof(SubProgram*);
   63647         }
   63648       }
   63649     }
   63650 
   63651     pMem->flags = MEM_Int;
   63652     pMem->u.i = pOp->p1;                          /* P1 */
   63653     pMem++;
   63654 
   63655     pMem->flags = MEM_Int;
   63656     pMem->u.i = pOp->p2;                          /* P2 */
   63657     pMem++;
   63658 
   63659     pMem->flags = MEM_Int;
   63660     pMem->u.i = pOp->p3;                          /* P3 */
   63661     pMem++;
   63662 
   63663     if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
   63664       assert( p->db->mallocFailed );
   63665       return SQLITE_ERROR;
   63666     }
   63667     pMem->flags = MEM_Str|MEM_Term;
   63668     zP4 = displayP4(pOp, pMem->z, 32);
   63669     if( zP4!=pMem->z ){
   63670       sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
   63671     }else{
   63672       assert( pMem->z!=0 );
   63673       pMem->n = sqlite3Strlen30(pMem->z);
   63674       pMem->enc = SQLITE_UTF8;
   63675     }
   63676     pMem++;
   63677 
   63678     if( p->explain==1 ){
   63679       if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
   63680         assert( p->db->mallocFailed );
   63681         return SQLITE_ERROR;
   63682       }
   63683       pMem->flags = MEM_Str|MEM_Term;
   63684       pMem->n = 2;
   63685       sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
   63686       pMem->enc = SQLITE_UTF8;
   63687       pMem++;
   63688 
   63689 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
   63690       if( sqlite3VdbeMemGrow(pMem, 500, 0) ){
   63691         assert( p->db->mallocFailed );
   63692         return SQLITE_ERROR;
   63693       }
   63694       pMem->flags = MEM_Str|MEM_Term;
   63695       pMem->n = displayComment(pOp, zP4, pMem->z, 500);
   63696       pMem->enc = SQLITE_UTF8;
   63697 #else
   63698       pMem->flags = MEM_Null;                       /* Comment */
   63699 #endif
   63700     }
   63701 
   63702     p->nResColumn = 8 - 4*(p->explain-1);
   63703     p->pResultSet = &p->aMem[1];
   63704     p->rc = SQLITE_OK;
   63705     rc = SQLITE_ROW;
   63706   }
   63707   return rc;
   63708 }
   63709 #endif /* SQLITE_OMIT_EXPLAIN */
   63710 
   63711 #ifdef SQLITE_DEBUG
   63712 /*
   63713 ** Print the SQL that was used to generate a VDBE program.
   63714 */
   63715 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
   63716   const char *z = 0;
   63717   if( p->zSql ){
   63718     z = p->zSql;
   63719   }else if( p->nOp>=1 ){
   63720     const VdbeOp *pOp = &p->aOp[0];
   63721     if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
   63722       z = pOp->p4.z;
   63723       while( sqlite3Isspace(*z) ) z++;
   63724     }
   63725   }
   63726   if( z ) printf("SQL: [%s]\n", z);
   63727 }
   63728 #endif
   63729 
   63730 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
   63731 /*
   63732 ** Print an IOTRACE message showing SQL content.
   63733 */
   63734 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
   63735   int nOp = p->nOp;
   63736   VdbeOp *pOp;
   63737   if( sqlite3IoTrace==0 ) return;
   63738   if( nOp<1 ) return;
   63739   pOp = &p->aOp[0];
   63740   if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
   63741     int i, j;
   63742     char z[1000];
   63743     sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
   63744     for(i=0; sqlite3Isspace(z[i]); i++){}
   63745     for(j=0; z[i]; i++){
   63746       if( sqlite3Isspace(z[i]) ){
   63747         if( z[i-1]!=' ' ){
   63748           z[j++] = ' ';
   63749         }
   63750       }else{
   63751         z[j++] = z[i];
   63752       }
   63753     }
   63754     z[j] = 0;
   63755     sqlite3IoTrace("SQL %s\n", z);
   63756   }
   63757 }
   63758 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
   63759 
   63760 /*
   63761 ** Allocate space from a fixed size buffer and return a pointer to
   63762 ** that space.  If insufficient space is available, return NULL.
   63763 **
   63764 ** The pBuf parameter is the initial value of a pointer which will
   63765 ** receive the new memory.  pBuf is normally NULL.  If pBuf is not
   63766 ** NULL, it means that memory space has already been allocated and that
   63767 ** this routine should not allocate any new memory.  When pBuf is not
   63768 ** NULL simply return pBuf.  Only allocate new memory space when pBuf
   63769 ** is NULL.
   63770 **
   63771 ** nByte is the number of bytes of space needed.
   63772 **
   63773 ** *ppFrom points to available space and pEnd points to the end of the
   63774 ** available space.  When space is allocated, *ppFrom is advanced past
   63775 ** the end of the allocated space.
   63776 **
   63777 ** *pnByte is a counter of the number of bytes of space that have failed
   63778 ** to allocate.  If there is insufficient space in *ppFrom to satisfy the
   63779 ** request, then increment *pnByte by the amount of the request.
   63780 */
   63781 static void *allocSpace(
   63782   void *pBuf,          /* Where return pointer will be stored */
   63783   int nByte,           /* Number of bytes to allocate */
   63784   u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
   63785   u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
   63786   int *pnByte          /* If allocation cannot be made, increment *pnByte */
   63787 ){
   63788   assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
   63789   if( pBuf ) return pBuf;
   63790   nByte = ROUND8(nByte);
   63791   if( &(*ppFrom)[nByte] <= pEnd ){
   63792     pBuf = (void*)*ppFrom;
   63793     *ppFrom += nByte;
   63794   }else{
   63795     *pnByte += nByte;
   63796   }
   63797   return pBuf;
   63798 }
   63799 
   63800 /*
   63801 ** Rewind the VDBE back to the beginning in preparation for
   63802 ** running it.
   63803 */
   63804 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
   63805 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
   63806   int i;
   63807 #endif
   63808   assert( p!=0 );
   63809   assert( p->magic==VDBE_MAGIC_INIT );
   63810 
   63811   /* There should be at least one opcode.
   63812   */
   63813   assert( p->nOp>0 );
   63814 
   63815   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
   63816   p->magic = VDBE_MAGIC_RUN;
   63817 
   63818 #ifdef SQLITE_DEBUG
   63819   for(i=1; i<p->nMem; i++){
   63820     assert( p->aMem[i].db==p->db );
   63821   }
   63822 #endif
   63823   p->pc = -1;
   63824   p->rc = SQLITE_OK;
   63825   p->errorAction = OE_Abort;
   63826   p->magic = VDBE_MAGIC_RUN;
   63827   p->nChange = 0;
   63828   p->cacheCtr = 1;
   63829   p->minWriteFileFormat = 255;
   63830   p->iStatement = 0;
   63831   p->nFkConstraint = 0;
   63832 #ifdef VDBE_PROFILE
   63833   for(i=0; i<p->nOp; i++){
   63834     p->aOp[i].cnt = 0;
   63835     p->aOp[i].cycles = 0;
   63836   }
   63837 #endif
   63838 }
   63839 
   63840 /*
   63841 ** Prepare a virtual machine for execution for the first time after
   63842 ** creating the virtual machine.  This involves things such
   63843 ** as allocating stack space and initializing the program counter.
   63844 ** After the VDBE has be prepped, it can be executed by one or more
   63845 ** calls to sqlite3VdbeExec().
   63846 **
   63847 ** This function may be called exact once on a each virtual machine.
   63848 ** After this routine is called the VM has been "packaged" and is ready
   63849 ** to run.  After this routine is called, futher calls to
   63850 ** sqlite3VdbeAddOp() functions are prohibited.  This routine disconnects
   63851 ** the Vdbe from the Parse object that helped generate it so that the
   63852 ** the Vdbe becomes an independent entity and the Parse object can be
   63853 ** destroyed.
   63854 **
   63855 ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
   63856 ** to its initial state after it has been run.
   63857 */
   63858 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
   63859   Vdbe *p,                       /* The VDBE */
   63860   Parse *pParse                  /* Parsing context */
   63861 ){
   63862   sqlite3 *db;                   /* The database connection */
   63863   int nVar;                      /* Number of parameters */
   63864   int nMem;                      /* Number of VM memory registers */
   63865   int nCursor;                   /* Number of cursors required */
   63866   int nArg;                      /* Number of arguments in subprograms */
   63867   int nOnce;                     /* Number of OP_Once instructions */
   63868   int n;                         /* Loop counter */
   63869   u8 *zCsr;                      /* Memory available for allocation */
   63870   u8 *zEnd;                      /* First byte past allocated memory */
   63871   int nByte;                     /* How much extra memory is needed */
   63872 
   63873   assert( p!=0 );
   63874   assert( p->nOp>0 );
   63875   assert( pParse!=0 );
   63876   assert( p->magic==VDBE_MAGIC_INIT );
   63877   assert( pParse==p->pParse );
   63878   db = p->db;
   63879   assert( db->mallocFailed==0 );
   63880   nVar = pParse->nVar;
   63881   nMem = pParse->nMem;
   63882   nCursor = pParse->nTab;
   63883   nArg = pParse->nMaxArg;
   63884   nOnce = pParse->nOnce;
   63885   if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
   63886 
   63887   /* For each cursor required, also allocate a memory cell. Memory
   63888   ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
   63889   ** the vdbe program. Instead they are used to allocate space for
   63890   ** VdbeCursor/BtCursor structures. The blob of memory associated with
   63891   ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
   63892   ** stores the blob of memory associated with cursor 1, etc.
   63893   **
   63894   ** See also: allocateCursor().
   63895   */
   63896   nMem += nCursor;
   63897 
   63898   /* Allocate space for memory registers, SQL variables, VDBE cursors and
   63899   ** an array to marshal SQL function arguments in.
   63900   */
   63901   zCsr = (u8*)&p->aOp[p->nOp];            /* Memory avaliable for allocation */
   63902   zEnd = (u8*)&p->aOp[pParse->nOpAlloc];  /* First byte past end of zCsr[] */
   63903 
   63904   resolveP2Values(p, &nArg);
   63905   p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
   63906   if( pParse->explain && nMem<10 ){
   63907     nMem = 10;
   63908   }
   63909   memset(zCsr, 0, zEnd-zCsr);
   63910   zCsr += (zCsr - (u8*)0)&7;
   63911   assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
   63912   p->expired = 0;
   63913 
   63914   /* Memory for registers, parameters, cursor, etc, is allocated in two
   63915   ** passes.  On the first pass, we try to reuse unused space at the
   63916   ** end of the opcode array.  If we are unable to satisfy all memory
   63917   ** requirements by reusing the opcode array tail, then the second
   63918   ** pass will fill in the rest using a fresh allocation.
   63919   **
   63920   ** This two-pass approach that reuses as much memory as possible from
   63921   ** the leftover space at the end of the opcode array can significantly
   63922   ** reduce the amount of memory held by a prepared statement.
   63923   */
   63924   do {
   63925     nByte = 0;
   63926     p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
   63927     p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
   63928     p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
   63929     p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
   63930     p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
   63931                           &zCsr, zEnd, &nByte);
   63932     p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte);
   63933     if( nByte ){
   63934       p->pFree = sqlite3DbMallocZero(db, nByte);
   63935     }
   63936     zCsr = p->pFree;
   63937     zEnd = &zCsr[nByte];
   63938   }while( nByte && !db->mallocFailed );
   63939 
   63940   p->nCursor = nCursor;
   63941   p->nOnceFlag = nOnce;
   63942   if( p->aVar ){
   63943     p->nVar = (ynVar)nVar;
   63944     for(n=0; n<nVar; n++){
   63945       p->aVar[n].flags = MEM_Null;
   63946       p->aVar[n].db = db;
   63947     }
   63948   }
   63949   if( p->azVar ){
   63950     p->nzVar = pParse->nzVar;
   63951     memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
   63952     memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
   63953   }
   63954   if( p->aMem ){
   63955     p->aMem--;                      /* aMem[] goes from 1..nMem */
   63956     p->nMem = nMem;                 /*       not from 0..nMem-1 */
   63957     for(n=1; n<=nMem; n++){
   63958       p->aMem[n].flags = MEM_Undefined;
   63959       p->aMem[n].db = db;
   63960     }
   63961   }
   63962   p->explain = pParse->explain;
   63963   sqlite3VdbeRewind(p);
   63964 }
   63965 
   63966 /*
   63967 ** Close a VDBE cursor and release all the resources that cursor
   63968 ** happens to hold.
   63969 */
   63970 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
   63971   if( pCx==0 ){
   63972     return;
   63973   }
   63974   sqlite3VdbeSorterClose(p->db, pCx);
   63975   if( pCx->pBt ){
   63976     sqlite3BtreeClose(pCx->pBt);
   63977     /* The pCx->pCursor will be close automatically, if it exists, by
   63978     ** the call above. */
   63979   }else if( pCx->pCursor ){
   63980     sqlite3BtreeCloseCursor(pCx->pCursor);
   63981   }
   63982 #ifndef SQLITE_OMIT_VIRTUALTABLE
   63983   if( pCx->pVtabCursor ){
   63984     sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
   63985     const sqlite3_module *pModule = pVtabCursor->pVtab->pModule;
   63986     p->inVtabMethod = 1;
   63987     pModule->xClose(pVtabCursor);
   63988     p->inVtabMethod = 0;
   63989   }
   63990 #endif
   63991 }
   63992 
   63993 /*
   63994 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
   63995 ** is used, for example, when a trigger sub-program is halted to restore
   63996 ** control to the main program.
   63997 */
   63998 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
   63999   Vdbe *v = pFrame->v;
   64000   v->aOnceFlag = pFrame->aOnceFlag;
   64001   v->nOnceFlag = pFrame->nOnceFlag;
   64002   v->aOp = pFrame->aOp;
   64003   v->nOp = pFrame->nOp;
   64004   v->aMem = pFrame->aMem;
   64005   v->nMem = pFrame->nMem;
   64006   v->apCsr = pFrame->apCsr;
   64007   v->nCursor = pFrame->nCursor;
   64008   v->db->lastRowid = pFrame->lastRowid;
   64009   v->nChange = pFrame->nChange;
   64010   return pFrame->pc;
   64011 }
   64012 
   64013 /*
   64014 ** Close all cursors.
   64015 **
   64016 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
   64017 ** cell array. This is necessary as the memory cell array may contain
   64018 ** pointers to VdbeFrame objects, which may in turn contain pointers to
   64019 ** open cursors.
   64020 */
   64021 static void closeAllCursors(Vdbe *p){
   64022   if( p->pFrame ){
   64023     VdbeFrame *pFrame;
   64024     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
   64025     sqlite3VdbeFrameRestore(pFrame);
   64026   }
   64027   p->pFrame = 0;
   64028   p->nFrame = 0;
   64029 
   64030   if( p->apCsr ){
   64031     int i;
   64032     for(i=0; i<p->nCursor; i++){
   64033       VdbeCursor *pC = p->apCsr[i];
   64034       if( pC ){
   64035         sqlite3VdbeFreeCursor(p, pC);
   64036         p->apCsr[i] = 0;
   64037       }
   64038     }
   64039   }
   64040   if( p->aMem ){
   64041     releaseMemArray(&p->aMem[1], p->nMem);
   64042   }
   64043   while( p->pDelFrame ){
   64044     VdbeFrame *pDel = p->pDelFrame;
   64045     p->pDelFrame = pDel->pParent;
   64046     sqlite3VdbeFrameDelete(pDel);
   64047   }
   64048 
   64049   /* Delete any auxdata allocations made by the VM */
   64050   sqlite3VdbeDeleteAuxData(p, -1, 0);
   64051   assert( p->pAuxData==0 );
   64052 }
   64053 
   64054 /*
   64055 ** Clean up the VM after execution.
   64056 **
   64057 ** This routine will automatically close any cursors, lists, and/or
   64058 ** sorters that were left open.  It also deletes the values of
   64059 ** variables in the aVar[] array.
   64060 */
   64061 static void Cleanup(Vdbe *p){
   64062   sqlite3 *db = p->db;
   64063 
   64064 #ifdef SQLITE_DEBUG
   64065   /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
   64066   ** Vdbe.aMem[] arrays have already been cleaned up.  */
   64067   int i;
   64068   if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
   64069   if( p->aMem ){
   64070     for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
   64071   }
   64072 #endif
   64073 
   64074   sqlite3DbFree(db, p->zErrMsg);
   64075   p->zErrMsg = 0;
   64076   p->pResultSet = 0;
   64077 }
   64078 
   64079 /*
   64080 ** Set the number of result columns that will be returned by this SQL
   64081 ** statement. This is now set at compile time, rather than during
   64082 ** execution of the vdbe program so that sqlite3_column_count() can
   64083 ** be called on an SQL statement before sqlite3_step().
   64084 */
   64085 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
   64086   Mem *pColName;
   64087   int n;
   64088   sqlite3 *db = p->db;
   64089 
   64090   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
   64091   sqlite3DbFree(db, p->aColName);
   64092   n = nResColumn*COLNAME_N;
   64093   p->nResColumn = (u16)nResColumn;
   64094   p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
   64095   if( p->aColName==0 ) return;
   64096   while( n-- > 0 ){
   64097     pColName->flags = MEM_Null;
   64098     pColName->db = p->db;
   64099     pColName++;
   64100   }
   64101 }
   64102 
   64103 /*
   64104 ** Set the name of the idx'th column to be returned by the SQL statement.
   64105 ** zName must be a pointer to a nul terminated string.
   64106 **
   64107 ** This call must be made after a call to sqlite3VdbeSetNumCols().
   64108 **
   64109 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
   64110 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
   64111 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
   64112 */
   64113 SQLITE_PRIVATE int sqlite3VdbeSetColName(
   64114   Vdbe *p,                         /* Vdbe being configured */
   64115   int idx,                         /* Index of column zName applies to */
   64116   int var,                         /* One of the COLNAME_* constants */
   64117   const char *zName,               /* Pointer to buffer containing name */
   64118   void (*xDel)(void*)              /* Memory management strategy for zName */
   64119 ){
   64120   int rc;
   64121   Mem *pColName;
   64122   assert( idx<p->nResColumn );
   64123   assert( var<COLNAME_N );
   64124   if( p->db->mallocFailed ){
   64125     assert( !zName || xDel!=SQLITE_DYNAMIC );
   64126     return SQLITE_NOMEM;
   64127   }
   64128   assert( p->aColName!=0 );
   64129   pColName = &(p->aColName[idx+var*p->nResColumn]);
   64130   rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
   64131   assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
   64132   return rc;
   64133 }
   64134 
   64135 /*
   64136 ** A read or write transaction may or may not be active on database handle
   64137 ** db. If a transaction is active, commit it. If there is a
   64138 ** write-transaction spanning more than one database file, this routine
   64139 ** takes care of the master journal trickery.
   64140 */
   64141 static int vdbeCommit(sqlite3 *db, Vdbe *p){
   64142   int i;
   64143   int nTrans = 0;  /* Number of databases with an active write-transaction */
   64144   int rc = SQLITE_OK;
   64145   int needXcommit = 0;
   64146 
   64147 #ifdef SQLITE_OMIT_VIRTUALTABLE
   64148   /* With this option, sqlite3VtabSync() is defined to be simply
   64149   ** SQLITE_OK so p is not used.
   64150   */
   64151   UNUSED_PARAMETER(p);
   64152 #endif
   64153 
   64154   /* Before doing anything else, call the xSync() callback for any
   64155   ** virtual module tables written in this transaction. This has to
   64156   ** be done before determining whether a master journal file is
   64157   ** required, as an xSync() callback may add an attached database
   64158   ** to the transaction.
   64159   */
   64160   rc = sqlite3VtabSync(db, p);
   64161 
   64162   /* This loop determines (a) if the commit hook should be invoked and
   64163   ** (b) how many database files have open write transactions, not
   64164   ** including the temp database. (b) is important because if more than
   64165   ** one database file has an open write transaction, a master journal
   64166   ** file is required for an atomic commit.
   64167   */
   64168   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
   64169     Btree *pBt = db->aDb[i].pBt;
   64170     if( sqlite3BtreeIsInTrans(pBt) ){
   64171       needXcommit = 1;
   64172       if( i!=1 ) nTrans++;
   64173       sqlite3BtreeEnter(pBt);
   64174       rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
   64175       sqlite3BtreeLeave(pBt);
   64176     }
   64177   }
   64178   if( rc!=SQLITE_OK ){
   64179     return rc;
   64180   }
   64181 
   64182   /* If there are any write-transactions at all, invoke the commit hook */
   64183   if( needXcommit && db->xCommitCallback ){
   64184     rc = db->xCommitCallback(db->pCommitArg);
   64185     if( rc ){
   64186       return SQLITE_CONSTRAINT_COMMITHOOK;
   64187     }
   64188   }
   64189 
   64190   /* The simple case - no more than one database file (not counting the
   64191   ** TEMP database) has a transaction active.   There is no need for the
   64192   ** master-journal.
   64193   **
   64194   ** If the return value of sqlite3BtreeGetFilename() is a zero length
   64195   ** string, it means the main database is :memory: or a temp file.  In
   64196   ** that case we do not support atomic multi-file commits, so use the
   64197   ** simple case then too.
   64198   */
   64199   if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
   64200    || nTrans<=1
   64201   ){
   64202     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
   64203       Btree *pBt = db->aDb[i].pBt;
   64204       if( pBt ){
   64205         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
   64206       }
   64207     }
   64208 
   64209     /* Do the commit only if all databases successfully complete phase 1.
   64210     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
   64211     ** IO error while deleting or truncating a journal file. It is unlikely,
   64212     ** but could happen. In this case abandon processing and return the error.
   64213     */
   64214     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
   64215       Btree *pBt = db->aDb[i].pBt;
   64216       if( pBt ){
   64217         rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
   64218       }
   64219     }
   64220     if( rc==SQLITE_OK ){
   64221       sqlite3VtabCommit(db);
   64222     }
   64223   }
   64224 
   64225   /* The complex case - There is a multi-file write-transaction active.
   64226   ** This requires a master journal file to ensure the transaction is
   64227   ** committed atomicly.
   64228   */
   64229 #ifndef SQLITE_OMIT_DISKIO
   64230   else{
   64231     sqlite3_vfs *pVfs = db->pVfs;
   64232     int needSync = 0;
   64233     char *zMaster = 0;   /* File-name for the master journal */
   64234     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
   64235     sqlite3_file *pMaster = 0;
   64236     i64 offset = 0;
   64237     int res;
   64238     int retryCount = 0;
   64239     int nMainFile;
   64240 
   64241     /* Select a master journal file name */
   64242     nMainFile = sqlite3Strlen30(zMainFile);
   64243     zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
   64244     if( zMaster==0 ) return SQLITE_NOMEM;
   64245     do {
   64246       u32 iRandom;
   64247       if( retryCount ){
   64248         if( retryCount>100 ){
   64249           sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
   64250           sqlite3OsDelete(pVfs, zMaster, 0);
   64251           break;
   64252         }else if( retryCount==1 ){
   64253           sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
   64254         }
   64255       }
   64256       retryCount++;
   64257       sqlite3_randomness(sizeof(iRandom), &iRandom);
   64258       sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
   64259                                (iRandom>>8)&0xffffff, iRandom&0xff);
   64260       /* The antipenultimate character of the master journal name must
   64261       ** be "9" to avoid name collisions when using 8+3 filenames. */
   64262       assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
   64263       sqlite3FileSuffix3(zMainFile, zMaster);
   64264       rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
   64265     }while( rc==SQLITE_OK && res );
   64266     if( rc==SQLITE_OK ){
   64267       /* Open the master journal. */
   64268       rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
   64269           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
   64270           SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
   64271       );
   64272     }
   64273     if( rc!=SQLITE_OK ){
   64274       sqlite3DbFree(db, zMaster);
   64275       return rc;
   64276     }
   64277 
   64278     /* Write the name of each database file in the transaction into the new
   64279     ** master journal file. If an error occurs at this point close
   64280     ** and delete the master journal file. All the individual journal files
   64281     ** still have 'null' as the master journal pointer, so they will roll
   64282     ** back independently if a failure occurs.
   64283     */
   64284     for(i=0; i<db->nDb; i++){
   64285       Btree *pBt = db->aDb[i].pBt;
   64286       if( sqlite3BtreeIsInTrans(pBt) ){
   64287         char const *zFile = sqlite3BtreeGetJournalname(pBt);
   64288         if( zFile==0 ){
   64289           continue;  /* Ignore TEMP and :memory: databases */
   64290         }
   64291         assert( zFile[0]!=0 );
   64292         if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
   64293           needSync = 1;
   64294         }
   64295         rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
   64296         offset += sqlite3Strlen30(zFile)+1;
   64297         if( rc!=SQLITE_OK ){
   64298           sqlite3OsCloseFree(pMaster);
   64299           sqlite3OsDelete(pVfs, zMaster, 0);
   64300           sqlite3DbFree(db, zMaster);
   64301           return rc;
   64302         }
   64303       }
   64304     }
   64305 
   64306     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
   64307     ** flag is set this is not required.
   64308     */
   64309     if( needSync
   64310      && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
   64311      && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
   64312     ){
   64313       sqlite3OsCloseFree(pMaster);
   64314       sqlite3OsDelete(pVfs, zMaster, 0);
   64315       sqlite3DbFree(db, zMaster);
   64316       return rc;
   64317     }
   64318 
   64319     /* Sync all the db files involved in the transaction. The same call
   64320     ** sets the master journal pointer in each individual journal. If
   64321     ** an error occurs here, do not delete the master journal file.
   64322     **
   64323     ** If the error occurs during the first call to
   64324     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
   64325     ** master journal file will be orphaned. But we cannot delete it,
   64326     ** in case the master journal file name was written into the journal
   64327     ** file before the failure occurred.
   64328     */
   64329     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
   64330       Btree *pBt = db->aDb[i].pBt;
   64331       if( pBt ){
   64332         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
   64333       }
   64334     }
   64335     sqlite3OsCloseFree(pMaster);
   64336     assert( rc!=SQLITE_BUSY );
   64337     if( rc!=SQLITE_OK ){
   64338       sqlite3DbFree(db, zMaster);
   64339       return rc;
   64340     }
   64341 
   64342     /* Delete the master journal file. This commits the transaction. After
   64343     ** doing this the directory is synced again before any individual
   64344     ** transaction files are deleted.
   64345     */
   64346     rc = sqlite3OsDelete(pVfs, zMaster, 1);
   64347     sqlite3DbFree(db, zMaster);
   64348     zMaster = 0;
   64349     if( rc ){
   64350       return rc;
   64351     }
   64352 
   64353     /* All files and directories have already been synced, so the following
   64354     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
   64355     ** deleting or truncating journals. If something goes wrong while
   64356     ** this is happening we don't really care. The integrity of the
   64357     ** transaction is already guaranteed, but some stray 'cold' journals
   64358     ** may be lying around. Returning an error code won't help matters.
   64359     */
   64360     disable_simulated_io_errors();
   64361     sqlite3BeginBenignMalloc();
   64362     for(i=0; i<db->nDb; i++){
   64363       Btree *pBt = db->aDb[i].pBt;
   64364       if( pBt ){
   64365         sqlite3BtreeCommitPhaseTwo(pBt, 1);
   64366       }
   64367     }
   64368     sqlite3EndBenignMalloc();
   64369     enable_simulated_io_errors();
   64370 
   64371     sqlite3VtabCommit(db);
   64372   }
   64373 #endif
   64374 
   64375   return rc;
   64376 }
   64377 
   64378 /*
   64379 ** This routine checks that the sqlite3.nVdbeActive count variable
   64380 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
   64381 ** currently active. An assertion fails if the two counts do not match.
   64382 ** This is an internal self-check only - it is not an essential processing
   64383 ** step.
   64384 **
   64385 ** This is a no-op if NDEBUG is defined.
   64386 */
   64387 #ifndef NDEBUG
   64388 static void checkActiveVdbeCnt(sqlite3 *db){
   64389   Vdbe *p;
   64390   int cnt = 0;
   64391   int nWrite = 0;
   64392   int nRead = 0;
   64393   p = db->pVdbe;
   64394   while( p ){
   64395     if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
   64396       cnt++;
   64397       if( p->readOnly==0 ) nWrite++;
   64398       if( p->bIsReader ) nRead++;
   64399     }
   64400     p = p->pNext;
   64401   }
   64402   assert( cnt==db->nVdbeActive );
   64403   assert( nWrite==db->nVdbeWrite );
   64404   assert( nRead==db->nVdbeRead );
   64405 }
   64406 #else
   64407 #define checkActiveVdbeCnt(x)
   64408 #endif
   64409 
   64410 /*
   64411 ** If the Vdbe passed as the first argument opened a statement-transaction,
   64412 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
   64413 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
   64414 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
   64415 ** statement transaction is committed.
   64416 **
   64417 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
   64418 ** Otherwise SQLITE_OK.
   64419 */
   64420 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
   64421   sqlite3 *const db = p->db;
   64422   int rc = SQLITE_OK;
   64423 
   64424   /* If p->iStatement is greater than zero, then this Vdbe opened a
   64425   ** statement transaction that should be closed here. The only exception
   64426   ** is that an IO error may have occurred, causing an emergency rollback.
   64427   ** In this case (db->nStatement==0), and there is nothing to do.
   64428   */
   64429   if( db->nStatement && p->iStatement ){
   64430     int i;
   64431     const int iSavepoint = p->iStatement-1;
   64432 
   64433     assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
   64434     assert( db->nStatement>0 );
   64435     assert( p->iStatement==(db->nStatement+db->nSavepoint) );
   64436 
   64437     for(i=0; i<db->nDb; i++){
   64438       int rc2 = SQLITE_OK;
   64439       Btree *pBt = db->aDb[i].pBt;
   64440       if( pBt ){
   64441         if( eOp==SAVEPOINT_ROLLBACK ){
   64442           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
   64443         }
   64444         if( rc2==SQLITE_OK ){
   64445           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
   64446         }
   64447         if( rc==SQLITE_OK ){
   64448           rc = rc2;
   64449         }
   64450       }
   64451     }
   64452     db->nStatement--;
   64453     p->iStatement = 0;
   64454 
   64455     if( rc==SQLITE_OK ){
   64456       if( eOp==SAVEPOINT_ROLLBACK ){
   64457         rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
   64458       }
   64459       if( rc==SQLITE_OK ){
   64460         rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
   64461       }
   64462     }
   64463 
   64464     /* If the statement transaction is being rolled back, also restore the
   64465     ** database handles deferred constraint counter to the value it had when
   64466     ** the statement transaction was opened.  */
   64467     if( eOp==SAVEPOINT_ROLLBACK ){
   64468       db->nDeferredCons = p->nStmtDefCons;
   64469       db->nDeferredImmCons = p->nStmtDefImmCons;
   64470     }
   64471   }
   64472   return rc;
   64473 }
   64474 
   64475 /*
   64476 ** This function is called when a transaction opened by the database
   64477 ** handle associated with the VM passed as an argument is about to be
   64478 ** committed. If there are outstanding deferred foreign key constraint
   64479 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
   64480 **
   64481 ** If there are outstanding FK violations and this function returns
   64482 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
   64483 ** and write an error message to it. Then return SQLITE_ERROR.
   64484 */
   64485 #ifndef SQLITE_OMIT_FOREIGN_KEY
   64486 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
   64487   sqlite3 *db = p->db;
   64488   if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
   64489    || (!deferred && p->nFkConstraint>0)
   64490   ){
   64491     p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
   64492     p->errorAction = OE_Abort;
   64493     sqlite3SetString(&p->zErrMsg, db, "FOREIGN KEY constraint failed");
   64494     return SQLITE_ERROR;
   64495   }
   64496   return SQLITE_OK;
   64497 }
   64498 #endif
   64499 
   64500 /*
   64501 ** This routine is called the when a VDBE tries to halt.  If the VDBE
   64502 ** has made changes and is in autocommit mode, then commit those
   64503 ** changes.  If a rollback is needed, then do the rollback.
   64504 **
   64505 ** This routine is the only way to move the state of a VM from
   64506 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
   64507 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
   64508 **
   64509 ** Return an error code.  If the commit could not complete because of
   64510 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
   64511 ** means the close did not happen and needs to be repeated.
   64512 */
   64513 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
   64514   int rc;                         /* Used to store transient return codes */
   64515   sqlite3 *db = p->db;
   64516 
   64517   /* This function contains the logic that determines if a statement or
   64518   ** transaction will be committed or rolled back as a result of the
   64519   ** execution of this virtual machine.
   64520   **
   64521   ** If any of the following errors occur:
   64522   **
   64523   **     SQLITE_NOMEM
   64524   **     SQLITE_IOERR
   64525   **     SQLITE_FULL
   64526   **     SQLITE_INTERRUPT
   64527   **
   64528   ** Then the internal cache might have been left in an inconsistent
   64529   ** state.  We need to rollback the statement transaction, if there is
   64530   ** one, or the complete transaction if there is no statement transaction.
   64531   */
   64532 
   64533   if( p->db->mallocFailed ){
   64534     p->rc = SQLITE_NOMEM;
   64535   }
   64536   if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
   64537   closeAllCursors(p);
   64538   if( p->magic!=VDBE_MAGIC_RUN ){
   64539     return SQLITE_OK;
   64540   }
   64541   checkActiveVdbeCnt(db);
   64542 
   64543   /* No commit or rollback needed if the program never started or if the
   64544   ** SQL statement does not read or write a database file.  */
   64545   if( p->pc>=0 && p->bIsReader ){
   64546     int mrc;   /* Primary error code from p->rc */
   64547     int eStatementOp = 0;
   64548     int isSpecialError;            /* Set to true if a 'special' error */
   64549 
   64550     /* Lock all btrees used by the statement */
   64551     sqlite3VdbeEnter(p);
   64552 
   64553     /* Check for one of the special errors */
   64554     mrc = p->rc & 0xff;
   64555     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
   64556                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
   64557     if( isSpecialError ){
   64558       /* If the query was read-only and the error code is SQLITE_INTERRUPT,
   64559       ** no rollback is necessary. Otherwise, at least a savepoint
   64560       ** transaction must be rolled back to restore the database to a
   64561       ** consistent state.
   64562       **
   64563       ** Even if the statement is read-only, it is important to perform
   64564       ** a statement or transaction rollback operation. If the error
   64565       ** occurred while writing to the journal, sub-journal or database
   64566       ** file as part of an effort to free up cache space (see function
   64567       ** pagerStress() in pager.c), the rollback is required to restore
   64568       ** the pager to a consistent state.
   64569       */
   64570       if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
   64571         if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
   64572           eStatementOp = SAVEPOINT_ROLLBACK;
   64573         }else{
   64574           /* We are forced to roll back the active transaction. Before doing
   64575           ** so, abort any other statements this handle currently has active.
   64576           */
   64577           sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
   64578           sqlite3CloseSavepoints(db);
   64579           db->autoCommit = 1;
   64580         }
   64581       }
   64582     }
   64583 
   64584     /* Check for immediate foreign key violations. */
   64585     if( p->rc==SQLITE_OK ){
   64586       sqlite3VdbeCheckFk(p, 0);
   64587     }
   64588 
   64589     /* If the auto-commit flag is set and this is the only active writer
   64590     ** VM, then we do either a commit or rollback of the current transaction.
   64591     **
   64592     ** Note: This block also runs if one of the special errors handled
   64593     ** above has occurred.
   64594     */
   64595     if( !sqlite3VtabInSync(db)
   64596      && db->autoCommit
   64597      && db->nVdbeWrite==(p->readOnly==0)
   64598     ){
   64599       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
   64600         rc = sqlite3VdbeCheckFk(p, 1);
   64601         if( rc!=SQLITE_OK ){
   64602           if( NEVER(p->readOnly) ){
   64603             sqlite3VdbeLeave(p);
   64604             return SQLITE_ERROR;
   64605           }
   64606           rc = SQLITE_CONSTRAINT_FOREIGNKEY;
   64607         }else{
   64608           /* The auto-commit flag is true, the vdbe program was successful
   64609           ** or hit an 'OR FAIL' constraint and there are no deferred foreign
   64610           ** key constraints to hold up the transaction. This means a commit
   64611           ** is required. */
   64612           rc = vdbeCommit(db, p);
   64613         }
   64614         if( rc==SQLITE_BUSY && p->readOnly ){
   64615           sqlite3VdbeLeave(p);
   64616           return SQLITE_BUSY;
   64617         }else if( rc!=SQLITE_OK ){
   64618           p->rc = rc;
   64619           sqlite3RollbackAll(db, SQLITE_OK);
   64620         }else{
   64621           db->nDeferredCons = 0;
   64622           db->nDeferredImmCons = 0;
   64623           db->flags &= ~SQLITE_DeferFKs;
   64624           sqlite3CommitInternalChanges(db);
   64625         }
   64626       }else{
   64627         sqlite3RollbackAll(db, SQLITE_OK);
   64628       }
   64629       db->nStatement = 0;
   64630     }else if( eStatementOp==0 ){
   64631       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
   64632         eStatementOp = SAVEPOINT_RELEASE;
   64633       }else if( p->errorAction==OE_Abort ){
   64634         eStatementOp = SAVEPOINT_ROLLBACK;
   64635       }else{
   64636         sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
   64637         sqlite3CloseSavepoints(db);
   64638         db->autoCommit = 1;
   64639       }
   64640     }
   64641 
   64642     /* If eStatementOp is non-zero, then a statement transaction needs to
   64643     ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
   64644     ** do so. If this operation returns an error, and the current statement
   64645     ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
   64646     ** current statement error code.
   64647     */
   64648     if( eStatementOp ){
   64649       rc = sqlite3VdbeCloseStatement(p, eStatementOp);
   64650       if( rc ){
   64651         if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
   64652           p->rc = rc;
   64653           sqlite3DbFree(db, p->zErrMsg);
   64654           p->zErrMsg = 0;
   64655         }
   64656         sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
   64657         sqlite3CloseSavepoints(db);
   64658         db->autoCommit = 1;
   64659       }
   64660     }
   64661 
   64662     /* If this was an INSERT, UPDATE or DELETE and no statement transaction
   64663     ** has been rolled back, update the database connection change-counter.
   64664     */
   64665     if( p->changeCntOn ){
   64666       if( eStatementOp!=SAVEPOINT_ROLLBACK ){
   64667         sqlite3VdbeSetChanges(db, p->nChange);
   64668       }else{
   64669         sqlite3VdbeSetChanges(db, 0);
   64670       }
   64671       p->nChange = 0;
   64672     }
   64673 
   64674     /* Release the locks */
   64675     sqlite3VdbeLeave(p);
   64676   }
   64677 
   64678   /* We have successfully halted and closed the VM.  Record this fact. */
   64679   if( p->pc>=0 ){
   64680     db->nVdbeActive--;
   64681     if( !p->readOnly ) db->nVdbeWrite--;
   64682     if( p->bIsReader ) db->nVdbeRead--;
   64683     assert( db->nVdbeActive>=db->nVdbeRead );
   64684     assert( db->nVdbeRead>=db->nVdbeWrite );
   64685     assert( db->nVdbeWrite>=0 );
   64686   }
   64687   p->magic = VDBE_MAGIC_HALT;
   64688   checkActiveVdbeCnt(db);
   64689   if( p->db->mallocFailed ){
   64690     p->rc = SQLITE_NOMEM;
   64691   }
   64692 
   64693   /* If the auto-commit flag is set to true, then any locks that were held
   64694   ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
   64695   ** to invoke any required unlock-notify callbacks.
   64696   */
   64697   if( db->autoCommit ){
   64698     sqlite3ConnectionUnlocked(db);
   64699   }
   64700 
   64701   assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
   64702   return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
   64703 }
   64704 
   64705 
   64706 /*
   64707 ** Each VDBE holds the result of the most recent sqlite3_step() call
   64708 ** in p->rc.  This routine sets that result back to SQLITE_OK.
   64709 */
   64710 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
   64711   p->rc = SQLITE_OK;
   64712 }
   64713 
   64714 /*
   64715 ** Copy the error code and error message belonging to the VDBE passed
   64716 ** as the first argument to its database handle (so that they will be
   64717 ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
   64718 **
   64719 ** This function does not clear the VDBE error code or message, just
   64720 ** copies them to the database handle.
   64721 */
   64722 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
   64723   sqlite3 *db = p->db;
   64724   int rc = p->rc;
   64725   if( p->zErrMsg ){
   64726     u8 mallocFailed = db->mallocFailed;
   64727     sqlite3BeginBenignMalloc();
   64728     if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
   64729     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
   64730     sqlite3EndBenignMalloc();
   64731     db->mallocFailed = mallocFailed;
   64732     db->errCode = rc;
   64733   }else{
   64734     sqlite3Error(db, rc, 0);
   64735   }
   64736   return rc;
   64737 }
   64738 
   64739 #ifdef SQLITE_ENABLE_SQLLOG
   64740 /*
   64741 ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
   64742 ** invoke it.
   64743 */
   64744 static void vdbeInvokeSqllog(Vdbe *v){
   64745   if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
   64746     char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
   64747     assert( v->db->init.busy==0 );
   64748     if( zExpanded ){
   64749       sqlite3GlobalConfig.xSqllog(
   64750           sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
   64751       );
   64752       sqlite3DbFree(v->db, zExpanded);
   64753     }
   64754   }
   64755 }
   64756 #else
   64757 # define vdbeInvokeSqllog(x)
   64758 #endif
   64759 
   64760 /*
   64761 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
   64762 ** Write any error messages into *pzErrMsg.  Return the result code.
   64763 **
   64764 ** After this routine is run, the VDBE should be ready to be executed
   64765 ** again.
   64766 **
   64767 ** To look at it another way, this routine resets the state of the
   64768 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
   64769 ** VDBE_MAGIC_INIT.
   64770 */
   64771 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
   64772   sqlite3 *db;
   64773   db = p->db;
   64774 
   64775   /* If the VM did not run to completion or if it encountered an
   64776   ** error, then it might not have been halted properly.  So halt
   64777   ** it now.
   64778   */
   64779   sqlite3VdbeHalt(p);
   64780 
   64781   /* If the VDBE has be run even partially, then transfer the error code
   64782   ** and error message from the VDBE into the main database structure.  But
   64783   ** if the VDBE has just been set to run but has not actually executed any
   64784   ** instructions yet, leave the main database error information unchanged.
   64785   */
   64786   if( p->pc>=0 ){
   64787     vdbeInvokeSqllog(p);
   64788     sqlite3VdbeTransferError(p);
   64789     sqlite3DbFree(db, p->zErrMsg);
   64790     p->zErrMsg = 0;
   64791     if( p->runOnlyOnce ) p->expired = 1;
   64792   }else if( p->rc && p->expired ){
   64793     /* The expired flag was set on the VDBE before the first call
   64794     ** to sqlite3_step(). For consistency (since sqlite3_step() was
   64795     ** called), set the database error in this case as well.
   64796     */
   64797     sqlite3Error(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
   64798     sqlite3DbFree(db, p->zErrMsg);
   64799     p->zErrMsg = 0;
   64800   }
   64801 
   64802   /* Reclaim all memory used by the VDBE
   64803   */
   64804   Cleanup(p);
   64805 
   64806   /* Save profiling information from this VDBE run.
   64807   */
   64808 #ifdef VDBE_PROFILE
   64809   {
   64810     FILE *out = fopen("vdbe_profile.out", "a");
   64811     if( out ){
   64812       int i;
   64813       fprintf(out, "---- ");
   64814       for(i=0; i<p->nOp; i++){
   64815         fprintf(out, "%02x", p->aOp[i].opcode);
   64816       }
   64817       fprintf(out, "\n");
   64818       if( p->zSql ){
   64819         char c, pc = 0;
   64820         fprintf(out, "-- ");
   64821         for(i=0; (c = p->zSql[i])!=0; i++){
   64822           if( pc=='\n' ) fprintf(out, "-- ");
   64823           putc(c, out);
   64824           pc = c;
   64825         }
   64826         if( pc!='\n' ) fprintf(out, "\n");
   64827       }
   64828       for(i=0; i<p->nOp; i++){
   64829         char zHdr[100];
   64830         sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
   64831            p->aOp[i].cnt,
   64832            p->aOp[i].cycles,
   64833            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
   64834         );
   64835         fprintf(out, "%s", zHdr);
   64836         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
   64837       }
   64838       fclose(out);
   64839     }
   64840   }
   64841 #endif
   64842   p->iCurrentTime = 0;
   64843   p->magic = VDBE_MAGIC_INIT;
   64844   return p->rc & db->errMask;
   64845 }
   64846 
   64847 /*
   64848 ** Clean up and delete a VDBE after execution.  Return an integer which is
   64849 ** the result code.  Write any error message text into *pzErrMsg.
   64850 */
   64851 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
   64852   int rc = SQLITE_OK;
   64853   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
   64854     rc = sqlite3VdbeReset(p);
   64855     assert( (rc & p->db->errMask)==rc );
   64856   }
   64857   sqlite3VdbeDelete(p);
   64858   return rc;
   64859 }
   64860 
   64861 /*
   64862 ** If parameter iOp is less than zero, then invoke the destructor for
   64863 ** all auxiliary data pointers currently cached by the VM passed as
   64864 ** the first argument.
   64865 **
   64866 ** Or, if iOp is greater than or equal to zero, then the destructor is
   64867 ** only invoked for those auxiliary data pointers created by the user
   64868 ** function invoked by the OP_Function opcode at instruction iOp of
   64869 ** VM pVdbe, and only then if:
   64870 **
   64871 **    * the associated function parameter is the 32nd or later (counting
   64872 **      from left to right), or
   64873 **
   64874 **    * the corresponding bit in argument mask is clear (where the first
   64875 **      function parameter corrsponds to bit 0 etc.).
   64876 */
   64877 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe *pVdbe, int iOp, int mask){
   64878   AuxData **pp = &pVdbe->pAuxData;
   64879   while( *pp ){
   64880     AuxData *pAux = *pp;
   64881     if( (iOp<0)
   64882      || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & MASKBIT32(pAux->iArg))))
   64883     ){
   64884       testcase( pAux->iArg==31 );
   64885       if( pAux->xDelete ){
   64886         pAux->xDelete(pAux->pAux);
   64887       }
   64888       *pp = pAux->pNext;
   64889       sqlite3DbFree(pVdbe->db, pAux);
   64890     }else{
   64891       pp= &pAux->pNext;
   64892     }
   64893   }
   64894 }
   64895 
   64896 /*
   64897 ** Free all memory associated with the Vdbe passed as the second argument,
   64898 ** except for object itself, which is preserved.
   64899 **
   64900 ** The difference between this function and sqlite3VdbeDelete() is that
   64901 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
   64902 ** the database connection and frees the object itself.
   64903 */
   64904 SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
   64905   SubProgram *pSub, *pNext;
   64906   int i;
   64907   assert( p->db==0 || p->db==db );
   64908   releaseMemArray(p->aVar, p->nVar);
   64909   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
   64910   for(pSub=p->pProgram; pSub; pSub=pNext){
   64911     pNext = pSub->pNext;
   64912     vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
   64913     sqlite3DbFree(db, pSub);
   64914   }
   64915   for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
   64916   vdbeFreeOpArray(db, p->aOp, p->nOp);
   64917   sqlite3DbFree(db, p->aColName);
   64918   sqlite3DbFree(db, p->zSql);
   64919   sqlite3DbFree(db, p->pFree);
   64920 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
   64921   sqlite3DbFree(db, p->zExplain);
   64922   sqlite3DbFree(db, p->pExplain);
   64923 #endif
   64924 }
   64925 
   64926 /*
   64927 ** Delete an entire VDBE.
   64928 */
   64929 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
   64930   sqlite3 *db;
   64931 
   64932   if( NEVER(p==0) ) return;
   64933   db = p->db;
   64934   assert( sqlite3_mutex_held(db->mutex) );
   64935   sqlite3VdbeClearObject(db, p);
   64936   if( p->pPrev ){
   64937     p->pPrev->pNext = p->pNext;
   64938   }else{
   64939     assert( db->pVdbe==p );
   64940     db->pVdbe = p->pNext;
   64941   }
   64942   if( p->pNext ){
   64943     p->pNext->pPrev = p->pPrev;
   64944   }
   64945   p->magic = VDBE_MAGIC_DEAD;
   64946   p->db = 0;
   64947   sqlite3DbFree(db, p);
   64948 }
   64949 
   64950 /*
   64951 ** Make sure the cursor p is ready to read or write the row to which it
   64952 ** was last positioned.  Return an error code if an OOM fault or I/O error
   64953 ** prevents us from positioning the cursor to its correct position.
   64954 **
   64955 ** If a MoveTo operation is pending on the given cursor, then do that
   64956 ** MoveTo now.  If no move is pending, check to see if the row has been
   64957 ** deleted out from under the cursor and if it has, mark the row as
   64958 ** a NULL row.
   64959 **
   64960 ** If the cursor is already pointing to the correct row and that row has
   64961 ** not been deleted out from under the cursor, then this routine is a no-op.
   64962 */
   64963 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
   64964   if( p->deferredMoveto ){
   64965     int res, rc;
   64966 #ifdef SQLITE_TEST
   64967     extern int sqlite3_search_count;
   64968 #endif
   64969     assert( p->isTable );
   64970     rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
   64971     if( rc ) return rc;
   64972     p->lastRowid = p->movetoTarget;
   64973     if( res!=0 ) return SQLITE_CORRUPT_BKPT;
   64974     p->rowidIsValid = 1;
   64975 #ifdef SQLITE_TEST
   64976     sqlite3_search_count++;
   64977 #endif
   64978     p->deferredMoveto = 0;
   64979     p->cacheStatus = CACHE_STALE;
   64980   }else if( p->pCursor ){
   64981     int hasMoved;
   64982     int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
   64983     if( rc ) return rc;
   64984     if( hasMoved ){
   64985       p->cacheStatus = CACHE_STALE;
   64986       if( hasMoved==2 ) p->nullRow = 1;
   64987     }
   64988   }
   64989   return SQLITE_OK;
   64990 }
   64991 
   64992 /*
   64993 ** The following functions:
   64994 **
   64995 ** sqlite3VdbeSerialType()
   64996 ** sqlite3VdbeSerialTypeLen()
   64997 ** sqlite3VdbeSerialLen()
   64998 ** sqlite3VdbeSerialPut()
   64999 ** sqlite3VdbeSerialGet()
   65000 **
   65001 ** encapsulate the code that serializes values for storage in SQLite
   65002 ** data and index records. Each serialized value consists of a
   65003 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
   65004 ** integer, stored as a varint.
   65005 **
   65006 ** In an SQLite index record, the serial type is stored directly before
   65007 ** the blob of data that it corresponds to. In a table record, all serial
   65008 ** types are stored at the start of the record, and the blobs of data at
   65009 ** the end. Hence these functions allow the caller to handle the
   65010 ** serial-type and data blob separately.
   65011 **
   65012 ** The following table describes the various storage classes for data:
   65013 **
   65014 **   serial type        bytes of data      type
   65015 **   --------------     ---------------    ---------------
   65016 **      0                     0            NULL
   65017 **      1                     1            signed integer
   65018 **      2                     2            signed integer
   65019 **      3                     3            signed integer
   65020 **      4                     4            signed integer
   65021 **      5                     6            signed integer
   65022 **      6                     8            signed integer
   65023 **      7                     8            IEEE float
   65024 **      8                     0            Integer constant 0
   65025 **      9                     0            Integer constant 1
   65026 **     10,11                               reserved for expansion
   65027 **    N>=12 and even       (N-12)/2        BLOB
   65028 **    N>=13 and odd        (N-13)/2        text
   65029 **
   65030 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
   65031 ** of SQLite will not understand those serial types.
   65032 */
   65033 
   65034 /*
   65035 ** Return the serial-type for the value stored in pMem.
   65036 */
   65037 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
   65038   int flags = pMem->flags;
   65039   u32 n;
   65040 
   65041   if( flags&MEM_Null ){
   65042     return 0;
   65043   }
   65044   if( flags&MEM_Int ){
   65045     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
   65046 #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
   65047     i64 i = pMem->u.i;
   65048     u64 u;
   65049     if( i<0 ){
   65050       if( i<(-MAX_6BYTE) ) return 6;
   65051       /* Previous test prevents:  u = -(-9223372036854775808) */
   65052       u = -i;
   65053     }else{
   65054       u = i;
   65055     }
   65056     if( u<=127 ){
   65057       return ((i&1)==i && file_format>=4) ? 8+(u32)u : 1;
   65058     }
   65059     if( u<=32767 ) return 2;
   65060     if( u<=8388607 ) return 3;
   65061     if( u<=2147483647 ) return 4;
   65062     if( u<=MAX_6BYTE ) return 5;
   65063     return 6;
   65064   }
   65065   if( flags&MEM_Real ){
   65066     return 7;
   65067   }
   65068   assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
   65069   assert( pMem->n>=0 );
   65070   n = (u32)pMem->n;
   65071   if( flags & MEM_Zero ){
   65072     n += pMem->u.nZero;
   65073   }
   65074   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
   65075 }
   65076 
   65077 /*
   65078 ** Return the length of the data corresponding to the supplied serial-type.
   65079 */
   65080 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
   65081   if( serial_type>=12 ){
   65082     return (serial_type-12)/2;
   65083   }else{
   65084     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
   65085     return aSize[serial_type];
   65086   }
   65087 }
   65088 
   65089 /*
   65090 ** If we are on an architecture with mixed-endian floating
   65091 ** points (ex: ARM7) then swap the lower 4 bytes with the
   65092 ** upper 4 bytes.  Return the result.
   65093 **
   65094 ** For most architectures, this is a no-op.
   65095 **
   65096 ** (later):  It is reported to me that the mixed-endian problem
   65097 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
   65098 ** that early versions of GCC stored the two words of a 64-bit
   65099 ** float in the wrong order.  And that error has been propagated
   65100 ** ever since.  The blame is not necessarily with GCC, though.
   65101 ** GCC might have just copying the problem from a prior compiler.
   65102 ** I am also told that newer versions of GCC that follow a different
   65103 ** ABI get the byte order right.
   65104 **
   65105 ** Developers using SQLite on an ARM7 should compile and run their
   65106 ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
   65107 ** enabled, some asserts below will ensure that the byte order of
   65108 ** floating point values is correct.
   65109 **
   65110 ** (2007-08-30)  Frank van Vugt has studied this problem closely
   65111 ** and has send his findings to the SQLite developers.  Frank
   65112 ** writes that some Linux kernels offer floating point hardware
   65113 ** emulation that uses only 32-bit mantissas instead of a full
   65114 ** 48-bits as required by the IEEE standard.  (This is the
   65115 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
   65116 ** byte swapping becomes very complicated.  To avoid problems,
   65117 ** the necessary byte swapping is carried out using a 64-bit integer
   65118 ** rather than a 64-bit float.  Frank assures us that the code here
   65119 ** works for him.  We, the developers, have no way to independently
   65120 ** verify this, but Frank seems to know what he is talking about
   65121 ** so we trust him.
   65122 */
   65123 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
   65124 static u64 floatSwap(u64 in){
   65125   union {
   65126     u64 r;
   65127     u32 i[2];
   65128   } u;
   65129   u32 t;
   65130 
   65131   u.r = in;
   65132   t = u.i[0];
   65133   u.i[0] = u.i[1];
   65134   u.i[1] = t;
   65135   return u.r;
   65136 }
   65137 # define swapMixedEndianFloat(X)  X = floatSwap(X)
   65138 #else
   65139 # define swapMixedEndianFloat(X)
   65140 #endif
   65141 
   65142 /*
   65143 ** Write the serialized data blob for the value stored in pMem into
   65144 ** buf. It is assumed that the caller has allocated sufficient space.
   65145 ** Return the number of bytes written.
   65146 **
   65147 ** nBuf is the amount of space left in buf[].  The caller is responsible
   65148 ** for allocating enough space to buf[] to hold the entire field, exclusive
   65149 ** of the pMem->u.nZero bytes for a MEM_Zero value.
   65150 **
   65151 ** Return the number of bytes actually written into buf[].  The number
   65152 ** of bytes in the zero-filled tail is included in the return value only
   65153 ** if those bytes were zeroed in buf[].
   65154 */
   65155 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
   65156   u32 len;
   65157 
   65158   /* Integer and Real */
   65159   if( serial_type<=7 && serial_type>0 ){
   65160     u64 v;
   65161     u32 i;
   65162     if( serial_type==7 ){
   65163       assert( sizeof(v)==sizeof(pMem->r) );
   65164       memcpy(&v, &pMem->r, sizeof(v));
   65165       swapMixedEndianFloat(v);
   65166     }else{
   65167       v = pMem->u.i;
   65168     }
   65169     len = i = sqlite3VdbeSerialTypeLen(serial_type);
   65170     while( i-- ){
   65171       buf[i] = (u8)(v&0xFF);
   65172       v >>= 8;
   65173     }
   65174     return len;
   65175   }
   65176 
   65177   /* String or blob */
   65178   if( serial_type>=12 ){
   65179     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
   65180              == (int)sqlite3VdbeSerialTypeLen(serial_type) );
   65181     len = pMem->n;
   65182     memcpy(buf, pMem->z, len);
   65183     return len;
   65184   }
   65185 
   65186   /* NULL or constants 0 or 1 */
   65187   return 0;
   65188 }
   65189 
   65190 /* Input "x" is a sequence of unsigned characters that represent a
   65191 ** big-endian integer.  Return the equivalent native integer
   65192 */
   65193 #define ONE_BYTE_INT(x)    ((i8)(x)[0])
   65194 #define TWO_BYTE_INT(x)    (256*(i8)((x)[0])|(x)[1])
   65195 #define THREE_BYTE_INT(x)  (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
   65196 #define FOUR_BYTE_UINT(x)  (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
   65197 
   65198 /*
   65199 ** Deserialize the data blob pointed to by buf as serial type serial_type
   65200 ** and store the result in pMem.  Return the number of bytes read.
   65201 */
   65202 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
   65203   const unsigned char *buf,     /* Buffer to deserialize from */
   65204   u32 serial_type,              /* Serial type to deserialize */
   65205   Mem *pMem                     /* Memory cell to write value into */
   65206 ){
   65207   u64 x;
   65208   u32 y;
   65209   switch( serial_type ){
   65210     case 10:   /* Reserved for future use */
   65211     case 11:   /* Reserved for future use */
   65212     case 0: {  /* NULL */
   65213       pMem->flags = MEM_Null;
   65214       break;
   65215     }
   65216     case 1: { /* 1-byte signed integer */
   65217       pMem->u.i = ONE_BYTE_INT(buf);
   65218       pMem->flags = MEM_Int;
   65219       testcase( pMem->u.i<0 );
   65220       return 1;
   65221     }
   65222     case 2: { /* 2-byte signed integer */
   65223       pMem->u.i = TWO_BYTE_INT(buf);
   65224       pMem->flags = MEM_Int;
   65225       testcase( pMem->u.i<0 );
   65226       return 2;
   65227     }
   65228     case 3: { /* 3-byte signed integer */
   65229       pMem->u.i = THREE_BYTE_INT(buf);
   65230       pMem->flags = MEM_Int;
   65231       testcase( pMem->u.i<0 );
   65232       return 3;
   65233     }
   65234     case 4: { /* 4-byte signed integer */
   65235       y = FOUR_BYTE_UINT(buf);
   65236       pMem->u.i = (i64)*(int*)&y;
   65237       pMem->flags = MEM_Int;
   65238       testcase( pMem->u.i<0 );
   65239       return 4;
   65240     }
   65241     case 5: { /* 6-byte signed integer */
   65242       pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
   65243       pMem->flags = MEM_Int;
   65244       testcase( pMem->u.i<0 );
   65245       return 6;
   65246     }
   65247     case 6:   /* 8-byte signed integer */
   65248     case 7: { /* IEEE floating point */
   65249 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
   65250       /* Verify that integers and floating point values use the same
   65251       ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
   65252       ** defined that 64-bit floating point values really are mixed
   65253       ** endian.
   65254       */
   65255       static const u64 t1 = ((u64)0x3ff00000)<<32;
   65256       static const double r1 = 1.0;
   65257       u64 t2 = t1;
   65258       swapMixedEndianFloat(t2);
   65259       assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
   65260 #endif
   65261       x = FOUR_BYTE_UINT(buf);
   65262       y = FOUR_BYTE_UINT(buf+4);
   65263       x = (x<<32) | y;
   65264       if( serial_type==6 ){
   65265         pMem->u.i = *(i64*)&x;
   65266         pMem->flags = MEM_Int;
   65267         testcase( pMem->u.i<0 );
   65268       }else{
   65269         assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
   65270         swapMixedEndianFloat(x);
   65271         memcpy(&pMem->r, &x, sizeof(x));
   65272         pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
   65273       }
   65274       return 8;
   65275     }
   65276     case 8:    /* Integer 0 */
   65277     case 9: {  /* Integer 1 */
   65278       pMem->u.i = serial_type-8;
   65279       pMem->flags = MEM_Int;
   65280       return 0;
   65281     }
   65282     default: {
   65283       static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
   65284       u32 len = (serial_type-12)/2;
   65285       pMem->z = (char *)buf;
   65286       pMem->n = len;
   65287       pMem->xDel = 0;
   65288       pMem->flags = aFlag[serial_type&1];
   65289       return len;
   65290     }
   65291   }
   65292   return 0;
   65293 }
   65294 
   65295 /*
   65296 ** This routine is used to allocate sufficient space for an UnpackedRecord
   65297 ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
   65298 ** the first argument is a pointer to KeyInfo structure pKeyInfo.
   65299 **
   65300 ** The space is either allocated using sqlite3DbMallocRaw() or from within
   65301 ** the unaligned buffer passed via the second and third arguments (presumably
   65302 ** stack space). If the former, then *ppFree is set to a pointer that should
   65303 ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
   65304 ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
   65305 ** before returning.
   65306 **
   65307 ** If an OOM error occurs, NULL is returned.
   65308 */
   65309 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
   65310   KeyInfo *pKeyInfo,              /* Description of the record */
   65311   char *pSpace,                   /* Unaligned space available */
   65312   int szSpace,                    /* Size of pSpace[] in bytes */
   65313   char **ppFree                   /* OUT: Caller should free this pointer */
   65314 ){
   65315   UnpackedRecord *p;              /* Unpacked record to return */
   65316   int nOff;                       /* Increment pSpace by nOff to align it */
   65317   int nByte;                      /* Number of bytes required for *p */
   65318 
   65319   /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
   65320   ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
   65321   ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
   65322   */
   65323   nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
   65324   nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
   65325   if( nByte>szSpace+nOff ){
   65326     p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
   65327     *ppFree = (char *)p;
   65328     if( !p ) return 0;
   65329   }else{
   65330     p = (UnpackedRecord*)&pSpace[nOff];
   65331     *ppFree = 0;
   65332   }
   65333 
   65334   p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
   65335   assert( pKeyInfo->aSortOrder!=0 );
   65336   p->pKeyInfo = pKeyInfo;
   65337   p->nField = pKeyInfo->nField + 1;
   65338   return p;
   65339 }
   65340 
   65341 /*
   65342 ** Given the nKey-byte encoding of a record in pKey[], populate the
   65343 ** UnpackedRecord structure indicated by the fourth argument with the
   65344 ** contents of the decoded record.
   65345 */
   65346 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
   65347   KeyInfo *pKeyInfo,     /* Information about the record format */
   65348   int nKey,              /* Size of the binary record */
   65349   const void *pKey,      /* The binary record */
   65350   UnpackedRecord *p      /* Populate this structure before returning. */
   65351 ){
   65352   const unsigned char *aKey = (const unsigned char *)pKey;
   65353   int d;
   65354   u32 idx;                        /* Offset in aKey[] to read from */
   65355   u16 u;                          /* Unsigned loop counter */
   65356   u32 szHdr;
   65357   Mem *pMem = p->aMem;
   65358 
   65359   p->default_rc = 0;
   65360   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   65361   idx = getVarint32(aKey, szHdr);
   65362   d = szHdr;
   65363   u = 0;
   65364   while( idx<szHdr && u<p->nField && d<=nKey ){
   65365     u32 serial_type;
   65366 
   65367     idx += getVarint32(&aKey[idx], serial_type);
   65368     pMem->enc = pKeyInfo->enc;
   65369     pMem->db = pKeyInfo->db;
   65370     /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
   65371     pMem->zMalloc = 0;
   65372     d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
   65373     pMem++;
   65374     u++;
   65375   }
   65376   assert( u<=pKeyInfo->nField + 1 );
   65377   p->nField = u;
   65378 }
   65379 
   65380 #if SQLITE_DEBUG
   65381 /*
   65382 ** This function compares two index or table record keys in the same way
   65383 ** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
   65384 ** this function deserializes and compares values using the
   65385 ** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
   65386 ** in assert() statements to ensure that the optimized code in
   65387 ** sqlite3VdbeRecordCompare() returns results with these two primitives.
   65388 */
   65389 static int vdbeRecordCompareDebug(
   65390   int nKey1, const void *pKey1, /* Left key */
   65391   const UnpackedRecord *pPKey2  /* Right key */
   65392 ){
   65393   u32 d1;            /* Offset into aKey[] of next data element */
   65394   u32 idx1;          /* Offset into aKey[] of next header element */
   65395   u32 szHdr1;        /* Number of bytes in header */
   65396   int i = 0;
   65397   int rc = 0;
   65398   const unsigned char *aKey1 = (const unsigned char *)pKey1;
   65399   KeyInfo *pKeyInfo;
   65400   Mem mem1;
   65401 
   65402   pKeyInfo = pPKey2->pKeyInfo;
   65403   mem1.enc = pKeyInfo->enc;
   65404   mem1.db = pKeyInfo->db;
   65405   /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
   65406   VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
   65407 
   65408   /* Compilers may complain that mem1.u.i is potentially uninitialized.
   65409   ** We could initialize it, as shown here, to silence those complaints.
   65410   ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
   65411   ** the unnecessary initialization has a measurable negative performance
   65412   ** impact, since this routine is a very high runner.  And so, we choose
   65413   ** to ignore the compiler warnings and leave this variable uninitialized.
   65414   */
   65415   /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
   65416 
   65417   idx1 = getVarint32(aKey1, szHdr1);
   65418   d1 = szHdr1;
   65419   assert( pKeyInfo->nField+pKeyInfo->nXField>=pPKey2->nField || CORRUPT_DB );
   65420   assert( pKeyInfo->aSortOrder!=0 );
   65421   assert( pKeyInfo->nField>0 );
   65422   assert( idx1<=szHdr1 || CORRUPT_DB );
   65423   do{
   65424     u32 serial_type1;
   65425 
   65426     /* Read the serial types for the next element in each key. */
   65427     idx1 += getVarint32( aKey1+idx1, serial_type1 );
   65428 
   65429     /* Verify that there is enough key space remaining to avoid
   65430     ** a buffer overread.  The "d1+serial_type1+2" subexpression will
   65431     ** always be greater than or equal to the amount of required key space.
   65432     ** Use that approximation to avoid the more expensive call to
   65433     ** sqlite3VdbeSerialTypeLen() in the common case.
   65434     */
   65435     if( d1+serial_type1+2>(u32)nKey1
   65436      && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
   65437     ){
   65438       break;
   65439     }
   65440 
   65441     /* Extract the values to be compared.
   65442     */
   65443     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
   65444 
   65445     /* Do the comparison
   65446     */
   65447     rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
   65448     if( rc!=0 ){
   65449       assert( mem1.zMalloc==0 );  /* See comment below */
   65450       if( pKeyInfo->aSortOrder[i] ){
   65451         rc = -rc;  /* Invert the result for DESC sort order. */
   65452       }
   65453       return rc;
   65454     }
   65455     i++;
   65456   }while( idx1<szHdr1 && i<pPKey2->nField );
   65457 
   65458   /* No memory allocation is ever used on mem1.  Prove this using
   65459   ** the following assert().  If the assert() fails, it indicates a
   65460   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
   65461   */
   65462   assert( mem1.zMalloc==0 );
   65463 
   65464   /* rc==0 here means that one of the keys ran out of fields and
   65465   ** all the fields up to that point were equal. Return the the default_rc
   65466   ** value.  */
   65467   return pPKey2->default_rc;
   65468 }
   65469 #endif
   65470 
   65471 /*
   65472 ** Both *pMem1 and *pMem2 contain string values. Compare the two values
   65473 ** using the collation sequence pColl. As usual, return a negative , zero
   65474 ** or positive value if *pMem1 is less than, equal to or greater than
   65475 ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
   65476 */
   65477 static int vdbeCompareMemString(
   65478   const Mem *pMem1,
   65479   const Mem *pMem2,
   65480   const CollSeq *pColl
   65481 ){
   65482   if( pMem1->enc==pColl->enc ){
   65483     /* The strings are already in the correct encoding.  Call the
   65484      ** comparison function directly */
   65485     return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
   65486   }else{
   65487     int rc;
   65488     const void *v1, *v2;
   65489     int n1, n2;
   65490     Mem c1;
   65491     Mem c2;
   65492     memset(&c1, 0, sizeof(c1));
   65493     memset(&c2, 0, sizeof(c2));
   65494     sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
   65495     sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
   65496     v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
   65497     n1 = v1==0 ? 0 : c1.n;
   65498     v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
   65499     n2 = v2==0 ? 0 : c2.n;
   65500     rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
   65501     sqlite3VdbeMemRelease(&c1);
   65502     sqlite3VdbeMemRelease(&c2);
   65503     return rc;
   65504   }
   65505 }
   65506 
   65507 /*
   65508 ** Compare the values contained by the two memory cells, returning
   65509 ** negative, zero or positive if pMem1 is less than, equal to, or greater
   65510 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
   65511 ** and reals) sorted numerically, followed by text ordered by the collating
   65512 ** sequence pColl and finally blob's ordered by memcmp().
   65513 **
   65514 ** Two NULL values are considered equal by this function.
   65515 */
   65516 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
   65517   int rc;
   65518   int f1, f2;
   65519   int combined_flags;
   65520 
   65521   f1 = pMem1->flags;
   65522   f2 = pMem2->flags;
   65523   combined_flags = f1|f2;
   65524   assert( (combined_flags & MEM_RowSet)==0 );
   65525 
   65526   /* If one value is NULL, it is less than the other. If both values
   65527   ** are NULL, return 0.
   65528   */
   65529   if( combined_flags&MEM_Null ){
   65530     return (f2&MEM_Null) - (f1&MEM_Null);
   65531   }
   65532 
   65533   /* If one value is a number and the other is not, the number is less.
   65534   ** If both are numbers, compare as reals if one is a real, or as integers
   65535   ** if both values are integers.
   65536   */
   65537   if( combined_flags&(MEM_Int|MEM_Real) ){
   65538     double r1, r2;
   65539     if( (f1 & f2 & MEM_Int)!=0 ){
   65540       if( pMem1->u.i < pMem2->u.i ) return -1;
   65541       if( pMem1->u.i > pMem2->u.i ) return 1;
   65542       return 0;
   65543     }
   65544     if( (f1&MEM_Real)!=0 ){
   65545       r1 = pMem1->r;
   65546     }else if( (f1&MEM_Int)!=0 ){
   65547       r1 = (double)pMem1->u.i;
   65548     }else{
   65549       return 1;
   65550     }
   65551     if( (f2&MEM_Real)!=0 ){
   65552       r2 = pMem2->r;
   65553     }else if( (f2&MEM_Int)!=0 ){
   65554       r2 = (double)pMem2->u.i;
   65555     }else{
   65556       return -1;
   65557     }
   65558     if( r1<r2 ) return -1;
   65559     if( r1>r2 ) return 1;
   65560     return 0;
   65561   }
   65562 
   65563   /* If one value is a string and the other is a blob, the string is less.
   65564   ** If both are strings, compare using the collating functions.
   65565   */
   65566   if( combined_flags&MEM_Str ){
   65567     if( (f1 & MEM_Str)==0 ){
   65568       return 1;
   65569     }
   65570     if( (f2 & MEM_Str)==0 ){
   65571       return -1;
   65572     }
   65573 
   65574     assert( pMem1->enc==pMem2->enc );
   65575     assert( pMem1->enc==SQLITE_UTF8 ||
   65576             pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
   65577 
   65578     /* The collation sequence must be defined at this point, even if
   65579     ** the user deletes the collation sequence after the vdbe program is
   65580     ** compiled (this was not always the case).
   65581     */
   65582     assert( !pColl || pColl->xCmp );
   65583 
   65584     if( pColl ){
   65585       return vdbeCompareMemString(pMem1, pMem2, pColl);
   65586     }
   65587     /* If a NULL pointer was passed as the collate function, fall through
   65588     ** to the blob case and use memcmp().  */
   65589   }
   65590 
   65591   /* Both values must be blobs.  Compare using memcmp().  */
   65592   rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
   65593   if( rc==0 ){
   65594     rc = pMem1->n - pMem2->n;
   65595   }
   65596   return rc;
   65597 }
   65598 
   65599 
   65600 /*
   65601 ** The first argument passed to this function is a serial-type that
   65602 ** corresponds to an integer - all values between 1 and 9 inclusive
   65603 ** except 7. The second points to a buffer containing an integer value
   65604 ** serialized according to serial_type. This function deserializes
   65605 ** and returns the value.
   65606 */
   65607 static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
   65608   u32 y;
   65609   assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
   65610   switch( serial_type ){
   65611     case 0:
   65612     case 1:
   65613       testcase( aKey[0]&0x80 );
   65614       return ONE_BYTE_INT(aKey);
   65615     case 2:
   65616       testcase( aKey[0]&0x80 );
   65617       return TWO_BYTE_INT(aKey);
   65618     case 3:
   65619       testcase( aKey[0]&0x80 );
   65620       return THREE_BYTE_INT(aKey);
   65621     case 4: {
   65622       testcase( aKey[0]&0x80 );
   65623       y = FOUR_BYTE_UINT(aKey);
   65624       return (i64)*(int*)&y;
   65625     }
   65626     case 5: {
   65627       testcase( aKey[0]&0x80 );
   65628       return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
   65629     }
   65630     case 6: {
   65631       u64 x = FOUR_BYTE_UINT(aKey);
   65632       testcase( aKey[0]&0x80 );
   65633       x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
   65634       return (i64)*(i64*)&x;
   65635     }
   65636   }
   65637 
   65638   return (serial_type - 8);
   65639 }
   65640 
   65641 /*
   65642 ** This function compares the two table rows or index records
   65643 ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
   65644 ** or positive integer if key1 is less than, equal to or
   65645 ** greater than key2.  The {nKey1, pKey1} key must be a blob
   65646 ** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
   65647 ** key must be a parsed key such as obtained from
   65648 ** sqlite3VdbeParseRecord.
   65649 **
   65650 ** If argument bSkip is non-zero, it is assumed that the caller has already
   65651 ** determined that the first fields of the keys are equal.
   65652 **
   65653 ** Key1 and Key2 do not have to contain the same number of fields. If all
   65654 ** fields that appear in both keys are equal, then pPKey2->default_rc is
   65655 ** returned.
   65656 **
   65657 ** If database corruption is discovered, set pPKey2->isCorrupt to non-zero
   65658 ** and return 0.
   65659 */
   65660 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
   65661   int nKey1, const void *pKey1,   /* Left key */
   65662   UnpackedRecord *pPKey2,         /* Right key */
   65663   int bSkip                       /* If true, skip the first field */
   65664 ){
   65665   u32 d1;                         /* Offset into aKey[] of next data element */
   65666   int i;                          /* Index of next field to compare */
   65667   u32 szHdr1;                     /* Size of record header in bytes */
   65668   u32 idx1;                       /* Offset of first type in header */
   65669   int rc = 0;                     /* Return value */
   65670   Mem *pRhs = pPKey2->aMem;       /* Next field of pPKey2 to compare */
   65671   KeyInfo *pKeyInfo = pPKey2->pKeyInfo;
   65672   const unsigned char *aKey1 = (const unsigned char *)pKey1;
   65673   Mem mem1;
   65674 
   65675   /* If bSkip is true, then the caller has already determined that the first
   65676   ** two elements in the keys are equal. Fix the various stack variables so
   65677   ** that this routine begins comparing at the second field. */
   65678   if( bSkip ){
   65679     u32 s1;
   65680     idx1 = 1 + getVarint32(&aKey1[1], s1);
   65681     szHdr1 = aKey1[0];
   65682     d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
   65683     i = 1;
   65684     pRhs++;
   65685   }else{
   65686     idx1 = getVarint32(aKey1, szHdr1);
   65687     d1 = szHdr1;
   65688     if( d1>(unsigned)nKey1 ){
   65689       pPKey2->isCorrupt = (u8)SQLITE_CORRUPT_BKPT;
   65690       return 0;  /* Corruption */
   65691     }
   65692     i = 0;
   65693   }
   65694 
   65695   VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
   65696   assert( pPKey2->pKeyInfo->nField+pPKey2->pKeyInfo->nXField>=pPKey2->nField
   65697        || CORRUPT_DB );
   65698   assert( pPKey2->pKeyInfo->aSortOrder!=0 );
   65699   assert( pPKey2->pKeyInfo->nField>0 );
   65700   assert( idx1<=szHdr1 || CORRUPT_DB );
   65701   do{
   65702     u32 serial_type;
   65703 
   65704     /* RHS is an integer */
   65705     if( pRhs->flags & MEM_Int ){
   65706       serial_type = aKey1[idx1];
   65707       testcase( serial_type==12 );
   65708       if( serial_type>=12 ){
   65709         rc = +1;
   65710       }else if( serial_type==0 ){
   65711         rc = -1;
   65712       }else if( serial_type==7 ){
   65713         double rhs = (double)pRhs->u.i;
   65714         sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
   65715         if( mem1.r<rhs ){
   65716           rc = -1;
   65717         }else if( mem1.r>rhs ){
   65718           rc = +1;
   65719         }
   65720       }else{
   65721         i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
   65722         i64 rhs = pRhs->u.i;
   65723         if( lhs<rhs ){
   65724           rc = -1;
   65725         }else if( lhs>rhs ){
   65726           rc = +1;
   65727         }
   65728       }
   65729     }
   65730 
   65731     /* RHS is real */
   65732     else if( pRhs->flags & MEM_Real ){
   65733       serial_type = aKey1[idx1];
   65734       if( serial_type>=12 ){
   65735         rc = +1;
   65736       }else if( serial_type==0 ){
   65737         rc = -1;
   65738       }else{
   65739         double rhs = pRhs->r;
   65740         double lhs;
   65741         sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
   65742         if( serial_type==7 ){
   65743           lhs = mem1.r;
   65744         }else{
   65745           lhs = (double)mem1.u.i;
   65746         }
   65747         if( lhs<rhs ){
   65748           rc = -1;
   65749         }else if( lhs>rhs ){
   65750           rc = +1;
   65751         }
   65752       }
   65753     }
   65754 
   65755     /* RHS is a string */
   65756     else if( pRhs->flags & MEM_Str ){
   65757       getVarint32(&aKey1[idx1], serial_type);
   65758       testcase( serial_type==12 );
   65759       if( serial_type<12 ){
   65760         rc = -1;
   65761       }else if( !(serial_type & 0x01) ){
   65762         rc = +1;
   65763       }else{
   65764         mem1.n = (serial_type - 12) / 2;
   65765         testcase( (d1+mem1.n)==(unsigned)nKey1 );
   65766         testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
   65767         if( (d1+mem1.n) > (unsigned)nKey1 ){
   65768           pPKey2->isCorrupt = (u8)SQLITE_CORRUPT_BKPT;
   65769           return 0;                /* Corruption */
   65770         }else if( pKeyInfo->aColl[i] ){
   65771           mem1.enc = pKeyInfo->enc;
   65772           mem1.db = pKeyInfo->db;
   65773           mem1.flags = MEM_Str;
   65774           mem1.z = (char*)&aKey1[d1];
   65775           rc = vdbeCompareMemString(&mem1, pRhs, pKeyInfo->aColl[i]);
   65776         }else{
   65777           int nCmp = MIN(mem1.n, pRhs->n);
   65778           rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
   65779           if( rc==0 ) rc = mem1.n - pRhs->n;
   65780         }
   65781       }
   65782     }
   65783 
   65784     /* RHS is a blob */
   65785     else if( pRhs->flags & MEM_Blob ){
   65786       getVarint32(&aKey1[idx1], serial_type);
   65787       testcase( serial_type==12 );
   65788       if( serial_type<12 || (serial_type & 0x01) ){
   65789         rc = -1;
   65790       }else{
   65791         int nStr = (serial_type - 12) / 2;
   65792         testcase( (d1+nStr)==(unsigned)nKey1 );
   65793         testcase( (d1+nStr+1)==(unsigned)nKey1 );
   65794         if( (d1+nStr) > (unsigned)nKey1 ){
   65795           pPKey2->isCorrupt = (u8)SQLITE_CORRUPT_BKPT;
   65796           return 0;                /* Corruption */
   65797         }else{
   65798           int nCmp = MIN(nStr, pRhs->n);
   65799           rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
   65800           if( rc==0 ) rc = nStr - pRhs->n;
   65801         }
   65802       }
   65803     }
   65804 
   65805     /* RHS is null */
   65806     else{
   65807       serial_type = aKey1[idx1];
   65808       rc = (serial_type!=0);
   65809     }
   65810 
   65811     if( rc!=0 ){
   65812       if( pKeyInfo->aSortOrder[i] ){
   65813         rc = -rc;
   65814       }
   65815       assert( CORRUPT_DB
   65816           || (rc<0 && vdbeRecordCompareDebug(nKey1, pKey1, pPKey2)<0)
   65817           || (rc>0 && vdbeRecordCompareDebug(nKey1, pKey1, pPKey2)>0)
   65818           || pKeyInfo->db->mallocFailed
   65819       );
   65820       assert( mem1.zMalloc==0 );  /* See comment below */
   65821       return rc;
   65822     }
   65823 
   65824     i++;
   65825     pRhs++;
   65826     d1 += sqlite3VdbeSerialTypeLen(serial_type);
   65827     idx1 += sqlite3VarintLen(serial_type);
   65828   }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 );
   65829 
   65830   /* No memory allocation is ever used on mem1.  Prove this using
   65831   ** the following assert().  If the assert() fails, it indicates a
   65832   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).  */
   65833   assert( mem1.zMalloc==0 );
   65834 
   65835   /* rc==0 here means that one or both of the keys ran out of fields and
   65836   ** all the fields up to that point were equal. Return the the default_rc
   65837   ** value.  */
   65838   assert( CORRUPT_DB
   65839        || pPKey2->default_rc==vdbeRecordCompareDebug(nKey1, pKey1, pPKey2)
   65840        || pKeyInfo->db->mallocFailed
   65841   );
   65842   return pPKey2->default_rc;
   65843 }
   65844 
   65845 /*
   65846 ** This function is an optimized version of sqlite3VdbeRecordCompare()
   65847 ** that (a) the first field of pPKey2 is an integer, and (b) the
   65848 ** size-of-header varint at the start of (pKey1/nKey1) fits in a single
   65849 ** byte (i.e. is less than 128).
   65850 **
   65851 ** To avoid concerns about buffer overreads, this routine is only used
   65852 ** on schemas where the maximum valid header size is 63 bytes or less.
   65853 */
   65854 static int vdbeRecordCompareInt(
   65855   int nKey1, const void *pKey1, /* Left key */
   65856   UnpackedRecord *pPKey2,       /* Right key */
   65857   int bSkip                     /* Ignored */
   65858 ){
   65859   const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
   65860   int serial_type = ((const u8*)pKey1)[1];
   65861   int res;
   65862   u32 y;
   65863   u64 x;
   65864   i64 v = pPKey2->aMem[0].u.i;
   65865   i64 lhs;
   65866   UNUSED_PARAMETER(bSkip);
   65867 
   65868   assert( bSkip==0 );
   65869   assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
   65870   switch( serial_type ){
   65871     case 1: { /* 1-byte signed integer */
   65872       lhs = ONE_BYTE_INT(aKey);
   65873       testcase( lhs<0 );
   65874       break;
   65875     }
   65876     case 2: { /* 2-byte signed integer */
   65877       lhs = TWO_BYTE_INT(aKey);
   65878       testcase( lhs<0 );
   65879       break;
   65880     }
   65881     case 3: { /* 3-byte signed integer */
   65882       lhs = THREE_BYTE_INT(aKey);
   65883       testcase( lhs<0 );
   65884       break;
   65885     }
   65886     case 4: { /* 4-byte signed integer */
   65887       y = FOUR_BYTE_UINT(aKey);
   65888       lhs = (i64)*(int*)&y;
   65889       testcase( lhs<0 );
   65890       break;
   65891     }
   65892     case 5: { /* 6-byte signed integer */
   65893       lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
   65894       testcase( lhs<0 );
   65895       break;
   65896     }
   65897     case 6: { /* 8-byte signed integer */
   65898       x = FOUR_BYTE_UINT(aKey);
   65899       x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
   65900       lhs = *(i64*)&x;
   65901       testcase( lhs<0 );
   65902       break;
   65903     }
   65904     case 8:
   65905       lhs = 0;
   65906       break;
   65907     case 9:
   65908       lhs = 1;
   65909       break;
   65910 
   65911     /* This case could be removed without changing the results of running
   65912     ** this code. Including it causes gcc to generate a faster switch
   65913     ** statement (since the range of switch targets now starts at zero and
   65914     ** is contiguous) but does not cause any duplicate code to be generated
   65915     ** (as gcc is clever enough to combine the two like cases). Other
   65916     ** compilers might be similar.  */
   65917     case 0: case 7:
   65918       return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2, 0);
   65919 
   65920     default:
   65921       return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2, 0);
   65922   }
   65923 
   65924   if( v>lhs ){
   65925     res = pPKey2->r1;
   65926   }else if( v<lhs ){
   65927     res = pPKey2->r2;
   65928   }else if( pPKey2->nField>1 ){
   65929     /* The first fields of the two keys are equal. Compare the trailing
   65930     ** fields.  */
   65931     res = sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2, 1);
   65932   }else{
   65933     /* The first fields of the two keys are equal and there are no trailing
   65934     ** fields. Return pPKey2->default_rc in this case. */
   65935     res = pPKey2->default_rc;
   65936   }
   65937 
   65938   assert( (res==0 && vdbeRecordCompareDebug(nKey1, pKey1, pPKey2)==0)
   65939        || (res<0 && vdbeRecordCompareDebug(nKey1, pKey1, pPKey2)<0)
   65940        || (res>0 && vdbeRecordCompareDebug(nKey1, pKey1, pPKey2)>0)
   65941        || CORRUPT_DB
   65942   );
   65943   return res;
   65944 }
   65945 
   65946 /*
   65947 ** This function is an optimized version of sqlite3VdbeRecordCompare()
   65948 ** that (a) the first field of pPKey2 is a string, that (b) the first field
   65949 ** uses the collation sequence BINARY and (c) that the size-of-header varint
   65950 ** at the start of (pKey1/nKey1) fits in a single byte.
   65951 */
   65952 static int vdbeRecordCompareString(
   65953   int nKey1, const void *pKey1, /* Left key */
   65954   UnpackedRecord *pPKey2,       /* Right key */
   65955   int bSkip
   65956 ){
   65957   const u8 *aKey1 = (const u8*)pKey1;
   65958   int serial_type;
   65959   int res;
   65960   UNUSED_PARAMETER(bSkip);
   65961 
   65962   assert( bSkip==0 );
   65963   getVarint32(&aKey1[1], serial_type);
   65964 
   65965   if( serial_type<12 ){
   65966     res = pPKey2->r1;      /* (pKey1/nKey1) is a number or a null */
   65967   }else if( !(serial_type & 0x01) ){
   65968     res = pPKey2->r2;      /* (pKey1/nKey1) is a blob */
   65969   }else{
   65970     int nCmp;
   65971     int nStr;
   65972     int szHdr = aKey1[0];
   65973 
   65974     nStr = (serial_type-12) / 2;
   65975     if( (szHdr + nStr) > nKey1 ){
   65976       pPKey2->isCorrupt = (u8)SQLITE_CORRUPT_BKPT;
   65977       return 0;    /* Corruption */
   65978     }
   65979     nCmp = MIN( pPKey2->aMem[0].n, nStr );
   65980     res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
   65981 
   65982     if( res==0 ){
   65983       res = nStr - pPKey2->aMem[0].n;
   65984       if( res==0 ){
   65985         if( pPKey2->nField>1 ){
   65986           res = sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2, 1);
   65987         }else{
   65988           res = pPKey2->default_rc;
   65989         }
   65990       }else if( res>0 ){
   65991         res = pPKey2->r2;
   65992       }else{
   65993         res = pPKey2->r1;
   65994       }
   65995     }else if( res>0 ){
   65996       res = pPKey2->r2;
   65997     }else{
   65998       res = pPKey2->r1;
   65999     }
   66000   }
   66001 
   66002   assert( (res==0 && vdbeRecordCompareDebug(nKey1, pKey1, pPKey2)==0)
   66003        || (res<0 && vdbeRecordCompareDebug(nKey1, pKey1, pPKey2)<0)
   66004        || (res>0 && vdbeRecordCompareDebug(nKey1, pKey1, pPKey2)>0)
   66005        || CORRUPT_DB
   66006        || pPKey2->pKeyInfo->db->mallocFailed
   66007   );
   66008   return res;
   66009 }
   66010 
   66011 /*
   66012 ** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
   66013 ** suitable for comparing serialized records to the unpacked record passed
   66014 ** as the only argument.
   66015 */
   66016 SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
   66017   /* varintRecordCompareInt() and varintRecordCompareString() both assume
   66018   ** that the size-of-header varint that occurs at the start of each record
   66019   ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
   66020   ** also assumes that it is safe to overread a buffer by at least the
   66021   ** maximum possible legal header size plus 8 bytes. Because there is
   66022   ** guaranteed to be at least 74 (but not 136) bytes of padding following each
   66023   ** buffer passed to varintRecordCompareInt() this makes it convenient to
   66024   ** limit the size of the header to 64 bytes in cases where the first field
   66025   ** is an integer.
   66026   **
   66027   ** The easiest way to enforce this limit is to consider only records with
   66028   ** 13 fields or less. If the first field is an integer, the maximum legal
   66029   ** header size is (12*5 + 1 + 1) bytes.  */
   66030   if( (p->pKeyInfo->nField + p->pKeyInfo->nXField)<=13 ){
   66031     int flags = p->aMem[0].flags;
   66032     if( p->pKeyInfo->aSortOrder[0] ){
   66033       p->r1 = 1;
   66034       p->r2 = -1;
   66035     }else{
   66036       p->r1 = -1;
   66037       p->r2 = 1;
   66038     }
   66039     if( (flags & MEM_Int) ){
   66040       return vdbeRecordCompareInt;
   66041     }
   66042     testcase( flags & MEM_Real );
   66043     testcase( flags & MEM_Null );
   66044     testcase( flags & MEM_Blob );
   66045     if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
   66046       assert( flags & MEM_Str );
   66047       return vdbeRecordCompareString;
   66048     }
   66049   }
   66050 
   66051   return sqlite3VdbeRecordCompare;
   66052 }
   66053 
   66054 /*
   66055 ** pCur points at an index entry created using the OP_MakeRecord opcode.
   66056 ** Read the rowid (the last field in the record) and store it in *rowid.
   66057 ** Return SQLITE_OK if everything works, or an error code otherwise.
   66058 **
   66059 ** pCur might be pointing to text obtained from a corrupt database file.
   66060 ** So the content cannot be trusted.  Do appropriate checks on the content.
   66061 */
   66062 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
   66063   i64 nCellKey = 0;
   66064   int rc;
   66065   u32 szHdr;        /* Size of the header */
   66066   u32 typeRowid;    /* Serial type of the rowid */
   66067   u32 lenRowid;     /* Size of the rowid */
   66068   Mem m, v;
   66069 
   66070   UNUSED_PARAMETER(db);
   66071 
   66072   /* Get the size of the index entry.  Only indices entries of less
   66073   ** than 2GiB are support - anything large must be database corruption.
   66074   ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
   66075   ** this code can safely assume that nCellKey is 32-bits
   66076   */
   66077   assert( sqlite3BtreeCursorIsValid(pCur) );
   66078   VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
   66079   assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
   66080   assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
   66081 
   66082   /* Read in the complete content of the index entry */
   66083   memset(&m, 0, sizeof(m));
   66084   rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, 1, &m);
   66085   if( rc ){
   66086     return rc;
   66087   }
   66088 
   66089   /* The index entry must begin with a header size */
   66090   (void)getVarint32((u8*)m.z, szHdr);
   66091   testcase( szHdr==3 );
   66092   testcase( szHdr==m.n );
   66093   if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
   66094     goto idx_rowid_corruption;
   66095   }
   66096 
   66097   /* The last field of the index should be an integer - the ROWID.
   66098   ** Verify that the last entry really is an integer. */
   66099   (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
   66100   testcase( typeRowid==1 );
   66101   testcase( typeRowid==2 );
   66102   testcase( typeRowid==3 );
   66103   testcase( typeRowid==4 );
   66104   testcase( typeRowid==5 );
   66105   testcase( typeRowid==6 );
   66106   testcase( typeRowid==8 );
   66107   testcase( typeRowid==9 );
   66108   if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
   66109     goto idx_rowid_corruption;
   66110   }
   66111   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
   66112   testcase( (u32)m.n==szHdr+lenRowid );
   66113   if( unlikely((u32)m.n<szHdr+lenRowid) ){
   66114     goto idx_rowid_corruption;
   66115   }
   66116 
   66117   /* Fetch the integer off the end of the index record */
   66118   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
   66119   *rowid = v.u.i;
   66120   sqlite3VdbeMemRelease(&m);
   66121   return SQLITE_OK;
   66122 
   66123   /* Jump here if database corruption is detected after m has been
   66124   ** allocated.  Free the m object and return SQLITE_CORRUPT. */
   66125 idx_rowid_corruption:
   66126   testcase( m.zMalloc!=0 );
   66127   sqlite3VdbeMemRelease(&m);
   66128   return SQLITE_CORRUPT_BKPT;
   66129 }
   66130 
   66131 /*
   66132 ** Compare the key of the index entry that cursor pC is pointing to against
   66133 ** the key string in pUnpacked.  Write into *pRes a number
   66134 ** that is negative, zero, or positive if pC is less than, equal to,
   66135 ** or greater than pUnpacked.  Return SQLITE_OK on success.
   66136 **
   66137 ** pUnpacked is either created without a rowid or is truncated so that it
   66138 ** omits the rowid at the end.  The rowid at the end of the index entry
   66139 ** is ignored as well.  Hence, this routine only compares the prefixes
   66140 ** of the keys prior to the final rowid, not the entire key.
   66141 */
   66142 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
   66143   VdbeCursor *pC,                  /* The cursor to compare against */
   66144   UnpackedRecord *pUnpacked,       /* Unpacked version of key */
   66145   int *res                         /* Write the comparison result here */
   66146 ){
   66147   i64 nCellKey = 0;
   66148   int rc;
   66149   BtCursor *pCur = pC->pCursor;
   66150   Mem m;
   66151 
   66152   assert( sqlite3BtreeCursorIsValid(pCur) );
   66153   VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
   66154   assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
   66155   /* nCellKey will always be between 0 and 0xffffffff because of the way
   66156   ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
   66157   if( nCellKey<=0 || nCellKey>0x7fffffff ){
   66158     *res = 0;
   66159     return SQLITE_CORRUPT_BKPT;
   66160   }
   66161   memset(&m, 0, sizeof(m));
   66162   rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (u32)nCellKey, 1, &m);
   66163   if( rc ){
   66164     return rc;
   66165   }
   66166   *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked, 0);
   66167   sqlite3VdbeMemRelease(&m);
   66168   return SQLITE_OK;
   66169 }
   66170 
   66171 /*
   66172 ** This routine sets the value to be returned by subsequent calls to
   66173 ** sqlite3_changes() on the database handle 'db'.
   66174 */
   66175 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
   66176   assert( sqlite3_mutex_held(db->mutex) );
   66177   db->nChange = nChange;
   66178   db->nTotalChange += nChange;
   66179 }
   66180 
   66181 /*
   66182 ** Set a flag in the vdbe to update the change counter when it is finalised
   66183 ** or reset.
   66184 */
   66185 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
   66186   v->changeCntOn = 1;
   66187 }
   66188 
   66189 /*
   66190 ** Mark every prepared statement associated with a database connection
   66191 ** as expired.
   66192 **
   66193 ** An expired statement means that recompilation of the statement is
   66194 ** recommend.  Statements expire when things happen that make their
   66195 ** programs obsolete.  Removing user-defined functions or collating
   66196 ** sequences, or changing an authorization function are the types of
   66197 ** things that make prepared statements obsolete.
   66198 */
   66199 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
   66200   Vdbe *p;
   66201   for(p = db->pVdbe; p; p=p->pNext){
   66202     p->expired = 1;
   66203   }
   66204 }
   66205 
   66206 /*
   66207 ** Return the database associated with the Vdbe.
   66208 */
   66209 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
   66210   return v->db;
   66211 }
   66212 
   66213 /*
   66214 ** Return a pointer to an sqlite3_value structure containing the value bound
   66215 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
   66216 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
   66217 ** constants) to the value before returning it.
   66218 **
   66219 ** The returned value must be freed by the caller using sqlite3ValueFree().
   66220 */
   66221 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
   66222   assert( iVar>0 );
   66223   if( v ){
   66224     Mem *pMem = &v->aVar[iVar-1];
   66225     if( 0==(pMem->flags & MEM_Null) ){
   66226       sqlite3_value *pRet = sqlite3ValueNew(v->db);
   66227       if( pRet ){
   66228         sqlite3VdbeMemCopy((Mem *)pRet, pMem);
   66229         sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
   66230       }
   66231       return pRet;
   66232     }
   66233   }
   66234   return 0;
   66235 }
   66236 
   66237 /*
   66238 ** Configure SQL variable iVar so that binding a new value to it signals
   66239 ** to sqlite3_reoptimize() that re-preparing the statement may result
   66240 ** in a better query plan.
   66241 */
   66242 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
   66243   assert( iVar>0 );
   66244   if( iVar>32 ){
   66245     v->expmask = 0xffffffff;
   66246   }else{
   66247     v->expmask |= ((u32)1 << (iVar-1));
   66248   }
   66249 }
   66250 
   66251 #ifndef SQLITE_OMIT_VIRTUALTABLE
   66252 /*
   66253 ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
   66254 ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
   66255 ** in memory obtained from sqlite3DbMalloc).
   66256 */
   66257 SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
   66258   sqlite3 *db = p->db;
   66259   sqlite3DbFree(db, p->zErrMsg);
   66260   p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
   66261   sqlite3_free(pVtab->zErrMsg);
   66262   pVtab->zErrMsg = 0;
   66263 }
   66264 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   66265 
   66266 /************** End of vdbeaux.c *********************************************/
   66267 /************** Begin file vdbeapi.c *****************************************/
   66268 /*
   66269 ** 2004 May 26
   66270 **
   66271 ** The author disclaims copyright to this source code.  In place of
   66272 ** a legal notice, here is a blessing:
   66273 **
   66274 **    May you do good and not evil.
   66275 **    May you find forgiveness for yourself and forgive others.
   66276 **    May you share freely, never taking more than you give.
   66277 **
   66278 *************************************************************************
   66279 **
   66280 ** This file contains code use to implement APIs that are part of the
   66281 ** VDBE.
   66282 */
   66283 
   66284 #ifndef SQLITE_OMIT_DEPRECATED
   66285 /*
   66286 ** Return TRUE (non-zero) of the statement supplied as an argument needs
   66287 ** to be recompiled.  A statement needs to be recompiled whenever the
   66288 ** execution environment changes in a way that would alter the program
   66289 ** that sqlite3_prepare() generates.  For example, if new functions or
   66290 ** collating sequences are registered or if an authorizer function is
   66291 ** added or changed.
   66292 */
   66293 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
   66294   Vdbe *p = (Vdbe*)pStmt;
   66295   return p==0 || p->expired;
   66296 }
   66297 #endif
   66298 
   66299 /*
   66300 ** Check on a Vdbe to make sure it has not been finalized.  Log
   66301 ** an error and return true if it has been finalized (or is otherwise
   66302 ** invalid).  Return false if it is ok.
   66303 */
   66304 static int vdbeSafety(Vdbe *p){
   66305   if( p->db==0 ){
   66306     sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
   66307     return 1;
   66308   }else{
   66309     return 0;
   66310   }
   66311 }
   66312 static int vdbeSafetyNotNull(Vdbe *p){
   66313   if( p==0 ){
   66314     sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
   66315     return 1;
   66316   }else{
   66317     return vdbeSafety(p);
   66318   }
   66319 }
   66320 
   66321 /*
   66322 ** The following routine destroys a virtual machine that is created by
   66323 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
   66324 ** success/failure code that describes the result of executing the virtual
   66325 ** machine.
   66326 **
   66327 ** This routine sets the error code and string returned by
   66328 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
   66329 */
   66330 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
   66331   int rc;
   66332   if( pStmt==0 ){
   66333     /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
   66334     ** pointer is a harmless no-op. */
   66335     rc = SQLITE_OK;
   66336   }else{
   66337     Vdbe *v = (Vdbe*)pStmt;
   66338     sqlite3 *db = v->db;
   66339     if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
   66340     sqlite3_mutex_enter(db->mutex);
   66341     rc = sqlite3VdbeFinalize(v);
   66342     rc = sqlite3ApiExit(db, rc);
   66343     sqlite3LeaveMutexAndCloseZombie(db);
   66344   }
   66345   return rc;
   66346 }
   66347 
   66348 /*
   66349 ** Terminate the current execution of an SQL statement and reset it
   66350 ** back to its starting state so that it can be reused. A success code from
   66351 ** the prior execution is returned.
   66352 **
   66353 ** This routine sets the error code and string returned by
   66354 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
   66355 */
   66356 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
   66357   int rc;
   66358   if( pStmt==0 ){
   66359     rc = SQLITE_OK;
   66360   }else{
   66361     Vdbe *v = (Vdbe*)pStmt;
   66362     sqlite3_mutex_enter(v->db->mutex);
   66363     rc = sqlite3VdbeReset(v);
   66364     sqlite3VdbeRewind(v);
   66365     assert( (rc & (v->db->errMask))==rc );
   66366     rc = sqlite3ApiExit(v->db, rc);
   66367     sqlite3_mutex_leave(v->db->mutex);
   66368   }
   66369   return rc;
   66370 }
   66371 
   66372 /*
   66373 ** Set all the parameters in the compiled SQL statement to NULL.
   66374 */
   66375 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
   66376   int i;
   66377   int rc = SQLITE_OK;
   66378   Vdbe *p = (Vdbe*)pStmt;
   66379 #if SQLITE_THREADSAFE
   66380   sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
   66381 #endif
   66382   sqlite3_mutex_enter(mutex);
   66383   for(i=0; i<p->nVar; i++){
   66384     sqlite3VdbeMemRelease(&p->aVar[i]);
   66385     p->aVar[i].flags = MEM_Null;
   66386   }
   66387   if( p->isPrepareV2 && p->expmask ){
   66388     p->expired = 1;
   66389   }
   66390   sqlite3_mutex_leave(mutex);
   66391   return rc;
   66392 }
   66393 
   66394 
   66395 /**************************** sqlite3_value_  *******************************
   66396 ** The following routines extract information from a Mem or sqlite3_value
   66397 ** structure.
   66398 */
   66399 SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
   66400   Mem *p = (Mem*)pVal;
   66401   if( p->flags & (MEM_Blob|MEM_Str) ){
   66402     sqlite3VdbeMemExpandBlob(p);
   66403     p->flags |= MEM_Blob;
   66404     return p->n ? p->z : 0;
   66405   }else{
   66406     return sqlite3_value_text(pVal);
   66407   }
   66408 }
   66409 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
   66410   return sqlite3ValueBytes(pVal, SQLITE_UTF8);
   66411 }
   66412 SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
   66413   return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
   66414 }
   66415 SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
   66416   return sqlite3VdbeRealValue((Mem*)pVal);
   66417 }
   66418 SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
   66419   return (int)sqlite3VdbeIntValue((Mem*)pVal);
   66420 }
   66421 SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
   66422   return sqlite3VdbeIntValue((Mem*)pVal);
   66423 }
   66424 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
   66425   return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
   66426 }
   66427 #ifndef SQLITE_OMIT_UTF16
   66428 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
   66429   return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
   66430 }
   66431 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
   66432   return sqlite3ValueText(pVal, SQLITE_UTF16BE);
   66433 }
   66434 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
   66435   return sqlite3ValueText(pVal, SQLITE_UTF16LE);
   66436 }
   66437 #endif /* SQLITE_OMIT_UTF16 */
   66438 SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
   66439   static const u8 aType[] = {
   66440      SQLITE_BLOB,     /* 0x00 */
   66441      SQLITE_NULL,     /* 0x01 */
   66442      SQLITE_TEXT,     /* 0x02 */
   66443      SQLITE_NULL,     /* 0x03 */
   66444      SQLITE_INTEGER,  /* 0x04 */
   66445      SQLITE_NULL,     /* 0x05 */
   66446      SQLITE_INTEGER,  /* 0x06 */
   66447      SQLITE_NULL,     /* 0x07 */
   66448      SQLITE_FLOAT,    /* 0x08 */
   66449      SQLITE_NULL,     /* 0x09 */
   66450      SQLITE_FLOAT,    /* 0x0a */
   66451      SQLITE_NULL,     /* 0x0b */
   66452      SQLITE_INTEGER,  /* 0x0c */
   66453      SQLITE_NULL,     /* 0x0d */
   66454      SQLITE_INTEGER,  /* 0x0e */
   66455      SQLITE_NULL,     /* 0x0f */
   66456      SQLITE_BLOB,     /* 0x10 */
   66457      SQLITE_NULL,     /* 0x11 */
   66458      SQLITE_TEXT,     /* 0x12 */
   66459      SQLITE_NULL,     /* 0x13 */
   66460      SQLITE_INTEGER,  /* 0x14 */
   66461      SQLITE_NULL,     /* 0x15 */
   66462      SQLITE_INTEGER,  /* 0x16 */
   66463      SQLITE_NULL,     /* 0x17 */
   66464      SQLITE_FLOAT,    /* 0x18 */
   66465      SQLITE_NULL,     /* 0x19 */
   66466      SQLITE_FLOAT,    /* 0x1a */
   66467      SQLITE_NULL,     /* 0x1b */
   66468      SQLITE_INTEGER,  /* 0x1c */
   66469      SQLITE_NULL,     /* 0x1d */
   66470      SQLITE_INTEGER,  /* 0x1e */
   66471      SQLITE_NULL,     /* 0x1f */
   66472   };
   66473   return aType[pVal->flags&MEM_AffMask];
   66474 }
   66475 
   66476 /**************************** sqlite3_result_  *******************************
   66477 ** The following routines are used by user-defined functions to specify
   66478 ** the function result.
   66479 **
   66480 ** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
   66481 ** result as a string or blob but if the string or blob is too large, it
   66482 ** then sets the error code to SQLITE_TOOBIG
   66483 */
   66484 static void setResultStrOrError(
   66485   sqlite3_context *pCtx,  /* Function context */
   66486   const char *z,          /* String pointer */
   66487   int n,                  /* Bytes in string, or negative */
   66488   u8 enc,                 /* Encoding of z.  0 for BLOBs */
   66489   void (*xDel)(void*)     /* Destructor function */
   66490 ){
   66491   if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
   66492     sqlite3_result_error_toobig(pCtx);
   66493   }
   66494 }
   66495 SQLITE_API void sqlite3_result_blob(
   66496   sqlite3_context *pCtx,
   66497   const void *z,
   66498   int n,
   66499   void (*xDel)(void *)
   66500 ){
   66501   assert( n>=0 );
   66502   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   66503   setResultStrOrError(pCtx, z, n, 0, xDel);
   66504 }
   66505 SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
   66506   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   66507   sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
   66508 }
   66509 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
   66510   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   66511   pCtx->isError = SQLITE_ERROR;
   66512   pCtx->fErrorOrAux = 1;
   66513   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
   66514 }
   66515 #ifndef SQLITE_OMIT_UTF16
   66516 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
   66517   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   66518   pCtx->isError = SQLITE_ERROR;
   66519   pCtx->fErrorOrAux = 1;
   66520   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
   66521 }
   66522 #endif
   66523 SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
   66524   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   66525   sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
   66526 }
   66527 SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
   66528   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   66529   sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
   66530 }
   66531 SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
   66532   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   66533   sqlite3VdbeMemSetNull(&pCtx->s);
   66534 }
   66535 SQLITE_API void sqlite3_result_text(
   66536   sqlite3_context *pCtx,
   66537   const char *z,
   66538   int n,
   66539   void (*xDel)(void *)
   66540 ){
   66541   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   66542   setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
   66543 }
   66544 #ifndef SQLITE_OMIT_UTF16
   66545 SQLITE_API void sqlite3_result_text16(
   66546   sqlite3_context *pCtx,
   66547   const void *z,
   66548   int n,
   66549   void (*xDel)(void *)
   66550 ){
   66551   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   66552   setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
   66553 }
   66554 SQLITE_API void sqlite3_result_text16be(
   66555   sqlite3_context *pCtx,
   66556   const void *z,
   66557   int n,
   66558   void (*xDel)(void *)
   66559 ){
   66560   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   66561   setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
   66562 }
   66563 SQLITE_API void sqlite3_result_text16le(
   66564   sqlite3_context *pCtx,
   66565   const void *z,
   66566   int n,
   66567   void (*xDel)(void *)
   66568 ){
   66569   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   66570   setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
   66571 }
   66572 #endif /* SQLITE_OMIT_UTF16 */
   66573 SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
   66574   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   66575   sqlite3VdbeMemCopy(&pCtx->s, pValue);
   66576 }
   66577 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
   66578   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   66579   sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
   66580 }
   66581 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
   66582   pCtx->isError = errCode;
   66583   pCtx->fErrorOrAux = 1;
   66584   if( pCtx->s.flags & MEM_Null ){
   66585     sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1,
   66586                          SQLITE_UTF8, SQLITE_STATIC);
   66587   }
   66588 }
   66589 
   66590 /* Force an SQLITE_TOOBIG error. */
   66591 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
   66592   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   66593   pCtx->isError = SQLITE_TOOBIG;
   66594   pCtx->fErrorOrAux = 1;
   66595   sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1,
   66596                        SQLITE_UTF8, SQLITE_STATIC);
   66597 }
   66598 
   66599 /* An SQLITE_NOMEM error. */
   66600 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
   66601   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   66602   sqlite3VdbeMemSetNull(&pCtx->s);
   66603   pCtx->isError = SQLITE_NOMEM;
   66604   pCtx->fErrorOrAux = 1;
   66605   pCtx->s.db->mallocFailed = 1;
   66606 }
   66607 
   66608 /*
   66609 ** This function is called after a transaction has been committed. It
   66610 ** invokes callbacks registered with sqlite3_wal_hook() as required.
   66611 */
   66612 static int doWalCallbacks(sqlite3 *db){
   66613   int rc = SQLITE_OK;
   66614 #ifndef SQLITE_OMIT_WAL
   66615   int i;
   66616   for(i=0; i<db->nDb; i++){
   66617     Btree *pBt = db->aDb[i].pBt;
   66618     if( pBt ){
   66619       int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
   66620       if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
   66621         rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
   66622       }
   66623     }
   66624   }
   66625 #endif
   66626   return rc;
   66627 }
   66628 
   66629 /*
   66630 ** Execute the statement pStmt, either until a row of data is ready, the
   66631 ** statement is completely executed or an error occurs.
   66632 **
   66633 ** This routine implements the bulk of the logic behind the sqlite_step()
   66634 ** API.  The only thing omitted is the automatic recompile if a
   66635 ** schema change has occurred.  That detail is handled by the
   66636 ** outer sqlite3_step() wrapper procedure.
   66637 */
   66638 static int sqlite3Step(Vdbe *p){
   66639   sqlite3 *db;
   66640   int rc;
   66641 
   66642   assert(p);
   66643   if( p->magic!=VDBE_MAGIC_RUN ){
   66644     /* We used to require that sqlite3_reset() be called before retrying
   66645     ** sqlite3_step() after any error or after SQLITE_DONE.  But beginning
   66646     ** with version 3.7.0, we changed this so that sqlite3_reset() would
   66647     ** be called automatically instead of throwing the SQLITE_MISUSE error.
   66648     ** This "automatic-reset" change is not technically an incompatibility,
   66649     ** since any application that receives an SQLITE_MISUSE is broken by
   66650     ** definition.
   66651     **
   66652     ** Nevertheless, some published applications that were originally written
   66653     ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
   66654     ** returns, and those were broken by the automatic-reset change.  As a
   66655     ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
   66656     ** legacy behavior of returning SQLITE_MISUSE for cases where the
   66657     ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
   66658     ** or SQLITE_BUSY error.
   66659     */
   66660 #ifdef SQLITE_OMIT_AUTORESET
   66661     if( p->rc==SQLITE_BUSY || p->rc==SQLITE_LOCKED ){
   66662       sqlite3_reset((sqlite3_stmt*)p);
   66663     }else{
   66664       return SQLITE_MISUSE_BKPT;
   66665     }
   66666 #else
   66667     sqlite3_reset((sqlite3_stmt*)p);
   66668 #endif
   66669   }
   66670 
   66671   /* Check that malloc() has not failed. If it has, return early. */
   66672   db = p->db;
   66673   if( db->mallocFailed ){
   66674     p->rc = SQLITE_NOMEM;
   66675     return SQLITE_NOMEM;
   66676   }
   66677 
   66678   if( p->pc<=0 && p->expired ){
   66679     p->rc = SQLITE_SCHEMA;
   66680     rc = SQLITE_ERROR;
   66681     goto end_of_step;
   66682   }
   66683   if( p->pc<0 ){
   66684     /* If there are no other statements currently running, then
   66685     ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
   66686     ** from interrupting a statement that has not yet started.
   66687     */
   66688     if( db->nVdbeActive==0 ){
   66689       db->u1.isInterrupted = 0;
   66690     }
   66691 
   66692     assert( db->nVdbeWrite>0 || db->autoCommit==0
   66693         || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
   66694     );
   66695 
   66696 #ifndef SQLITE_OMIT_TRACE
   66697     if( db->xProfile && !db->init.busy ){
   66698       sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
   66699     }
   66700 #endif
   66701 
   66702     db->nVdbeActive++;
   66703     if( p->readOnly==0 ) db->nVdbeWrite++;
   66704     if( p->bIsReader ) db->nVdbeRead++;
   66705     p->pc = 0;
   66706   }
   66707 #ifndef SQLITE_OMIT_EXPLAIN
   66708   if( p->explain ){
   66709     rc = sqlite3VdbeList(p);
   66710   }else
   66711 #endif /* SQLITE_OMIT_EXPLAIN */
   66712   {
   66713     db->nVdbeExec++;
   66714     rc = sqlite3VdbeExec(p);
   66715     db->nVdbeExec--;
   66716   }
   66717 
   66718 #ifndef SQLITE_OMIT_TRACE
   66719   /* Invoke the profile callback if there is one
   66720   */
   66721   if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
   66722     sqlite3_int64 iNow;
   66723     sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
   66724     db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
   66725   }
   66726 #endif
   66727 
   66728   if( rc==SQLITE_DONE ){
   66729     assert( p->rc==SQLITE_OK );
   66730     p->rc = doWalCallbacks(db);
   66731     if( p->rc!=SQLITE_OK ){
   66732       rc = SQLITE_ERROR;
   66733     }
   66734   }
   66735 
   66736   db->errCode = rc;
   66737   if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
   66738     p->rc = SQLITE_NOMEM;
   66739   }
   66740 end_of_step:
   66741   /* At this point local variable rc holds the value that should be
   66742   ** returned if this statement was compiled using the legacy
   66743   ** sqlite3_prepare() interface. According to the docs, this can only
   66744   ** be one of the values in the first assert() below. Variable p->rc
   66745   ** contains the value that would be returned if sqlite3_finalize()
   66746   ** were called on statement p.
   66747   */
   66748   assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR
   66749        || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
   66750   );
   66751   assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
   66752   if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
   66753     /* If this statement was prepared using sqlite3_prepare_v2(), and an
   66754     ** error has occurred, then return the error code in p->rc to the
   66755     ** caller. Set the error code in the database handle to the same value.
   66756     */
   66757     rc = sqlite3VdbeTransferError(p);
   66758   }
   66759   return (rc&db->errMask);
   66760 }
   66761 
   66762 /*
   66763 ** This is the top-level implementation of sqlite3_step().  Call
   66764 ** sqlite3Step() to do most of the work.  If a schema error occurs,
   66765 ** call sqlite3Reprepare() and try again.
   66766 */
   66767 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
   66768   int rc = SQLITE_OK;      /* Result from sqlite3Step() */
   66769   int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */
   66770   Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
   66771   int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
   66772   sqlite3 *db;             /* The database connection */
   66773 
   66774   if( vdbeSafetyNotNull(v) ){
   66775     return SQLITE_MISUSE_BKPT;
   66776   }
   66777   db = v->db;
   66778   sqlite3_mutex_enter(db->mutex);
   66779   v->doingRerun = 0;
   66780   while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
   66781          && cnt++ < SQLITE_MAX_SCHEMA_RETRY
   66782          && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
   66783     sqlite3_reset(pStmt);
   66784     v->doingRerun = 1;
   66785     assert( v->expired==0 );
   66786   }
   66787   if( rc2!=SQLITE_OK ){
   66788     /* This case occurs after failing to recompile an sql statement.
   66789     ** The error message from the SQL compiler has already been loaded
   66790     ** into the database handle. This block copies the error message
   66791     ** from the database handle into the statement and sets the statement
   66792     ** program counter to 0 to ensure that when the statement is
   66793     ** finalized or reset the parser error message is available via
   66794     ** sqlite3_errmsg() and sqlite3_errcode().
   66795     */
   66796     const char *zErr = (const char *)sqlite3_value_text(db->pErr);
   66797     assert( zErr!=0 || db->mallocFailed );
   66798     sqlite3DbFree(db, v->zErrMsg);
   66799     if( !db->mallocFailed ){
   66800       v->zErrMsg = sqlite3DbStrDup(db, zErr);
   66801       v->rc = rc2;
   66802     } else {
   66803       v->zErrMsg = 0;
   66804       v->rc = rc = SQLITE_NOMEM;
   66805     }
   66806   }
   66807   rc = sqlite3ApiExit(db, rc);
   66808   sqlite3_mutex_leave(db->mutex);
   66809   return rc;
   66810 }
   66811 
   66812 
   66813 /*
   66814 ** Extract the user data from a sqlite3_context structure and return a
   66815 ** pointer to it.
   66816 */
   66817 SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
   66818   assert( p && p->pFunc );
   66819   return p->pFunc->pUserData;
   66820 }
   66821 
   66822 /*
   66823 ** Extract the user data from a sqlite3_context structure and return a
   66824 ** pointer to it.
   66825 **
   66826 ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
   66827 ** returns a copy of the pointer to the database connection (the 1st
   66828 ** parameter) of the sqlite3_create_function() and
   66829 ** sqlite3_create_function16() routines that originally registered the
   66830 ** application defined function.
   66831 */
   66832 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
   66833   assert( p && p->pFunc );
   66834   return p->s.db;
   66835 }
   66836 
   66837 /*
   66838 ** Return the current time for a statement
   66839 */
   66840 SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
   66841   Vdbe *v = p->pVdbe;
   66842   int rc;
   66843   if( v->iCurrentTime==0 ){
   66844     rc = sqlite3OsCurrentTimeInt64(p->s.db->pVfs, &v->iCurrentTime);
   66845     if( rc ) v->iCurrentTime = 0;
   66846   }
   66847   return v->iCurrentTime;
   66848 }
   66849 
   66850 /*
   66851 ** The following is the implementation of an SQL function that always
   66852 ** fails with an error message stating that the function is used in the
   66853 ** wrong context.  The sqlite3_overload_function() API might construct
   66854 ** SQL function that use this routine so that the functions will exist
   66855 ** for name resolution but are actually overloaded by the xFindFunction
   66856 ** method of virtual tables.
   66857 */
   66858 SQLITE_PRIVATE void sqlite3InvalidFunction(
   66859   sqlite3_context *context,  /* The function calling context */
   66860   int NotUsed,               /* Number of arguments to the function */
   66861   sqlite3_value **NotUsed2   /* Value of each argument */
   66862 ){
   66863   const char *zName = context->pFunc->zName;
   66864   char *zErr;
   66865   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   66866   zErr = sqlite3_mprintf(
   66867       "unable to use function %s in the requested context", zName);
   66868   sqlite3_result_error(context, zErr, -1);
   66869   sqlite3_free(zErr);
   66870 }
   66871 
   66872 /*
   66873 ** Allocate or return the aggregate context for a user function.  A new
   66874 ** context is allocated on the first call.  Subsequent calls return the
   66875 ** same context that was returned on prior calls.
   66876 */
   66877 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
   66878   Mem *pMem;
   66879   assert( p && p->pFunc && p->pFunc->xStep );
   66880   assert( sqlite3_mutex_held(p->s.db->mutex) );
   66881   pMem = p->pMem;
   66882   testcase( nByte<0 );
   66883   if( (pMem->flags & MEM_Agg)==0 ){
   66884     if( nByte<=0 ){
   66885       sqlite3VdbeMemReleaseExternal(pMem);
   66886       pMem->flags = MEM_Null;
   66887       pMem->z = 0;
   66888     }else{
   66889       sqlite3VdbeMemGrow(pMem, nByte, 0);
   66890       pMem->flags = MEM_Agg;
   66891       pMem->u.pDef = p->pFunc;
   66892       if( pMem->z ){
   66893         memset(pMem->z, 0, nByte);
   66894       }
   66895     }
   66896   }
   66897   return (void*)pMem->z;
   66898 }
   66899 
   66900 /*
   66901 ** Return the auxilary data pointer, if any, for the iArg'th argument to
   66902 ** the user-function defined by pCtx.
   66903 */
   66904 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
   66905   AuxData *pAuxData;
   66906 
   66907   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   66908   for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
   66909     if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
   66910   }
   66911 
   66912   return (pAuxData ? pAuxData->pAux : 0);
   66913 }
   66914 
   66915 /*
   66916 ** Set the auxilary data pointer and delete function, for the iArg'th
   66917 ** argument to the user-function defined by pCtx. Any previous value is
   66918 ** deleted by calling the delete function specified when it was set.
   66919 */
   66920 SQLITE_API void sqlite3_set_auxdata(
   66921   sqlite3_context *pCtx,
   66922   int iArg,
   66923   void *pAux,
   66924   void (*xDelete)(void*)
   66925 ){
   66926   AuxData *pAuxData;
   66927   Vdbe *pVdbe = pCtx->pVdbe;
   66928 
   66929   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   66930   if( iArg<0 ) goto failed;
   66931 
   66932   for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
   66933     if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
   66934   }
   66935   if( pAuxData==0 ){
   66936     pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
   66937     if( !pAuxData ) goto failed;
   66938     pAuxData->iOp = pCtx->iOp;
   66939     pAuxData->iArg = iArg;
   66940     pAuxData->pNext = pVdbe->pAuxData;
   66941     pVdbe->pAuxData = pAuxData;
   66942     if( pCtx->fErrorOrAux==0 ){
   66943       pCtx->isError = 0;
   66944       pCtx->fErrorOrAux = 1;
   66945     }
   66946   }else if( pAuxData->xDelete ){
   66947     pAuxData->xDelete(pAuxData->pAux);
   66948   }
   66949 
   66950   pAuxData->pAux = pAux;
   66951   pAuxData->xDelete = xDelete;
   66952   return;
   66953 
   66954 failed:
   66955   if( xDelete ){
   66956     xDelete(pAux);
   66957   }
   66958 }
   66959 
   66960 #ifndef SQLITE_OMIT_DEPRECATED
   66961 /*
   66962 ** Return the number of times the Step function of a aggregate has been
   66963 ** called.
   66964 **
   66965 ** This function is deprecated.  Do not use it for new code.  It is
   66966 ** provide only to avoid breaking legacy code.  New aggregate function
   66967 ** implementations should keep their own counts within their aggregate
   66968 ** context.
   66969 */
   66970 SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
   66971   assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
   66972   return p->pMem->n;
   66973 }
   66974 #endif
   66975 
   66976 /*
   66977 ** Return the number of columns in the result set for the statement pStmt.
   66978 */
   66979 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
   66980   Vdbe *pVm = (Vdbe *)pStmt;
   66981   return pVm ? pVm->nResColumn : 0;
   66982 }
   66983 
   66984 /*
   66985 ** Return the number of values available from the current row of the
   66986 ** currently executing statement pStmt.
   66987 */
   66988 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
   66989   Vdbe *pVm = (Vdbe *)pStmt;
   66990   if( pVm==0 || pVm->pResultSet==0 ) return 0;
   66991   return pVm->nResColumn;
   66992 }
   66993 
   66994 /*
   66995 ** Return a pointer to static memory containing an SQL NULL value.
   66996 */
   66997 static const Mem *columnNullValue(void){
   66998   /* Even though the Mem structure contains an element
   66999   ** of type i64, on certain architectures (x86) with certain compiler
   67000   ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
   67001   ** instead of an 8-byte one. This all works fine, except that when
   67002   ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
   67003   ** that a Mem structure is located on an 8-byte boundary. To prevent
   67004   ** these assert()s from failing, when building with SQLITE_DEBUG defined
   67005   ** using gcc, we force nullMem to be 8-byte aligned using the magical
   67006   ** __attribute__((aligned(8))) macro.  */
   67007   static const Mem nullMem
   67008 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
   67009     __attribute__((aligned(8)))
   67010 #endif
   67011     = {0, "", (double)0, {0}, 0, MEM_Null, 0,
   67012 #ifdef SQLITE_DEBUG
   67013        0, 0,  /* pScopyFrom, pFiller */
   67014 #endif
   67015        0, 0 };
   67016   return &nullMem;
   67017 }
   67018 
   67019 /*
   67020 ** Check to see if column iCol of the given statement is valid.  If
   67021 ** it is, return a pointer to the Mem for the value of that column.
   67022 ** If iCol is not valid, return a pointer to a Mem which has a value
   67023 ** of NULL.
   67024 */
   67025 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
   67026   Vdbe *pVm;
   67027   Mem *pOut;
   67028 
   67029   pVm = (Vdbe *)pStmt;
   67030   if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
   67031     sqlite3_mutex_enter(pVm->db->mutex);
   67032     pOut = &pVm->pResultSet[i];
   67033   }else{
   67034     if( pVm && ALWAYS(pVm->db) ){
   67035       sqlite3_mutex_enter(pVm->db->mutex);
   67036       sqlite3Error(pVm->db, SQLITE_RANGE, 0);
   67037     }
   67038     pOut = (Mem*)columnNullValue();
   67039   }
   67040   return pOut;
   67041 }
   67042 
   67043 /*
   67044 ** This function is called after invoking an sqlite3_value_XXX function on a
   67045 ** column value (i.e. a value returned by evaluating an SQL expression in the
   67046 ** select list of a SELECT statement) that may cause a malloc() failure. If
   67047 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
   67048 ** code of statement pStmt set to SQLITE_NOMEM.
   67049 **
   67050 ** Specifically, this is called from within:
   67051 **
   67052 **     sqlite3_column_int()
   67053 **     sqlite3_column_int64()
   67054 **     sqlite3_column_text()
   67055 **     sqlite3_column_text16()
   67056 **     sqlite3_column_real()
   67057 **     sqlite3_column_bytes()
   67058 **     sqlite3_column_bytes16()
   67059 **     sqiite3_column_blob()
   67060 */
   67061 static void columnMallocFailure(sqlite3_stmt *pStmt)
   67062 {
   67063   /* If malloc() failed during an encoding conversion within an
   67064   ** sqlite3_column_XXX API, then set the return code of the statement to
   67065   ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
   67066   ** and _finalize() will return NOMEM.
   67067   */
   67068   Vdbe *p = (Vdbe *)pStmt;
   67069   if( p ){
   67070     p->rc = sqlite3ApiExit(p->db, p->rc);
   67071     sqlite3_mutex_leave(p->db->mutex);
   67072   }
   67073 }
   67074 
   67075 /**************************** sqlite3_column_  *******************************
   67076 ** The following routines are used to access elements of the current row
   67077 ** in the result set.
   67078 */
   67079 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
   67080   const void *val;
   67081   val = sqlite3_value_blob( columnMem(pStmt,i) );
   67082   /* Even though there is no encoding conversion, value_blob() might
   67083   ** need to call malloc() to expand the result of a zeroblob()
   67084   ** expression.
   67085   */
   67086   columnMallocFailure(pStmt);
   67087   return val;
   67088 }
   67089 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
   67090   int val = sqlite3_value_bytes( columnMem(pStmt,i) );
   67091   columnMallocFailure(pStmt);
   67092   return val;
   67093 }
   67094 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
   67095   int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
   67096   columnMallocFailure(pStmt);
   67097   return val;
   67098 }
   67099 SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
   67100   double val = sqlite3_value_double( columnMem(pStmt,i) );
   67101   columnMallocFailure(pStmt);
   67102   return val;
   67103 }
   67104 SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
   67105   int val = sqlite3_value_int( columnMem(pStmt,i) );
   67106   columnMallocFailure(pStmt);
   67107   return val;
   67108 }
   67109 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
   67110   sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
   67111   columnMallocFailure(pStmt);
   67112   return val;
   67113 }
   67114 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
   67115   const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
   67116   columnMallocFailure(pStmt);
   67117   return val;
   67118 }
   67119 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
   67120   Mem *pOut = columnMem(pStmt, i);
   67121   if( pOut->flags&MEM_Static ){
   67122     pOut->flags &= ~MEM_Static;
   67123     pOut->flags |= MEM_Ephem;
   67124   }
   67125   columnMallocFailure(pStmt);
   67126   return (sqlite3_value *)pOut;
   67127 }
   67128 #ifndef SQLITE_OMIT_UTF16
   67129 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
   67130   const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
   67131   columnMallocFailure(pStmt);
   67132   return val;
   67133 }
   67134 #endif /* SQLITE_OMIT_UTF16 */
   67135 SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
   67136   int iType = sqlite3_value_type( columnMem(pStmt,i) );
   67137   columnMallocFailure(pStmt);
   67138   return iType;
   67139 }
   67140 
   67141 /*
   67142 ** Convert the N-th element of pStmt->pColName[] into a string using
   67143 ** xFunc() then return that string.  If N is out of range, return 0.
   67144 **
   67145 ** There are up to 5 names for each column.  useType determines which
   67146 ** name is returned.  Here are the names:
   67147 **
   67148 **    0      The column name as it should be displayed for output
   67149 **    1      The datatype name for the column
   67150 **    2      The name of the database that the column derives from
   67151 **    3      The name of the table that the column derives from
   67152 **    4      The name of the table column that the result column derives from
   67153 **
   67154 ** If the result is not a simple column reference (if it is an expression
   67155 ** or a constant) then useTypes 2, 3, and 4 return NULL.
   67156 */
   67157 static const void *columnName(
   67158   sqlite3_stmt *pStmt,
   67159   int N,
   67160   const void *(*xFunc)(Mem*),
   67161   int useType
   67162 ){
   67163   const void *ret = 0;
   67164   Vdbe *p = (Vdbe *)pStmt;
   67165   int n;
   67166   sqlite3 *db = p->db;
   67167 
   67168   assert( db!=0 );
   67169   n = sqlite3_column_count(pStmt);
   67170   if( N<n && N>=0 ){
   67171     N += useType*n;
   67172     sqlite3_mutex_enter(db->mutex);
   67173     assert( db->mallocFailed==0 );
   67174     ret = xFunc(&p->aColName[N]);
   67175      /* A malloc may have failed inside of the xFunc() call. If this
   67176     ** is the case, clear the mallocFailed flag and return NULL.
   67177     */
   67178     if( db->mallocFailed ){
   67179       db->mallocFailed = 0;
   67180       ret = 0;
   67181     }
   67182     sqlite3_mutex_leave(db->mutex);
   67183   }
   67184   return ret;
   67185 }
   67186 
   67187 /*
   67188 ** Return the name of the Nth column of the result set returned by SQL
   67189 ** statement pStmt.
   67190 */
   67191 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
   67192   return columnName(
   67193       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
   67194 }
   67195 #ifndef SQLITE_OMIT_UTF16
   67196 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
   67197   return columnName(
   67198       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
   67199 }
   67200 #endif
   67201 
   67202 /*
   67203 ** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
   67204 ** not define OMIT_DECLTYPE.
   67205 */
   67206 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
   67207 # error "Must not define both SQLITE_OMIT_DECLTYPE \
   67208          and SQLITE_ENABLE_COLUMN_METADATA"
   67209 #endif
   67210 
   67211 #ifndef SQLITE_OMIT_DECLTYPE
   67212 /*
   67213 ** Return the column declaration type (if applicable) of the 'i'th column
   67214 ** of the result set of SQL statement pStmt.
   67215 */
   67216 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
   67217   return columnName(
   67218       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
   67219 }
   67220 #ifndef SQLITE_OMIT_UTF16
   67221 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
   67222   return columnName(
   67223       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
   67224 }
   67225 #endif /* SQLITE_OMIT_UTF16 */
   67226 #endif /* SQLITE_OMIT_DECLTYPE */
   67227 
   67228 #ifdef SQLITE_ENABLE_COLUMN_METADATA
   67229 /*
   67230 ** Return the name of the database from which a result column derives.
   67231 ** NULL is returned if the result column is an expression or constant or
   67232 ** anything else which is not an unabiguous reference to a database column.
   67233 */
   67234 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
   67235   return columnName(
   67236       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
   67237 }
   67238 #ifndef SQLITE_OMIT_UTF16
   67239 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
   67240   return columnName(
   67241       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
   67242 }
   67243 #endif /* SQLITE_OMIT_UTF16 */
   67244 
   67245 /*
   67246 ** Return the name of the table from which a result column derives.
   67247 ** NULL is returned if the result column is an expression or constant or
   67248 ** anything else which is not an unabiguous reference to a database column.
   67249 */
   67250 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
   67251   return columnName(
   67252       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
   67253 }
   67254 #ifndef SQLITE_OMIT_UTF16
   67255 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
   67256   return columnName(
   67257       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
   67258 }
   67259 #endif /* SQLITE_OMIT_UTF16 */
   67260 
   67261 /*
   67262 ** Return the name of the table column from which a result column derives.
   67263 ** NULL is returned if the result column is an expression or constant or
   67264 ** anything else which is not an unabiguous reference to a database column.
   67265 */
   67266 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
   67267   return columnName(
   67268       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
   67269 }
   67270 #ifndef SQLITE_OMIT_UTF16
   67271 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
   67272   return columnName(
   67273       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
   67274 }
   67275 #endif /* SQLITE_OMIT_UTF16 */
   67276 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
   67277 
   67278 
   67279 /******************************* sqlite3_bind_  ***************************
   67280 **
   67281 ** Routines used to attach values to wildcards in a compiled SQL statement.
   67282 */
   67283 /*
   67284 ** Unbind the value bound to variable i in virtual machine p. This is the
   67285 ** the same as binding a NULL value to the column. If the "i" parameter is
   67286 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
   67287 **
   67288 ** A successful evaluation of this routine acquires the mutex on p.
   67289 ** the mutex is released if any kind of error occurs.
   67290 **
   67291 ** The error code stored in database p->db is overwritten with the return
   67292 ** value in any case.
   67293 */
   67294 static int vdbeUnbind(Vdbe *p, int i){
   67295   Mem *pVar;
   67296   if( vdbeSafetyNotNull(p) ){
   67297     return SQLITE_MISUSE_BKPT;
   67298   }
   67299   sqlite3_mutex_enter(p->db->mutex);
   67300   if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
   67301     sqlite3Error(p->db, SQLITE_MISUSE, 0);
   67302     sqlite3_mutex_leave(p->db->mutex);
   67303     sqlite3_log(SQLITE_MISUSE,
   67304         "bind on a busy prepared statement: [%s]", p->zSql);
   67305     return SQLITE_MISUSE_BKPT;
   67306   }
   67307   if( i<1 || i>p->nVar ){
   67308     sqlite3Error(p->db, SQLITE_RANGE, 0);
   67309     sqlite3_mutex_leave(p->db->mutex);
   67310     return SQLITE_RANGE;
   67311   }
   67312   i--;
   67313   pVar = &p->aVar[i];
   67314   sqlite3VdbeMemRelease(pVar);
   67315   pVar->flags = MEM_Null;
   67316   sqlite3Error(p->db, SQLITE_OK, 0);
   67317 
   67318   /* If the bit corresponding to this variable in Vdbe.expmask is set, then
   67319   ** binding a new value to this variable invalidates the current query plan.
   67320   **
   67321   ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
   67322   ** parameter in the WHERE clause might influence the choice of query plan
   67323   ** for a statement, then the statement will be automatically recompiled,
   67324   ** as if there had been a schema change, on the first sqlite3_step() call
   67325   ** following any change to the bindings of that parameter.
   67326   */
   67327   if( p->isPrepareV2 &&
   67328      ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
   67329   ){
   67330     p->expired = 1;
   67331   }
   67332   return SQLITE_OK;
   67333 }
   67334 
   67335 /*
   67336 ** Bind a text or BLOB value.
   67337 */
   67338 static int bindText(
   67339   sqlite3_stmt *pStmt,   /* The statement to bind against */
   67340   int i,                 /* Index of the parameter to bind */
   67341   const void *zData,     /* Pointer to the data to be bound */
   67342   int nData,             /* Number of bytes of data to be bound */
   67343   void (*xDel)(void*),   /* Destructor for the data */
   67344   u8 encoding            /* Encoding for the data */
   67345 ){
   67346   Vdbe *p = (Vdbe *)pStmt;
   67347   Mem *pVar;
   67348   int rc;
   67349 
   67350   rc = vdbeUnbind(p, i);
   67351   if( rc==SQLITE_OK ){
   67352     if( zData!=0 ){
   67353       pVar = &p->aVar[i-1];
   67354       rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
   67355       if( rc==SQLITE_OK && encoding!=0 ){
   67356         rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
   67357       }
   67358       sqlite3Error(p->db, rc, 0);
   67359       rc = sqlite3ApiExit(p->db, rc);
   67360     }
   67361     sqlite3_mutex_leave(p->db->mutex);
   67362   }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
   67363     xDel((void*)zData);
   67364   }
   67365   return rc;
   67366 }
   67367 
   67368 
   67369 /*
   67370 ** Bind a blob value to an SQL statement variable.
   67371 */
   67372 SQLITE_API int sqlite3_bind_blob(
   67373   sqlite3_stmt *pStmt,
   67374   int i,
   67375   const void *zData,
   67376   int nData,
   67377   void (*xDel)(void*)
   67378 ){
   67379   return bindText(pStmt, i, zData, nData, xDel, 0);
   67380 }
   67381 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
   67382   int rc;
   67383   Vdbe *p = (Vdbe *)pStmt;
   67384   rc = vdbeUnbind(p, i);
   67385   if( rc==SQLITE_OK ){
   67386     sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
   67387     sqlite3_mutex_leave(p->db->mutex);
   67388   }
   67389   return rc;
   67390 }
   67391 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
   67392   return sqlite3_bind_int64(p, i, (i64)iValue);
   67393 }
   67394 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
   67395   int rc;
   67396   Vdbe *p = (Vdbe *)pStmt;
   67397   rc = vdbeUnbind(p, i);
   67398   if( rc==SQLITE_OK ){
   67399     sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
   67400     sqlite3_mutex_leave(p->db->mutex);
   67401   }
   67402   return rc;
   67403 }
   67404 SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
   67405   int rc;
   67406   Vdbe *p = (Vdbe*)pStmt;
   67407   rc = vdbeUnbind(p, i);
   67408   if( rc==SQLITE_OK ){
   67409     sqlite3_mutex_leave(p->db->mutex);
   67410   }
   67411   return rc;
   67412 }
   67413 SQLITE_API int sqlite3_bind_text(
   67414   sqlite3_stmt *pStmt,
   67415   int i,
   67416   const char *zData,
   67417   int nData,
   67418   void (*xDel)(void*)
   67419 ){
   67420   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
   67421 }
   67422 #ifndef SQLITE_OMIT_UTF16
   67423 SQLITE_API int sqlite3_bind_text16(
   67424   sqlite3_stmt *pStmt,
   67425   int i,
   67426   const void *zData,
   67427   int nData,
   67428   void (*xDel)(void*)
   67429 ){
   67430   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
   67431 }
   67432 #endif /* SQLITE_OMIT_UTF16 */
   67433 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
   67434   int rc;
   67435   switch( sqlite3_value_type((sqlite3_value*)pValue) ){
   67436     case SQLITE_INTEGER: {
   67437       rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
   67438       break;
   67439     }
   67440     case SQLITE_FLOAT: {
   67441       rc = sqlite3_bind_double(pStmt, i, pValue->r);
   67442       break;
   67443     }
   67444     case SQLITE_BLOB: {
   67445       if( pValue->flags & MEM_Zero ){
   67446         rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
   67447       }else{
   67448         rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
   67449       }
   67450       break;
   67451     }
   67452     case SQLITE_TEXT: {
   67453       rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
   67454                               pValue->enc);
   67455       break;
   67456     }
   67457     default: {
   67458       rc = sqlite3_bind_null(pStmt, i);
   67459       break;
   67460     }
   67461   }
   67462   return rc;
   67463 }
   67464 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
   67465   int rc;
   67466   Vdbe *p = (Vdbe *)pStmt;
   67467   rc = vdbeUnbind(p, i);
   67468   if( rc==SQLITE_OK ){
   67469     sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
   67470     sqlite3_mutex_leave(p->db->mutex);
   67471   }
   67472   return rc;
   67473 }
   67474 
   67475 /*
   67476 ** Return the number of wildcards that can be potentially bound to.
   67477 ** This routine is added to support DBD::SQLite.
   67478 */
   67479 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
   67480   Vdbe *p = (Vdbe*)pStmt;
   67481   return p ? p->nVar : 0;
   67482 }
   67483 
   67484 /*
   67485 ** Return the name of a wildcard parameter.  Return NULL if the index
   67486 ** is out of range or if the wildcard is unnamed.
   67487 **
   67488 ** The result is always UTF-8.
   67489 */
   67490 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
   67491   Vdbe *p = (Vdbe*)pStmt;
   67492   if( p==0 || i<1 || i>p->nzVar ){
   67493     return 0;
   67494   }
   67495   return p->azVar[i-1];
   67496 }
   67497 
   67498 /*
   67499 ** Given a wildcard parameter name, return the index of the variable
   67500 ** with that name.  If there is no variable with the given name,
   67501 ** return 0.
   67502 */
   67503 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
   67504   int i;
   67505   if( p==0 ){
   67506     return 0;
   67507   }
   67508   if( zName ){
   67509     for(i=0; i<p->nzVar; i++){
   67510       const char *z = p->azVar[i];
   67511       if( z && strncmp(z,zName,nName)==0 && z[nName]==0 ){
   67512         return i+1;
   67513       }
   67514     }
   67515   }
   67516   return 0;
   67517 }
   67518 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
   67519   return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
   67520 }
   67521 
   67522 /*
   67523 ** Transfer all bindings from the first statement over to the second.
   67524 */
   67525 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
   67526   Vdbe *pFrom = (Vdbe*)pFromStmt;
   67527   Vdbe *pTo = (Vdbe*)pToStmt;
   67528   int i;
   67529   assert( pTo->db==pFrom->db );
   67530   assert( pTo->nVar==pFrom->nVar );
   67531   sqlite3_mutex_enter(pTo->db->mutex);
   67532   for(i=0; i<pFrom->nVar; i++){
   67533     sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
   67534   }
   67535   sqlite3_mutex_leave(pTo->db->mutex);
   67536   return SQLITE_OK;
   67537 }
   67538 
   67539 #ifndef SQLITE_OMIT_DEPRECATED
   67540 /*
   67541 ** Deprecated external interface.  Internal/core SQLite code
   67542 ** should call sqlite3TransferBindings.
   67543 **
   67544 ** Is is misuse to call this routine with statements from different
   67545 ** database connections.  But as this is a deprecated interface, we
   67546 ** will not bother to check for that condition.
   67547 **
   67548 ** If the two statements contain a different number of bindings, then
   67549 ** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
   67550 ** SQLITE_OK is returned.
   67551 */
   67552 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
   67553   Vdbe *pFrom = (Vdbe*)pFromStmt;
   67554   Vdbe *pTo = (Vdbe*)pToStmt;
   67555   if( pFrom->nVar!=pTo->nVar ){
   67556     return SQLITE_ERROR;
   67557   }
   67558   if( pTo->isPrepareV2 && pTo->expmask ){
   67559     pTo->expired = 1;
   67560   }
   67561   if( pFrom->isPrepareV2 && pFrom->expmask ){
   67562     pFrom->expired = 1;
   67563   }
   67564   return sqlite3TransferBindings(pFromStmt, pToStmt);
   67565 }
   67566 #endif
   67567 
   67568 /*
   67569 ** Return the sqlite3* database handle to which the prepared statement given
   67570 ** in the argument belongs.  This is the same database handle that was
   67571 ** the first argument to the sqlite3_prepare() that was used to create
   67572 ** the statement in the first place.
   67573 */
   67574 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
   67575   return pStmt ? ((Vdbe*)pStmt)->db : 0;
   67576 }
   67577 
   67578 /*
   67579 ** Return true if the prepared statement is guaranteed to not modify the
   67580 ** database.
   67581 */
   67582 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
   67583   return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
   67584 }
   67585 
   67586 /*
   67587 ** Return true if the prepared statement is in need of being reset.
   67588 */
   67589 SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
   67590   Vdbe *v = (Vdbe*)pStmt;
   67591   return v!=0 && v->pc>=0 && v->magic==VDBE_MAGIC_RUN;
   67592 }
   67593 
   67594 /*
   67595 ** Return a pointer to the next prepared statement after pStmt associated
   67596 ** with database connection pDb.  If pStmt is NULL, return the first
   67597 ** prepared statement for the database connection.  Return NULL if there
   67598 ** are no more.
   67599 */
   67600 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
   67601   sqlite3_stmt *pNext;
   67602   sqlite3_mutex_enter(pDb->mutex);
   67603   if( pStmt==0 ){
   67604     pNext = (sqlite3_stmt*)pDb->pVdbe;
   67605   }else{
   67606     pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
   67607   }
   67608   sqlite3_mutex_leave(pDb->mutex);
   67609   return pNext;
   67610 }
   67611 
   67612 /*
   67613 ** Return the value of a status counter for a prepared statement
   67614 */
   67615 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
   67616   Vdbe *pVdbe = (Vdbe*)pStmt;
   67617   u32 v = pVdbe->aCounter[op];
   67618   if( resetFlag ) pVdbe->aCounter[op] = 0;
   67619   return (int)v;
   67620 }
   67621 
   67622 /************** End of vdbeapi.c *********************************************/
   67623 /************** Begin file vdbetrace.c ***************************************/
   67624 /*
   67625 ** 2009 November 25
   67626 **
   67627 ** The author disclaims copyright to this source code.  In place of
   67628 ** a legal notice, here is a blessing:
   67629 **
   67630 **    May you do good and not evil.
   67631 **    May you find forgiveness for yourself and forgive others.
   67632 **    May you share freely, never taking more than you give.
   67633 **
   67634 *************************************************************************
   67635 **
   67636 ** This file contains code used to insert the values of host parameters
   67637 ** (aka "wildcards") into the SQL text output by sqlite3_trace().
   67638 **
   67639 ** The Vdbe parse-tree explainer is also found here.
   67640 */
   67641 
   67642 #ifndef SQLITE_OMIT_TRACE
   67643 
   67644 /*
   67645 ** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
   67646 ** bytes in this text up to but excluding the first character in
   67647 ** a host parameter.  If the text contains no host parameters, return
   67648 ** the total number of bytes in the text.
   67649 */
   67650 static int findNextHostParameter(const char *zSql, int *pnToken){
   67651   int tokenType;
   67652   int nTotal = 0;
   67653   int n;
   67654 
   67655   *pnToken = 0;
   67656   while( zSql[0] ){
   67657     n = sqlite3GetToken((u8*)zSql, &tokenType);
   67658     assert( n>0 && tokenType!=TK_ILLEGAL );
   67659     if( tokenType==TK_VARIABLE ){
   67660       *pnToken = n;
   67661       break;
   67662     }
   67663     nTotal += n;
   67664     zSql += n;
   67665   }
   67666   return nTotal;
   67667 }
   67668 
   67669 /*
   67670 ** This function returns a pointer to a nul-terminated string in memory
   67671 ** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
   67672 ** string contains a copy of zRawSql but with host parameters expanded to
   67673 ** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
   67674 ** then the returned string holds a copy of zRawSql with "-- " prepended
   67675 ** to each line of text.
   67676 **
   67677 ** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
   67678 ** then long strings and blobs are truncated to that many bytes.  This
   67679 ** can be used to prevent unreasonably large trace strings when dealing
   67680 ** with large (multi-megabyte) strings and blobs.
   67681 **
   67682 ** The calling function is responsible for making sure the memory returned
   67683 ** is eventually freed.
   67684 **
   67685 ** ALGORITHM:  Scan the input string looking for host parameters in any of
   67686 ** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
   67687 ** string literals, quoted identifier names, and comments.  For text forms,
   67688 ** the host parameter index is found by scanning the perpared
   67689 ** statement for the corresponding OP_Variable opcode.  Once the host
   67690 ** parameter index is known, locate the value in p->aVar[].  Then render
   67691 ** the value as a literal in place of the host parameter name.
   67692 */
   67693 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
   67694   Vdbe *p,                 /* The prepared statement being evaluated */
   67695   const char *zRawSql      /* Raw text of the SQL statement */
   67696 ){
   67697   sqlite3 *db;             /* The database connection */
   67698   int idx = 0;             /* Index of a host parameter */
   67699   int nextIndex = 1;       /* Index of next ? host parameter */
   67700   int n;                   /* Length of a token prefix */
   67701   int nToken;              /* Length of the parameter token */
   67702   int i;                   /* Loop counter */
   67703   Mem *pVar;               /* Value of a host parameter */
   67704   StrAccum out;            /* Accumulate the output here */
   67705   char zBase[100];         /* Initial working space */
   67706 
   67707   db = p->db;
   67708   sqlite3StrAccumInit(&out, zBase, sizeof(zBase),
   67709                       db->aLimit[SQLITE_LIMIT_LENGTH]);
   67710   out.db = db;
   67711   if( db->nVdbeExec>1 ){
   67712     while( *zRawSql ){
   67713       const char *zStart = zRawSql;
   67714       while( *(zRawSql++)!='\n' && *zRawSql );
   67715       sqlite3StrAccumAppend(&out, "-- ", 3);
   67716       assert( (zRawSql - zStart) > 0 );
   67717       sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
   67718     }
   67719   }else{
   67720     while( zRawSql[0] ){
   67721       n = findNextHostParameter(zRawSql, &nToken);
   67722       assert( n>0 );
   67723       sqlite3StrAccumAppend(&out, zRawSql, n);
   67724       zRawSql += n;
   67725       assert( zRawSql[0] || nToken==0 );
   67726       if( nToken==0 ) break;
   67727       if( zRawSql[0]=='?' ){
   67728         if( nToken>1 ){
   67729           assert( sqlite3Isdigit(zRawSql[1]) );
   67730           sqlite3GetInt32(&zRawSql[1], &idx);
   67731         }else{
   67732           idx = nextIndex;
   67733         }
   67734       }else{
   67735         assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
   67736         testcase( zRawSql[0]==':' );
   67737         testcase( zRawSql[0]=='$' );
   67738         testcase( zRawSql[0]=='@' );
   67739         idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
   67740         assert( idx>0 );
   67741       }
   67742       zRawSql += nToken;
   67743       nextIndex = idx + 1;
   67744       assert( idx>0 && idx<=p->nVar );
   67745       pVar = &p->aVar[idx-1];
   67746       if( pVar->flags & MEM_Null ){
   67747         sqlite3StrAccumAppend(&out, "NULL", 4);
   67748       }else if( pVar->flags & MEM_Int ){
   67749         sqlite3XPrintf(&out, 0, "%lld", pVar->u.i);
   67750       }else if( pVar->flags & MEM_Real ){
   67751         sqlite3XPrintf(&out, 0, "%!.15g", pVar->r);
   67752       }else if( pVar->flags & MEM_Str ){
   67753         int nOut;  /* Number of bytes of the string text to include in output */
   67754 #ifndef SQLITE_OMIT_UTF16
   67755         u8 enc = ENC(db);
   67756         Mem utf8;
   67757         if( enc!=SQLITE_UTF8 ){
   67758           memset(&utf8, 0, sizeof(utf8));
   67759           utf8.db = db;
   67760           sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
   67761           sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
   67762           pVar = &utf8;
   67763         }
   67764 #endif
   67765         nOut = pVar->n;
   67766 #ifdef SQLITE_TRACE_SIZE_LIMIT
   67767         if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
   67768           nOut = SQLITE_TRACE_SIZE_LIMIT;
   67769           while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
   67770         }
   67771 #endif
   67772         sqlite3XPrintf(&out, 0, "'%.*q'", nOut, pVar->z);
   67773 #ifdef SQLITE_TRACE_SIZE_LIMIT
   67774         if( nOut<pVar->n ){
   67775           sqlite3XPrintf(&out, 0, "/*+%d bytes*/", pVar->n-nOut);
   67776         }
   67777 #endif
   67778 #ifndef SQLITE_OMIT_UTF16
   67779         if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
   67780 #endif
   67781       }else if( pVar->flags & MEM_Zero ){
   67782         sqlite3XPrintf(&out, 0, "zeroblob(%d)", pVar->u.nZero);
   67783       }else{
   67784         int nOut;  /* Number of bytes of the blob to include in output */
   67785         assert( pVar->flags & MEM_Blob );
   67786         sqlite3StrAccumAppend(&out, "x'", 2);
   67787         nOut = pVar->n;
   67788 #ifdef SQLITE_TRACE_SIZE_LIMIT
   67789         if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
   67790 #endif
   67791         for(i=0; i<nOut; i++){
   67792           sqlite3XPrintf(&out, 0, "%02x", pVar->z[i]&0xff);
   67793         }
   67794         sqlite3StrAccumAppend(&out, "'", 1);
   67795 #ifdef SQLITE_TRACE_SIZE_LIMIT
   67796         if( nOut<pVar->n ){
   67797           sqlite3XPrintf(&out, 0, "/*+%d bytes*/", pVar->n-nOut);
   67798         }
   67799 #endif
   67800       }
   67801     }
   67802   }
   67803   return sqlite3StrAccumFinish(&out);
   67804 }
   67805 
   67806 #endif /* #ifndef SQLITE_OMIT_TRACE */
   67807 
   67808 /*****************************************************************************
   67809 ** The following code implements the data-structure explaining logic
   67810 ** for the Vdbe.
   67811 */
   67812 
   67813 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
   67814 
   67815 /*
   67816 ** Allocate a new Explain object
   67817 */
   67818 SQLITE_PRIVATE void sqlite3ExplainBegin(Vdbe *pVdbe){
   67819   if( pVdbe ){
   67820     Explain *p;
   67821     sqlite3BeginBenignMalloc();
   67822     p = (Explain *)sqlite3MallocZero( sizeof(Explain) );
   67823     if( p ){
   67824       p->pVdbe = pVdbe;
   67825       sqlite3_free(pVdbe->pExplain);
   67826       pVdbe->pExplain = p;
   67827       sqlite3StrAccumInit(&p->str, p->zBase, sizeof(p->zBase),
   67828                           SQLITE_MAX_LENGTH);
   67829       p->str.useMalloc = 2;
   67830     }else{
   67831       sqlite3EndBenignMalloc();
   67832     }
   67833   }
   67834 }
   67835 
   67836 /*
   67837 ** Return true if the Explain ends with a new-line.
   67838 */
   67839 static int endsWithNL(Explain *p){
   67840   return p && p->str.zText && p->str.nChar
   67841            && p->str.zText[p->str.nChar-1]=='\n';
   67842 }
   67843 
   67844 /*
   67845 ** Append text to the indentation
   67846 */
   67847 SQLITE_PRIVATE void sqlite3ExplainPrintf(Vdbe *pVdbe, const char *zFormat, ...){
   67848   Explain *p;
   67849   if( pVdbe && (p = pVdbe->pExplain)!=0 ){
   67850     va_list ap;
   67851     if( p->nIndent && endsWithNL(p) ){
   67852       int n = p->nIndent;
   67853       if( n>ArraySize(p->aIndent) ) n = ArraySize(p->aIndent);
   67854       sqlite3AppendSpace(&p->str, p->aIndent[n-1]);
   67855     }
   67856     va_start(ap, zFormat);
   67857     sqlite3VXPrintf(&p->str, SQLITE_PRINTF_INTERNAL, zFormat, ap);
   67858     va_end(ap);
   67859   }
   67860 }
   67861 
   67862 /*
   67863 ** Append a '\n' if there is not already one.
   67864 */
   67865 SQLITE_PRIVATE void sqlite3ExplainNL(Vdbe *pVdbe){
   67866   Explain *p;
   67867   if( pVdbe && (p = pVdbe->pExplain)!=0 && !endsWithNL(p) ){
   67868     sqlite3StrAccumAppend(&p->str, "\n", 1);
   67869   }
   67870 }
   67871 
   67872 /*
   67873 ** Push a new indentation level.  Subsequent lines will be indented
   67874 ** so that they begin at the current cursor position.
   67875 */
   67876 SQLITE_PRIVATE void sqlite3ExplainPush(Vdbe *pVdbe){
   67877   Explain *p;
   67878   if( pVdbe && (p = pVdbe->pExplain)!=0 ){
   67879     if( p->str.zText && p->nIndent<ArraySize(p->aIndent) ){
   67880       const char *z = p->str.zText;
   67881       int i = p->str.nChar-1;
   67882       int x;
   67883       while( i>=0 && z[i]!='\n' ){ i--; }
   67884       x = (p->str.nChar - 1) - i;
   67885       if( p->nIndent && x<p->aIndent[p->nIndent-1] ){
   67886         x = p->aIndent[p->nIndent-1];
   67887       }
   67888       p->aIndent[p->nIndent] = x;
   67889     }
   67890     p->nIndent++;
   67891   }
   67892 }
   67893 
   67894 /*
   67895 ** Pop the indentation stack by one level.
   67896 */
   67897 SQLITE_PRIVATE void sqlite3ExplainPop(Vdbe *p){
   67898   if( p && p->pExplain ) p->pExplain->nIndent--;
   67899 }
   67900 
   67901 /*
   67902 ** Free the indentation structure
   67903 */
   67904 SQLITE_PRIVATE void sqlite3ExplainFinish(Vdbe *pVdbe){
   67905   if( pVdbe && pVdbe->pExplain ){
   67906     sqlite3_free(pVdbe->zExplain);
   67907     sqlite3ExplainNL(pVdbe);
   67908     pVdbe->zExplain = sqlite3StrAccumFinish(&pVdbe->pExplain->str);
   67909     sqlite3_free(pVdbe->pExplain);
   67910     pVdbe->pExplain = 0;
   67911     sqlite3EndBenignMalloc();
   67912   }
   67913 }
   67914 
   67915 /*
   67916 ** Return the explanation of a virtual machine.
   67917 */
   67918 SQLITE_PRIVATE const char *sqlite3VdbeExplanation(Vdbe *pVdbe){
   67919   return (pVdbe && pVdbe->zExplain) ? pVdbe->zExplain : 0;
   67920 }
   67921 #endif /* defined(SQLITE_DEBUG) */
   67922 
   67923 /************** End of vdbetrace.c *******************************************/
   67924 /************** Begin file vdbe.c ********************************************/
   67925 /*
   67926 ** 2001 September 15
   67927 **
   67928 ** The author disclaims copyright to this source code.  In place of
   67929 ** a legal notice, here is a blessing:
   67930 **
   67931 **    May you do good and not evil.
   67932 **    May you find forgiveness for yourself and forgive others.
   67933 **    May you share freely, never taking more than you give.
   67934 **
   67935 *************************************************************************
   67936 ** The code in this file implements the function that runs the
   67937 ** bytecode of a prepared statement.
   67938 **
   67939 ** Various scripts scan this source file in order to generate HTML
   67940 ** documentation, headers files, or other derived files.  The formatting
   67941 ** of the code in this file is, therefore, important.  See other comments
   67942 ** in this file for details.  If in doubt, do not deviate from existing
   67943 ** commenting and indentation practices when changing or adding code.
   67944 */
   67945 
   67946 /*
   67947 ** Invoke this macro on memory cells just prior to changing the
   67948 ** value of the cell.  This macro verifies that shallow copies are
   67949 ** not misused.  A shallow copy of a string or blob just copies a
   67950 ** pointer to the string or blob, not the content.  If the original
   67951 ** is changed while the copy is still in use, the string or blob might
   67952 ** be changed out from under the copy.  This macro verifies that nothing
   67953 ** like that ever happens.
   67954 */
   67955 #ifdef SQLITE_DEBUG
   67956 # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
   67957 #else
   67958 # define memAboutToChange(P,M)
   67959 #endif
   67960 
   67961 /*
   67962 ** The following global variable is incremented every time a cursor
   67963 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
   67964 ** procedures use this information to make sure that indices are
   67965 ** working correctly.  This variable has no function other than to
   67966 ** help verify the correct operation of the library.
   67967 */
   67968 #ifdef SQLITE_TEST
   67969 SQLITE_API int sqlite3_search_count = 0;
   67970 #endif
   67971 
   67972 /*
   67973 ** When this global variable is positive, it gets decremented once before
   67974 ** each instruction in the VDBE.  When it reaches zero, the u1.isInterrupted
   67975 ** field of the sqlite3 structure is set in order to simulate an interrupt.
   67976 **
   67977 ** This facility is used for testing purposes only.  It does not function
   67978 ** in an ordinary build.
   67979 */
   67980 #ifdef SQLITE_TEST
   67981 SQLITE_API int sqlite3_interrupt_count = 0;
   67982 #endif
   67983 
   67984 /*
   67985 ** The next global variable is incremented each type the OP_Sort opcode
   67986 ** is executed.  The test procedures use this information to make sure that
   67987 ** sorting is occurring or not occurring at appropriate times.   This variable
   67988 ** has no function other than to help verify the correct operation of the
   67989 ** library.
   67990 */
   67991 #ifdef SQLITE_TEST
   67992 SQLITE_API int sqlite3_sort_count = 0;
   67993 #endif
   67994 
   67995 /*
   67996 ** The next global variable records the size of the largest MEM_Blob
   67997 ** or MEM_Str that has been used by a VDBE opcode.  The test procedures
   67998 ** use this information to make sure that the zero-blob functionality
   67999 ** is working correctly.   This variable has no function other than to
   68000 ** help verify the correct operation of the library.
   68001 */
   68002 #ifdef SQLITE_TEST
   68003 SQLITE_API int sqlite3_max_blobsize = 0;
   68004 static void updateMaxBlobsize(Mem *p){
   68005   if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
   68006     sqlite3_max_blobsize = p->n;
   68007   }
   68008 }
   68009 #endif
   68010 
   68011 /*
   68012 ** The next global variable is incremented each time the OP_Found opcode
   68013 ** is executed. This is used to test whether or not the foreign key
   68014 ** operation implemented using OP_FkIsZero is working. This variable
   68015 ** has no function other than to help verify the correct operation of the
   68016 ** library.
   68017 */
   68018 #ifdef SQLITE_TEST
   68019 SQLITE_API int sqlite3_found_count = 0;
   68020 #endif
   68021 
   68022 /*
   68023 ** Test a register to see if it exceeds the current maximum blob size.
   68024 ** If it does, record the new maximum blob size.
   68025 */
   68026 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
   68027 # define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
   68028 #else
   68029 # define UPDATE_MAX_BLOBSIZE(P)
   68030 #endif
   68031 
   68032 /*
   68033 ** Invoke the VDBE coverage callback, if that callback is defined.  This
   68034 ** feature is used for test suite validation only and does not appear an
   68035 ** production builds.
   68036 **
   68037 ** M is an integer, 2 or 3, that indices how many different ways the
   68038 ** branch can go.  It is usually 2.  "I" is the direction the branch
   68039 ** goes.  0 means falls through.  1 means branch is taken.  2 means the
   68040 ** second alternative branch is taken.
   68041 **
   68042 ** iSrcLine is the source code line (from the __LINE__ macro) that
   68043 ** generated the VDBE instruction.  This instrumentation assumes that all
   68044 ** source code is in a single file (the amalgamation).  Special values 1
   68045 ** and 2 for the iSrcLine parameter mean that this particular branch is
   68046 ** always taken or never taken, respectively.
   68047 */
   68048 #if !defined(SQLITE_VDBE_COVERAGE)
   68049 # define VdbeBranchTaken(I,M)
   68050 #else
   68051 # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
   68052   static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){
   68053     if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){
   68054       M = iSrcLine;
   68055       /* Assert the truth of VdbeCoverageAlwaysTaken() and
   68056       ** VdbeCoverageNeverTaken() */
   68057       assert( (M & I)==I );
   68058     }else{
   68059       if( sqlite3GlobalConfig.xVdbeBranch==0 ) return;  /*NO_TEST*/
   68060       sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
   68061                                       iSrcLine,I,M);
   68062     }
   68063   }
   68064 #endif
   68065 
   68066 /*
   68067 ** Convert the given register into a string if it isn't one
   68068 ** already. Return non-zero if a malloc() fails.
   68069 */
   68070 #define Stringify(P, enc) \
   68071    if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
   68072      { goto no_mem; }
   68073 
   68074 /*
   68075 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
   68076 ** a pointer to a dynamically allocated string where some other entity
   68077 ** is responsible for deallocating that string.  Because the register
   68078 ** does not control the string, it might be deleted without the register
   68079 ** knowing it.
   68080 **
   68081 ** This routine converts an ephemeral string into a dynamically allocated
   68082 ** string that the register itself controls.  In other words, it
   68083 ** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
   68084 */
   68085 #define Deephemeralize(P) \
   68086    if( ((P)->flags&MEM_Ephem)!=0 \
   68087        && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
   68088 
   68089 /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
   68090 #define isSorter(x) ((x)->pSorter!=0)
   68091 
   68092 /*
   68093 ** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
   68094 ** if we run out of memory.
   68095 */
   68096 static VdbeCursor *allocateCursor(
   68097   Vdbe *p,              /* The virtual machine */
   68098   int iCur,             /* Index of the new VdbeCursor */
   68099   int nField,           /* Number of fields in the table or index */
   68100   int iDb,              /* Database the cursor belongs to, or -1 */
   68101   int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
   68102 ){
   68103   /* Find the memory cell that will be used to store the blob of memory
   68104   ** required for this VdbeCursor structure. It is convenient to use a
   68105   ** vdbe memory cell to manage the memory allocation required for a
   68106   ** VdbeCursor structure for the following reasons:
   68107   **
   68108   **   * Sometimes cursor numbers are used for a couple of different
   68109   **     purposes in a vdbe program. The different uses might require
   68110   **     different sized allocations. Memory cells provide growable
   68111   **     allocations.
   68112   **
   68113   **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
   68114   **     be freed lazily via the sqlite3_release_memory() API. This
   68115   **     minimizes the number of malloc calls made by the system.
   68116   **
   68117   ** Memory cells for cursors are allocated at the top of the address
   68118   ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
   68119   ** cursor 1 is managed by memory cell (p->nMem-1), etc.
   68120   */
   68121   Mem *pMem = &p->aMem[p->nMem-iCur];
   68122 
   68123   int nByte;
   68124   VdbeCursor *pCx = 0;
   68125   nByte =
   68126       ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
   68127       (isBtreeCursor?sqlite3BtreeCursorSize():0);
   68128 
   68129   assert( iCur<p->nCursor );
   68130   if( p->apCsr[iCur] ){
   68131     sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
   68132     p->apCsr[iCur] = 0;
   68133   }
   68134   if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
   68135     p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
   68136     memset(pCx, 0, sizeof(VdbeCursor));
   68137     pCx->iDb = iDb;
   68138     pCx->nField = nField;
   68139     if( isBtreeCursor ){
   68140       pCx->pCursor = (BtCursor*)
   68141           &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
   68142       sqlite3BtreeCursorZero(pCx->pCursor);
   68143     }
   68144   }
   68145   return pCx;
   68146 }
   68147 
   68148 /*
   68149 ** Try to convert a value into a numeric representation if we can
   68150 ** do so without loss of information.  In other words, if the string
   68151 ** looks like a number, convert it into a number.  If it does not
   68152 ** look like a number, leave it alone.
   68153 */
   68154 static void applyNumericAffinity(Mem *pRec){
   68155   double rValue;
   68156   i64 iValue;
   68157   u8 enc = pRec->enc;
   68158   if( (pRec->flags&MEM_Str)==0 ) return;
   68159   if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
   68160   if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
   68161     pRec->u.i = iValue;
   68162     pRec->flags |= MEM_Int;
   68163   }else{
   68164     pRec->r = rValue;
   68165     pRec->flags |= MEM_Real;
   68166   }
   68167 }
   68168 #define ApplyNumericAffinity(X)  \
   68169    if(((X)->flags&(MEM_Real|MEM_Int))==0){applyNumericAffinity(X);}
   68170 
   68171 /*
   68172 ** Processing is determine by the affinity parameter:
   68173 **
   68174 ** SQLITE_AFF_INTEGER:
   68175 ** SQLITE_AFF_REAL:
   68176 ** SQLITE_AFF_NUMERIC:
   68177 **    Try to convert pRec to an integer representation or a
   68178 **    floating-point representation if an integer representation
   68179 **    is not possible.  Note that the integer representation is
   68180 **    always preferred, even if the affinity is REAL, because
   68181 **    an integer representation is more space efficient on disk.
   68182 **
   68183 ** SQLITE_AFF_TEXT:
   68184 **    Convert pRec to a text representation.
   68185 **
   68186 ** SQLITE_AFF_NONE:
   68187 **    No-op.  pRec is unchanged.
   68188 */
   68189 static void applyAffinity(
   68190   Mem *pRec,          /* The value to apply affinity to */
   68191   char affinity,      /* The affinity to be applied */
   68192   u8 enc              /* Use this text encoding */
   68193 ){
   68194   if( affinity==SQLITE_AFF_TEXT ){
   68195     /* Only attempt the conversion to TEXT if there is an integer or real
   68196     ** representation (blob and NULL do not get converted) but no string
   68197     ** representation.
   68198     */
   68199     if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
   68200       sqlite3VdbeMemStringify(pRec, enc);
   68201     }
   68202     pRec->flags &= ~(MEM_Real|MEM_Int);
   68203   }else if( affinity!=SQLITE_AFF_NONE ){
   68204     assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
   68205              || affinity==SQLITE_AFF_NUMERIC );
   68206     ApplyNumericAffinity(pRec);
   68207     if( pRec->flags & MEM_Real ){
   68208       sqlite3VdbeIntegerAffinity(pRec);
   68209     }
   68210   }
   68211 }
   68212 
   68213 /*
   68214 ** Try to convert the type of a function argument or a result column
   68215 ** into a numeric representation.  Use either INTEGER or REAL whichever
   68216 ** is appropriate.  But only do the conversion if it is possible without
   68217 ** loss of information and return the revised type of the argument.
   68218 */
   68219 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
   68220   int eType = sqlite3_value_type(pVal);
   68221   if( eType==SQLITE_TEXT ){
   68222     Mem *pMem = (Mem*)pVal;
   68223     applyNumericAffinity(pMem);
   68224     eType = sqlite3_value_type(pVal);
   68225   }
   68226   return eType;
   68227 }
   68228 
   68229 /*
   68230 ** Exported version of applyAffinity(). This one works on sqlite3_value*,
   68231 ** not the internal Mem* type.
   68232 */
   68233 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
   68234   sqlite3_value *pVal,
   68235   u8 affinity,
   68236   u8 enc
   68237 ){
   68238   applyAffinity((Mem *)pVal, affinity, enc);
   68239 }
   68240 
   68241 /*
   68242 ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
   68243 ** none.
   68244 **
   68245 ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
   68246 ** But it does set pMem->r and pMem->u.i appropriately.
   68247 */
   68248 static u16 numericType(Mem *pMem){
   68249   if( pMem->flags & (MEM_Int|MEM_Real) ){
   68250     return pMem->flags & (MEM_Int|MEM_Real);
   68251   }
   68252   if( pMem->flags & (MEM_Str|MEM_Blob) ){
   68253     if( sqlite3AtoF(pMem->z, &pMem->r, pMem->n, pMem->enc)==0 ){
   68254       return 0;
   68255     }
   68256     if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==SQLITE_OK ){
   68257       return MEM_Int;
   68258     }
   68259     return MEM_Real;
   68260   }
   68261   return 0;
   68262 }
   68263 
   68264 #ifdef SQLITE_DEBUG
   68265 /*
   68266 ** Write a nice string representation of the contents of cell pMem
   68267 ** into buffer zBuf, length nBuf.
   68268 */
   68269 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
   68270   char *zCsr = zBuf;
   68271   int f = pMem->flags;
   68272 
   68273   static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
   68274 
   68275   if( f&MEM_Blob ){
   68276     int i;
   68277     char c;
   68278     if( f & MEM_Dyn ){
   68279       c = 'z';
   68280       assert( (f & (MEM_Static|MEM_Ephem))==0 );
   68281     }else if( f & MEM_Static ){
   68282       c = 't';
   68283       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
   68284     }else if( f & MEM_Ephem ){
   68285       c = 'e';
   68286       assert( (f & (MEM_Static|MEM_Dyn))==0 );
   68287     }else{
   68288       c = 's';
   68289     }
   68290 
   68291     sqlite3_snprintf(100, zCsr, "%c", c);
   68292     zCsr += sqlite3Strlen30(zCsr);
   68293     sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
   68294     zCsr += sqlite3Strlen30(zCsr);
   68295     for(i=0; i<16 && i<pMem->n; i++){
   68296       sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
   68297       zCsr += sqlite3Strlen30(zCsr);
   68298     }
   68299     for(i=0; i<16 && i<pMem->n; i++){
   68300       char z = pMem->z[i];
   68301       if( z<32 || z>126 ) *zCsr++ = '.';
   68302       else *zCsr++ = z;
   68303     }
   68304 
   68305     sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
   68306     zCsr += sqlite3Strlen30(zCsr);
   68307     if( f & MEM_Zero ){
   68308       sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
   68309       zCsr += sqlite3Strlen30(zCsr);
   68310     }
   68311     *zCsr = '\0';
   68312   }else if( f & MEM_Str ){
   68313     int j, k;
   68314     zBuf[0] = ' ';
   68315     if( f & MEM_Dyn ){
   68316       zBuf[1] = 'z';
   68317       assert( (f & (MEM_Static|MEM_Ephem))==0 );
   68318     }else if( f & MEM_Static ){
   68319       zBuf[1] = 't';
   68320       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
   68321     }else if( f & MEM_Ephem ){
   68322       zBuf[1] = 'e';
   68323       assert( (f & (MEM_Static|MEM_Dyn))==0 );
   68324     }else{
   68325       zBuf[1] = 's';
   68326     }
   68327     k = 2;
   68328     sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
   68329     k += sqlite3Strlen30(&zBuf[k]);
   68330     zBuf[k++] = '[';
   68331     for(j=0; j<15 && j<pMem->n; j++){
   68332       u8 c = pMem->z[j];
   68333       if( c>=0x20 && c<0x7f ){
   68334         zBuf[k++] = c;
   68335       }else{
   68336         zBuf[k++] = '.';
   68337       }
   68338     }
   68339     zBuf[k++] = ']';
   68340     sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
   68341     k += sqlite3Strlen30(&zBuf[k]);
   68342     zBuf[k++] = 0;
   68343   }
   68344 }
   68345 #endif
   68346 
   68347 #ifdef SQLITE_DEBUG
   68348 /*
   68349 ** Print the value of a register for tracing purposes:
   68350 */
   68351 static void memTracePrint(Mem *p){
   68352   if( p->flags & MEM_Undefined ){
   68353     printf(" undefined");
   68354   }else if( p->flags & MEM_Null ){
   68355     printf(" NULL");
   68356   }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
   68357     printf(" si:%lld", p->u.i);
   68358   }else if( p->flags & MEM_Int ){
   68359     printf(" i:%lld", p->u.i);
   68360 #ifndef SQLITE_OMIT_FLOATING_POINT
   68361   }else if( p->flags & MEM_Real ){
   68362     printf(" r:%g", p->r);
   68363 #endif
   68364   }else if( p->flags & MEM_RowSet ){
   68365     printf(" (rowset)");
   68366   }else{
   68367     char zBuf[200];
   68368     sqlite3VdbeMemPrettyPrint(p, zBuf);
   68369     printf(" %s", zBuf);
   68370   }
   68371 }
   68372 static void registerTrace(int iReg, Mem *p){
   68373   printf("REG[%d] = ", iReg);
   68374   memTracePrint(p);
   68375   printf("\n");
   68376 }
   68377 #endif
   68378 
   68379 #ifdef SQLITE_DEBUG
   68380 #  define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
   68381 #else
   68382 #  define REGISTER_TRACE(R,M)
   68383 #endif
   68384 
   68385 
   68386 #ifdef VDBE_PROFILE
   68387 
   68388 /*
   68389 ** hwtime.h contains inline assembler code for implementing
   68390 ** high-performance timing routines.
   68391 */
   68392 /************** Include hwtime.h in the middle of vdbe.c *********************/
   68393 /************** Begin file hwtime.h ******************************************/
   68394 /*
   68395 ** 2008 May 27
   68396 **
   68397 ** The author disclaims copyright to this source code.  In place of
   68398 ** a legal notice, here is a blessing:
   68399 **
   68400 **    May you do good and not evil.
   68401 **    May you find forgiveness for yourself and forgive others.
   68402 **    May you share freely, never taking more than you give.
   68403 **
   68404 ******************************************************************************
   68405 **
   68406 ** This file contains inline asm code for retrieving "high-performance"
   68407 ** counters for x86 class CPUs.
   68408 */
   68409 #ifndef _HWTIME_H_
   68410 #define _HWTIME_H_
   68411 
   68412 /*
   68413 ** The following routine only works on pentium-class (or newer) processors.
   68414 ** It uses the RDTSC opcode to read the cycle count value out of the
   68415 ** processor and returns that value.  This can be used for high-res
   68416 ** profiling.
   68417 */
   68418 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
   68419       (defined(i386) || defined(__i386__) || defined(_M_IX86))
   68420 
   68421   #if defined(__GNUC__)
   68422 
   68423   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   68424      unsigned int lo, hi;
   68425      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
   68426      return (sqlite_uint64)hi << 32 | lo;
   68427   }
   68428 
   68429   #elif defined(_MSC_VER)
   68430 
   68431   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
   68432      __asm {
   68433         rdtsc
   68434         ret       ; return value at EDX:EAX
   68435      }
   68436   }
   68437 
   68438   #endif
   68439 
   68440 #elif (defined(__GNUC__) && defined(__x86_64__))
   68441 
   68442   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   68443       unsigned long val;
   68444       __asm__ __volatile__ ("rdtsc" : "=A" (val));
   68445       return val;
   68446   }
   68447 
   68448 #elif (defined(__GNUC__) && defined(__ppc__))
   68449 
   68450   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   68451       unsigned long long retval;
   68452       unsigned long junk;
   68453       __asm__ __volatile__ ("\n\
   68454           1:      mftbu   %1\n\
   68455                   mftb    %L0\n\
   68456                   mftbu   %0\n\
   68457                   cmpw    %0,%1\n\
   68458                   bne     1b"
   68459                   : "=r" (retval), "=r" (junk));
   68460       return retval;
   68461   }
   68462 
   68463 #else
   68464 
   68465   #error Need implementation of sqlite3Hwtime() for your platform.
   68466 
   68467   /*
   68468   ** To compile without implementing sqlite3Hwtime() for your platform,
   68469   ** you can remove the above #error and use the following
   68470   ** stub function.  You will lose timing support for many
   68471   ** of the debugging and testing utilities, but it should at
   68472   ** least compile and run.
   68473   */
   68474 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
   68475 
   68476 #endif
   68477 
   68478 #endif /* !defined(_HWTIME_H_) */
   68479 
   68480 /************** End of hwtime.h **********************************************/
   68481 /************** Continuing where we left off in vdbe.c ***********************/
   68482 
   68483 #endif
   68484 
   68485 #ifndef NDEBUG
   68486 /*
   68487 ** This function is only called from within an assert() expression. It
   68488 ** checks that the sqlite3.nTransaction variable is correctly set to
   68489 ** the number of non-transaction savepoints currently in the
   68490 ** linked list starting at sqlite3.pSavepoint.
   68491 **
   68492 ** Usage:
   68493 **
   68494 **     assert( checkSavepointCount(db) );
   68495 */
   68496 static int checkSavepointCount(sqlite3 *db){
   68497   int n = 0;
   68498   Savepoint *p;
   68499   for(p=db->pSavepoint; p; p=p->pNext) n++;
   68500   assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
   68501   return 1;
   68502 }
   68503 #endif
   68504 
   68505 
   68506 /*
   68507 ** Execute as much of a VDBE program as we can.
   68508 ** This is the core of sqlite3_step().
   68509 */
   68510 SQLITE_PRIVATE int sqlite3VdbeExec(
   68511   Vdbe *p                    /* The VDBE */
   68512 ){
   68513   int pc=0;                  /* The program counter */
   68514   Op *aOp = p->aOp;          /* Copy of p->aOp */
   68515   Op *pOp;                   /* Current operation */
   68516   int rc = SQLITE_OK;        /* Value to return */
   68517   sqlite3 *db = p->db;       /* The database */
   68518   u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
   68519   u8 encoding = ENC(db);     /* The database encoding */
   68520   int iCompare = 0;          /* Result of last OP_Compare operation */
   68521   unsigned nVmStep = 0;      /* Number of virtual machine steps */
   68522 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   68523   unsigned nProgressLimit = 0;/* Invoke xProgress() when nVmStep reaches this */
   68524 #endif
   68525   Mem *aMem = p->aMem;       /* Copy of p->aMem */
   68526   Mem *pIn1 = 0;             /* 1st input operand */
   68527   Mem *pIn2 = 0;             /* 2nd input operand */
   68528   Mem *pIn3 = 0;             /* 3rd input operand */
   68529   Mem *pOut = 0;             /* Output operand */
   68530   int *aPermute = 0;         /* Permutation of columns for OP_Compare */
   68531   i64 lastRowid = db->lastRowid;  /* Saved value of the last insert ROWID */
   68532 #ifdef VDBE_PROFILE
   68533   u64 start;                 /* CPU clock count at start of opcode */
   68534 #endif
   68535   /*** INSERT STACK UNION HERE ***/
   68536 
   68537   assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
   68538   sqlite3VdbeEnter(p);
   68539   if( p->rc==SQLITE_NOMEM ){
   68540     /* This happens if a malloc() inside a call to sqlite3_column_text() or
   68541     ** sqlite3_column_text16() failed.  */
   68542     goto no_mem;
   68543   }
   68544   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
   68545   assert( p->bIsReader || p->readOnly!=0 );
   68546   p->rc = SQLITE_OK;
   68547   p->iCurrentTime = 0;
   68548   assert( p->explain==0 );
   68549   p->pResultSet = 0;
   68550   db->busyHandler.nBusy = 0;
   68551   if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
   68552   sqlite3VdbeIOTraceSql(p);
   68553 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   68554   if( db->xProgress ){
   68555     assert( 0 < db->nProgressOps );
   68556     nProgressLimit = (unsigned)p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
   68557     if( nProgressLimit==0 ){
   68558       nProgressLimit = db->nProgressOps;
   68559     }else{
   68560       nProgressLimit %= (unsigned)db->nProgressOps;
   68561     }
   68562   }
   68563 #endif
   68564 #ifdef SQLITE_DEBUG
   68565   sqlite3BeginBenignMalloc();
   68566   if( p->pc==0
   68567    && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
   68568   ){
   68569     int i;
   68570     int once = 1;
   68571     sqlite3VdbePrintSql(p);
   68572     if( p->db->flags & SQLITE_VdbeListing ){
   68573       printf("VDBE Program Listing:\n");
   68574       for(i=0; i<p->nOp; i++){
   68575         sqlite3VdbePrintOp(stdout, i, &aOp[i]);
   68576       }
   68577     }
   68578     if( p->db->flags & SQLITE_VdbeEQP ){
   68579       for(i=0; i<p->nOp; i++){
   68580         if( aOp[i].opcode==OP_Explain ){
   68581           if( once ) printf("VDBE Query Plan:\n");
   68582           printf("%s\n", aOp[i].p4.z);
   68583           once = 0;
   68584         }
   68585       }
   68586     }
   68587     if( p->db->flags & SQLITE_VdbeTrace )  printf("VDBE Trace:\n");
   68588   }
   68589   sqlite3EndBenignMalloc();
   68590 #endif
   68591   for(pc=p->pc; rc==SQLITE_OK; pc++){
   68592     assert( pc>=0 && pc<p->nOp );
   68593     if( db->mallocFailed ) goto no_mem;
   68594 #ifdef VDBE_PROFILE
   68595     start = sqlite3Hwtime();
   68596 #endif
   68597     nVmStep++;
   68598     pOp = &aOp[pc];
   68599 
   68600     /* Only allow tracing if SQLITE_DEBUG is defined.
   68601     */
   68602 #ifdef SQLITE_DEBUG
   68603     if( db->flags & SQLITE_VdbeTrace ){
   68604       sqlite3VdbePrintOp(stdout, pc, pOp);
   68605     }
   68606 #endif
   68607 
   68608 
   68609     /* Check to see if we need to simulate an interrupt.  This only happens
   68610     ** if we have a special test build.
   68611     */
   68612 #ifdef SQLITE_TEST
   68613     if( sqlite3_interrupt_count>0 ){
   68614       sqlite3_interrupt_count--;
   68615       if( sqlite3_interrupt_count==0 ){
   68616         sqlite3_interrupt(db);
   68617       }
   68618     }
   68619 #endif
   68620 
   68621     /* On any opcode with the "out2-prerelease" tag, free any
   68622     ** external allocations out of mem[p2] and set mem[p2] to be
   68623     ** an undefined integer.  Opcodes will either fill in the integer
   68624     ** value or convert mem[p2] to a different type.
   68625     */
   68626     assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
   68627     if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
   68628       assert( pOp->p2>0 );
   68629       assert( pOp->p2<=(p->nMem-p->nCursor) );
   68630       pOut = &aMem[pOp->p2];
   68631       memAboutToChange(p, pOut);
   68632       VdbeMemRelease(pOut);
   68633       pOut->flags = MEM_Int;
   68634     }
   68635 
   68636     /* Sanity checking on other operands */
   68637 #ifdef SQLITE_DEBUG
   68638     if( (pOp->opflags & OPFLG_IN1)!=0 ){
   68639       assert( pOp->p1>0 );
   68640       assert( pOp->p1<=(p->nMem-p->nCursor) );
   68641       assert( memIsValid(&aMem[pOp->p1]) );
   68642       assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
   68643       REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
   68644     }
   68645     if( (pOp->opflags & OPFLG_IN2)!=0 ){
   68646       assert( pOp->p2>0 );
   68647       assert( pOp->p2<=(p->nMem-p->nCursor) );
   68648       assert( memIsValid(&aMem[pOp->p2]) );
   68649       assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
   68650       REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
   68651     }
   68652     if( (pOp->opflags & OPFLG_IN3)!=0 ){
   68653       assert( pOp->p3>0 );
   68654       assert( pOp->p3<=(p->nMem-p->nCursor) );
   68655       assert( memIsValid(&aMem[pOp->p3]) );
   68656       assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
   68657       REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
   68658     }
   68659     if( (pOp->opflags & OPFLG_OUT2)!=0 ){
   68660       assert( pOp->p2>0 );
   68661       assert( pOp->p2<=(p->nMem-p->nCursor) );
   68662       memAboutToChange(p, &aMem[pOp->p2]);
   68663     }
   68664     if( (pOp->opflags & OPFLG_OUT3)!=0 ){
   68665       assert( pOp->p3>0 );
   68666       assert( pOp->p3<=(p->nMem-p->nCursor) );
   68667       memAboutToChange(p, &aMem[pOp->p3]);
   68668     }
   68669 #endif
   68670 
   68671     switch( pOp->opcode ){
   68672 
   68673 /*****************************************************************************
   68674 ** What follows is a massive switch statement where each case implements a
   68675 ** separate instruction in the virtual machine.  If we follow the usual
   68676 ** indentation conventions, each case should be indented by 6 spaces.  But
   68677 ** that is a lot of wasted space on the left margin.  So the code within
   68678 ** the switch statement will break with convention and be flush-left. Another
   68679 ** big comment (similar to this one) will mark the point in the code where
   68680 ** we transition back to normal indentation.
   68681 **
   68682 ** The formatting of each case is important.  The makefile for SQLite
   68683 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
   68684 ** file looking for lines that begin with "case OP_".  The opcodes.h files
   68685 ** will be filled with #defines that give unique integer values to each
   68686 ** opcode and the opcodes.c file is filled with an array of strings where
   68687 ** each string is the symbolic name for the corresponding opcode.  If the
   68688 ** case statement is followed by a comment of the form "/# same as ... #/"
   68689 ** that comment is used to determine the particular value of the opcode.
   68690 **
   68691 ** Other keywords in the comment that follows each case are used to
   68692 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
   68693 ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
   68694 ** the mkopcodeh.awk script for additional information.
   68695 **
   68696 ** Documentation about VDBE opcodes is generated by scanning this file
   68697 ** for lines of that contain "Opcode:".  That line and all subsequent
   68698 ** comment lines are used in the generation of the opcode.html documentation
   68699 ** file.
   68700 **
   68701 ** SUMMARY:
   68702 **
   68703 **     Formatting is important to scripts that scan this file.
   68704 **     Do not deviate from the formatting style currently in use.
   68705 **
   68706 *****************************************************************************/
   68707 
   68708 /* Opcode:  Goto * P2 * * *
   68709 **
   68710 ** An unconditional jump to address P2.
   68711 ** The next instruction executed will be
   68712 ** the one at index P2 from the beginning of
   68713 ** the program.
   68714 **
   68715 ** The P1 parameter is not actually used by this opcode.  However, it
   68716 ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
   68717 ** that this Goto is the bottom of a loop and that the lines from P2 down
   68718 ** to the current line should be indented for EXPLAIN output.
   68719 */
   68720 case OP_Goto: {             /* jump */
   68721   pc = pOp->p2 - 1;
   68722 
   68723   /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
   68724   ** OP_VNext, OP_RowSetNext, or OP_SorterNext) all jump here upon
   68725   ** completion.  Check to see if sqlite3_interrupt() has been called
   68726   ** or if the progress callback needs to be invoked.
   68727   **
   68728   ** This code uses unstructured "goto" statements and does not look clean.
   68729   ** But that is not due to sloppy coding habits. The code is written this
   68730   ** way for performance, to avoid having to run the interrupt and progress
   68731   ** checks on every opcode.  This helps sqlite3_step() to run about 1.5%
   68732   ** faster according to "valgrind --tool=cachegrind" */
   68733 check_for_interrupt:
   68734   if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
   68735 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   68736   /* Call the progress callback if it is configured and the required number
   68737   ** of VDBE ops have been executed (either since this invocation of
   68738   ** sqlite3VdbeExec() or since last time the progress callback was called).
   68739   ** If the progress callback returns non-zero, exit the virtual machine with
   68740   ** a return code SQLITE_ABORT.
   68741   */
   68742   if( db->xProgress!=0 && nVmStep>=nProgressLimit ){
   68743     assert( db->nProgressOps!=0 );
   68744     nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
   68745     if( db->xProgress(db->pProgressArg) ){
   68746       rc = SQLITE_INTERRUPT;
   68747       goto vdbe_error_halt;
   68748     }
   68749   }
   68750 #endif
   68751 
   68752   break;
   68753 }
   68754 
   68755 /* Opcode:  Gosub P1 P2 * * *
   68756 **
   68757 ** Write the current address onto register P1
   68758 ** and then jump to address P2.
   68759 */
   68760 case OP_Gosub: {            /* jump */
   68761   assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
   68762   pIn1 = &aMem[pOp->p1];
   68763   assert( VdbeMemDynamic(pIn1)==0 );
   68764   memAboutToChange(p, pIn1);
   68765   pIn1->flags = MEM_Int;
   68766   pIn1->u.i = pc;
   68767   REGISTER_TRACE(pOp->p1, pIn1);
   68768   pc = pOp->p2 - 1;
   68769   break;
   68770 }
   68771 
   68772 /* Opcode:  Return P1 * * * *
   68773 **
   68774 ** Jump to the next instruction after the address in register P1.  After
   68775 ** the jump, register P1 becomes undefined.
   68776 */
   68777 case OP_Return: {           /* in1 */
   68778   pIn1 = &aMem[pOp->p1];
   68779   assert( pIn1->flags==MEM_Int );
   68780   pc = (int)pIn1->u.i;
   68781   pIn1->flags = MEM_Undefined;
   68782   break;
   68783 }
   68784 
   68785 /* Opcode: InitCoroutine P1 P2 P3 * *
   68786 **
   68787 ** Set up register P1 so that it will Yield to the coroutine
   68788 ** located at address P3.
   68789 **
   68790 ** If P2!=0 then the coroutine implementation immediately follows
   68791 ** this opcode.  So jump over the coroutine implementation to
   68792 ** address P2.
   68793 **
   68794 ** See also: EndCoroutine
   68795 */
   68796 case OP_InitCoroutine: {     /* jump */
   68797   assert( pOp->p1>0 &&  pOp->p1<=(p->nMem-p->nCursor) );
   68798   assert( pOp->p2>=0 && pOp->p2<p->nOp );
   68799   assert( pOp->p3>=0 && pOp->p3<p->nOp );
   68800   pOut = &aMem[pOp->p1];
   68801   assert( !VdbeMemDynamic(pOut) );
   68802   pOut->u.i = pOp->p3 - 1;
   68803   pOut->flags = MEM_Int;
   68804   if( pOp->p2 ) pc = pOp->p2 - 1;
   68805   break;
   68806 }
   68807 
   68808 /* Opcode:  EndCoroutine P1 * * * *
   68809 **
   68810 ** The instruction at the address in register P1 is a Yield.
   68811 ** Jump to the P2 parameter of that Yield.
   68812 ** After the jump, register P1 becomes undefined.
   68813 **
   68814 ** See also: InitCoroutine
   68815 */
   68816 case OP_EndCoroutine: {           /* in1 */
   68817   VdbeOp *pCaller;
   68818   pIn1 = &aMem[pOp->p1];
   68819   assert( pIn1->flags==MEM_Int );
   68820   assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
   68821   pCaller = &aOp[pIn1->u.i];
   68822   assert( pCaller->opcode==OP_Yield );
   68823   assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
   68824   pc = pCaller->p2 - 1;
   68825   pIn1->flags = MEM_Undefined;
   68826   break;
   68827 }
   68828 
   68829 /* Opcode:  Yield P1 P2 * * *
   68830 **
   68831 ** Swap the program counter with the value in register P1.  This
   68832 ** has the effect of yielding to a coroutine.
   68833 **
   68834 ** If the coroutine that is launched by this instruction ends with
   68835 ** Yield or Return then continue to the next instruction.  But if
   68836 ** the coroutine launched by this instruction ends with
   68837 ** EndCoroutine, then jump to P2 rather than continuing with the
   68838 ** next instruction.
   68839 **
   68840 ** See also: InitCoroutine
   68841 */
   68842 case OP_Yield: {            /* in1, jump */
   68843   int pcDest;
   68844   pIn1 = &aMem[pOp->p1];
   68845   assert( VdbeMemDynamic(pIn1)==0 );
   68846   pIn1->flags = MEM_Int;
   68847   pcDest = (int)pIn1->u.i;
   68848   pIn1->u.i = pc;
   68849   REGISTER_TRACE(pOp->p1, pIn1);
   68850   pc = pcDest;
   68851   break;
   68852 }
   68853 
   68854 /* Opcode:  HaltIfNull  P1 P2 P3 P4 P5
   68855 ** Synopsis:  if r[P3]=null halt
   68856 **
   68857 ** Check the value in register P3.  If it is NULL then Halt using
   68858 ** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
   68859 ** value in register P3 is not NULL, then this routine is a no-op.
   68860 ** The P5 parameter should be 1.
   68861 */
   68862 case OP_HaltIfNull: {      /* in3 */
   68863   pIn3 = &aMem[pOp->p3];
   68864   if( (pIn3->flags & MEM_Null)==0 ) break;
   68865   /* Fall through into OP_Halt */
   68866 }
   68867 
   68868 /* Opcode:  Halt P1 P2 * P4 P5
   68869 **
   68870 ** Exit immediately.  All open cursors, etc are closed
   68871 ** automatically.
   68872 **
   68873 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
   68874 ** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
   68875 ** For errors, it can be some other value.  If P1!=0 then P2 will determine
   68876 ** whether or not to rollback the current transaction.  Do not rollback
   68877 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
   68878 ** then back out all changes that have occurred during this execution of the
   68879 ** VDBE, but do not rollback the transaction.
   68880 **
   68881 ** If P4 is not null then it is an error message string.
   68882 **
   68883 ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
   68884 **
   68885 **    0:  (no change)
   68886 **    1:  NOT NULL contraint failed: P4
   68887 **    2:  UNIQUE constraint failed: P4
   68888 **    3:  CHECK constraint failed: P4
   68889 **    4:  FOREIGN KEY constraint failed: P4
   68890 **
   68891 ** If P5 is not zero and P4 is NULL, then everything after the ":" is
   68892 ** omitted.
   68893 **
   68894 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
   68895 ** every program.  So a jump past the last instruction of the program
   68896 ** is the same as executing Halt.
   68897 */
   68898 case OP_Halt: {
   68899   const char *zType;
   68900   const char *zLogFmt;
   68901 
   68902   if( pOp->p1==SQLITE_OK && p->pFrame ){
   68903     /* Halt the sub-program. Return control to the parent frame. */
   68904     VdbeFrame *pFrame = p->pFrame;
   68905     p->pFrame = pFrame->pParent;
   68906     p->nFrame--;
   68907     sqlite3VdbeSetChanges(db, p->nChange);
   68908     pc = sqlite3VdbeFrameRestore(pFrame);
   68909     lastRowid = db->lastRowid;
   68910     if( pOp->p2==OE_Ignore ){
   68911       /* Instruction pc is the OP_Program that invoked the sub-program
   68912       ** currently being halted. If the p2 instruction of this OP_Halt
   68913       ** instruction is set to OE_Ignore, then the sub-program is throwing
   68914       ** an IGNORE exception. In this case jump to the address specified
   68915       ** as the p2 of the calling OP_Program.  */
   68916       pc = p->aOp[pc].p2-1;
   68917     }
   68918     aOp = p->aOp;
   68919     aMem = p->aMem;
   68920     break;
   68921   }
   68922   p->rc = pOp->p1;
   68923   p->errorAction = (u8)pOp->p2;
   68924   p->pc = pc;
   68925   if( p->rc ){
   68926     if( pOp->p5 ){
   68927       static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
   68928                                              "FOREIGN KEY" };
   68929       assert( pOp->p5>=1 && pOp->p5<=4 );
   68930       testcase( pOp->p5==1 );
   68931       testcase( pOp->p5==2 );
   68932       testcase( pOp->p5==3 );
   68933       testcase( pOp->p5==4 );
   68934       zType = azType[pOp->p5-1];
   68935     }else{
   68936       zType = 0;
   68937     }
   68938     assert( zType!=0 || pOp->p4.z!=0 );
   68939     zLogFmt = "abort at %d in [%s]: %s";
   68940     if( zType && pOp->p4.z ){
   68941       sqlite3SetString(&p->zErrMsg, db, "%s constraint failed: %s",
   68942                        zType, pOp->p4.z);
   68943     }else if( pOp->p4.z ){
   68944       sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
   68945     }else{
   68946       sqlite3SetString(&p->zErrMsg, db, "%s constraint failed", zType);
   68947     }
   68948     sqlite3_log(pOp->p1, zLogFmt, pc, p->zSql, p->zErrMsg);
   68949   }
   68950   rc = sqlite3VdbeHalt(p);
   68951   assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
   68952   if( rc==SQLITE_BUSY ){
   68953     p->rc = rc = SQLITE_BUSY;
   68954   }else{
   68955     assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
   68956     assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
   68957     rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
   68958   }
   68959   goto vdbe_return;
   68960 }
   68961 
   68962 /* Opcode: Integer P1 P2 * * *
   68963 ** Synopsis: r[P2]=P1
   68964 **
   68965 ** The 32-bit integer value P1 is written into register P2.
   68966 */
   68967 case OP_Integer: {         /* out2-prerelease */
   68968   pOut->u.i = pOp->p1;
   68969   break;
   68970 }
   68971 
   68972 /* Opcode: Int64 * P2 * P4 *
   68973 ** Synopsis: r[P2]=P4
   68974 **
   68975 ** P4 is a pointer to a 64-bit integer value.
   68976 ** Write that value into register P2.
   68977 */
   68978 case OP_Int64: {           /* out2-prerelease */
   68979   assert( pOp->p4.pI64!=0 );
   68980   pOut->u.i = *pOp->p4.pI64;
   68981   break;
   68982 }
   68983 
   68984 #ifndef SQLITE_OMIT_FLOATING_POINT
   68985 /* Opcode: Real * P2 * P4 *
   68986 ** Synopsis: r[P2]=P4
   68987 **
   68988 ** P4 is a pointer to a 64-bit floating point value.
   68989 ** Write that value into register P2.
   68990 */
   68991 case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
   68992   pOut->flags = MEM_Real;
   68993   assert( !sqlite3IsNaN(*pOp->p4.pReal) );
   68994   pOut->r = *pOp->p4.pReal;
   68995   break;
   68996 }
   68997 #endif
   68998 
   68999 /* Opcode: String8 * P2 * P4 *
   69000 ** Synopsis: r[P2]='P4'
   69001 **
   69002 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
   69003 ** into a String before it is executed for the first time.  During
   69004 ** this transformation, the length of string P4 is computed and stored
   69005 ** as the P1 parameter.
   69006 */
   69007 case OP_String8: {         /* same as TK_STRING, out2-prerelease */
   69008   assert( pOp->p4.z!=0 );
   69009   pOp->opcode = OP_String;
   69010   pOp->p1 = sqlite3Strlen30(pOp->p4.z);
   69011 
   69012 #ifndef SQLITE_OMIT_UTF16
   69013   if( encoding!=SQLITE_UTF8 ){
   69014     rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
   69015     if( rc==SQLITE_TOOBIG ) goto too_big;
   69016     if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
   69017     assert( pOut->zMalloc==pOut->z );
   69018     assert( VdbeMemDynamic(pOut)==0 );
   69019     pOut->zMalloc = 0;
   69020     pOut->flags |= MEM_Static;
   69021     if( pOp->p4type==P4_DYNAMIC ){
   69022       sqlite3DbFree(db, pOp->p4.z);
   69023     }
   69024     pOp->p4type = P4_DYNAMIC;
   69025     pOp->p4.z = pOut->z;
   69026     pOp->p1 = pOut->n;
   69027   }
   69028 #endif
   69029   if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   69030     goto too_big;
   69031   }
   69032   /* Fall through to the next case, OP_String */
   69033 }
   69034 
   69035 /* Opcode: String P1 P2 * P4 *
   69036 ** Synopsis: r[P2]='P4' (len=P1)
   69037 **
   69038 ** The string value P4 of length P1 (bytes) is stored in register P2.
   69039 */
   69040 case OP_String: {          /* out2-prerelease */
   69041   assert( pOp->p4.z!=0 );
   69042   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
   69043   pOut->z = pOp->p4.z;
   69044   pOut->n = pOp->p1;
   69045   pOut->enc = encoding;
   69046   UPDATE_MAX_BLOBSIZE(pOut);
   69047   break;
   69048 }
   69049 
   69050 /* Opcode: Null P1 P2 P3 * *
   69051 ** Synopsis:  r[P2..P3]=NULL
   69052 **
   69053 ** Write a NULL into registers P2.  If P3 greater than P2, then also write
   69054 ** NULL into register P3 and every register in between P2 and P3.  If P3
   69055 ** is less than P2 (typically P3 is zero) then only register P2 is
   69056 ** set to NULL.
   69057 **
   69058 ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
   69059 ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
   69060 ** OP_Ne or OP_Eq.
   69061 */
   69062 case OP_Null: {           /* out2-prerelease */
   69063   int cnt;
   69064   u16 nullFlag;
   69065   cnt = pOp->p3-pOp->p2;
   69066   assert( pOp->p3<=(p->nMem-p->nCursor) );
   69067   pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
   69068   while( cnt>0 ){
   69069     pOut++;
   69070     memAboutToChange(p, pOut);
   69071     VdbeMemRelease(pOut);
   69072     pOut->flags = nullFlag;
   69073     cnt--;
   69074   }
   69075   break;
   69076 }
   69077 
   69078 /* Opcode: SoftNull P1 * * * *
   69079 ** Synopsis:  r[P1]=NULL
   69080 **
   69081 ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
   69082 ** instruction, but do not free any string or blob memory associated with
   69083 ** the register, so that if the value was a string or blob that was
   69084 ** previously copied using OP_SCopy, the copies will continue to be valid.
   69085 */
   69086 case OP_SoftNull: {
   69087   assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
   69088   pOut = &aMem[pOp->p1];
   69089   pOut->flags = (pOut->flags|MEM_Null)&~MEM_Undefined;
   69090   break;
   69091 }
   69092 
   69093 /* Opcode: Blob P1 P2 * P4 *
   69094 ** Synopsis: r[P2]=P4 (len=P1)
   69095 **
   69096 ** P4 points to a blob of data P1 bytes long.  Store this
   69097 ** blob in register P2.
   69098 */
   69099 case OP_Blob: {                /* out2-prerelease */
   69100   assert( pOp->p1 <= SQLITE_MAX_LENGTH );
   69101   sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
   69102   pOut->enc = encoding;
   69103   UPDATE_MAX_BLOBSIZE(pOut);
   69104   break;
   69105 }
   69106 
   69107 /* Opcode: Variable P1 P2 * P4 *
   69108 ** Synopsis: r[P2]=parameter(P1,P4)
   69109 **
   69110 ** Transfer the values of bound parameter P1 into register P2
   69111 **
   69112 ** If the parameter is named, then its name appears in P4.
   69113 ** The P4 value is used by sqlite3_bind_parameter_name().
   69114 */
   69115 case OP_Variable: {            /* out2-prerelease */
   69116   Mem *pVar;       /* Value being transferred */
   69117 
   69118   assert( pOp->p1>0 && pOp->p1<=p->nVar );
   69119   assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
   69120   pVar = &p->aVar[pOp->p1 - 1];
   69121   if( sqlite3VdbeMemTooBig(pVar) ){
   69122     goto too_big;
   69123   }
   69124   sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
   69125   UPDATE_MAX_BLOBSIZE(pOut);
   69126   break;
   69127 }
   69128 
   69129 /* Opcode: Move P1 P2 P3 * *
   69130 ** Synopsis:  r[P2@P3]=r[P1@P3]
   69131 **
   69132 ** Move the P3 values in register P1..P1+P3-1 over into
   69133 ** registers P2..P2+P3-1.  Registers P1..P1+P3-1 are
   69134 ** left holding a NULL.  It is an error for register ranges
   69135 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap.  It is an error
   69136 ** for P3 to be less than 1.
   69137 */
   69138 case OP_Move: {
   69139   char *zMalloc;   /* Holding variable for allocated memory */
   69140   int n;           /* Number of registers left to copy */
   69141   int p1;          /* Register to copy from */
   69142   int p2;          /* Register to copy to */
   69143 
   69144   n = pOp->p3;
   69145   p1 = pOp->p1;
   69146   p2 = pOp->p2;
   69147   assert( n>0 && p1>0 && p2>0 );
   69148   assert( p1+n<=p2 || p2+n<=p1 );
   69149 
   69150   pIn1 = &aMem[p1];
   69151   pOut = &aMem[p2];
   69152   do{
   69153     assert( pOut<=&aMem[(p->nMem-p->nCursor)] );
   69154     assert( pIn1<=&aMem[(p->nMem-p->nCursor)] );
   69155     assert( memIsValid(pIn1) );
   69156     memAboutToChange(p, pOut);
   69157     VdbeMemRelease(pOut);
   69158     zMalloc = pOut->zMalloc;
   69159     memcpy(pOut, pIn1, sizeof(Mem));
   69160 #ifdef SQLITE_DEBUG
   69161     if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<&aMem[p1+pOp->p3] ){
   69162       pOut->pScopyFrom += p1 - pOp->p2;
   69163     }
   69164 #endif
   69165     pIn1->flags = MEM_Undefined;
   69166     pIn1->xDel = 0;
   69167     pIn1->zMalloc = zMalloc;
   69168     REGISTER_TRACE(p2++, pOut);
   69169     pIn1++;
   69170     pOut++;
   69171   }while( --n );
   69172   break;
   69173 }
   69174 
   69175 /* Opcode: Copy P1 P2 P3 * *
   69176 ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
   69177 **
   69178 ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
   69179 **
   69180 ** This instruction makes a deep copy of the value.  A duplicate
   69181 ** is made of any string or blob constant.  See also OP_SCopy.
   69182 */
   69183 case OP_Copy: {
   69184   int n;
   69185 
   69186   n = pOp->p3;
   69187   pIn1 = &aMem[pOp->p1];
   69188   pOut = &aMem[pOp->p2];
   69189   assert( pOut!=pIn1 );
   69190   while( 1 ){
   69191     sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
   69192     Deephemeralize(pOut);
   69193 #ifdef SQLITE_DEBUG
   69194     pOut->pScopyFrom = 0;
   69195 #endif
   69196     REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
   69197     if( (n--)==0 ) break;
   69198     pOut++;
   69199     pIn1++;
   69200   }
   69201   break;
   69202 }
   69203 
   69204 /* Opcode: SCopy P1 P2 * * *
   69205 ** Synopsis: r[P2]=r[P1]
   69206 **
   69207 ** Make a shallow copy of register P1 into register P2.
   69208 **
   69209 ** This instruction makes a shallow copy of the value.  If the value
   69210 ** is a string or blob, then the copy is only a pointer to the
   69211 ** original and hence if the original changes so will the copy.
   69212 ** Worse, if the original is deallocated, the copy becomes invalid.
   69213 ** Thus the program must guarantee that the original will not change
   69214 ** during the lifetime of the copy.  Use OP_Copy to make a complete
   69215 ** copy.
   69216 */
   69217 case OP_SCopy: {            /* out2 */
   69218   pIn1 = &aMem[pOp->p1];
   69219   pOut = &aMem[pOp->p2];
   69220   assert( pOut!=pIn1 );
   69221   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
   69222 #ifdef SQLITE_DEBUG
   69223   if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
   69224 #endif
   69225   break;
   69226 }
   69227 
   69228 /* Opcode: ResultRow P1 P2 * * *
   69229 ** Synopsis:  output=r[P1@P2]
   69230 **
   69231 ** The registers P1 through P1+P2-1 contain a single row of
   69232 ** results. This opcode causes the sqlite3_step() call to terminate
   69233 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
   69234 ** structure to provide access to the r(P1)..r(P1+P2-1) values as
   69235 ** the result row.
   69236 */
   69237 case OP_ResultRow: {
   69238   Mem *pMem;
   69239   int i;
   69240   assert( p->nResColumn==pOp->p2 );
   69241   assert( pOp->p1>0 );
   69242   assert( pOp->p1+pOp->p2<=(p->nMem-p->nCursor)+1 );
   69243 
   69244 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   69245   /* Run the progress counter just before returning.
   69246   */
   69247   if( db->xProgress!=0
   69248    && nVmStep>=nProgressLimit
   69249    && db->xProgress(db->pProgressArg)!=0
   69250   ){
   69251     rc = SQLITE_INTERRUPT;
   69252     goto vdbe_error_halt;
   69253   }
   69254 #endif
   69255 
   69256   /* If this statement has violated immediate foreign key constraints, do
   69257   ** not return the number of rows modified. And do not RELEASE the statement
   69258   ** transaction. It needs to be rolled back.  */
   69259   if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
   69260     assert( db->flags&SQLITE_CountRows );
   69261     assert( p->usesStmtJournal );
   69262     break;
   69263   }
   69264 
   69265   /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
   69266   ** DML statements invoke this opcode to return the number of rows
   69267   ** modified to the user. This is the only way that a VM that
   69268   ** opens a statement transaction may invoke this opcode.
   69269   **
   69270   ** In case this is such a statement, close any statement transaction
   69271   ** opened by this VM before returning control to the user. This is to
   69272   ** ensure that statement-transactions are always nested, not overlapping.
   69273   ** If the open statement-transaction is not closed here, then the user
   69274   ** may step another VM that opens its own statement transaction. This
   69275   ** may lead to overlapping statement transactions.
   69276   **
   69277   ** The statement transaction is never a top-level transaction.  Hence
   69278   ** the RELEASE call below can never fail.
   69279   */
   69280   assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
   69281   rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
   69282   if( NEVER(rc!=SQLITE_OK) ){
   69283     break;
   69284   }
   69285 
   69286   /* Invalidate all ephemeral cursor row caches */
   69287   p->cacheCtr = (p->cacheCtr + 2)|1;
   69288 
   69289   /* Make sure the results of the current row are \000 terminated
   69290   ** and have an assigned type.  The results are de-ephemeralized as
   69291   ** a side effect.
   69292   */
   69293   pMem = p->pResultSet = &aMem[pOp->p1];
   69294   for(i=0; i<pOp->p2; i++){
   69295     assert( memIsValid(&pMem[i]) );
   69296     Deephemeralize(&pMem[i]);
   69297     assert( (pMem[i].flags & MEM_Ephem)==0
   69298             || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
   69299     sqlite3VdbeMemNulTerminate(&pMem[i]);
   69300     REGISTER_TRACE(pOp->p1+i, &pMem[i]);
   69301   }
   69302   if( db->mallocFailed ) goto no_mem;
   69303 
   69304   /* Return SQLITE_ROW
   69305   */
   69306   p->pc = pc + 1;
   69307   rc = SQLITE_ROW;
   69308   goto vdbe_return;
   69309 }
   69310 
   69311 /* Opcode: Concat P1 P2 P3 * *
   69312 ** Synopsis: r[P3]=r[P2]+r[P1]
   69313 **
   69314 ** Add the text in register P1 onto the end of the text in
   69315 ** register P2 and store the result in register P3.
   69316 ** If either the P1 or P2 text are NULL then store NULL in P3.
   69317 **
   69318 **   P3 = P2 || P1
   69319 **
   69320 ** It is illegal for P1 and P3 to be the same register. Sometimes,
   69321 ** if P3 is the same register as P2, the implementation is able
   69322 ** to avoid a memcpy().
   69323 */
   69324 case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
   69325   i64 nByte;
   69326 
   69327   pIn1 = &aMem[pOp->p1];
   69328   pIn2 = &aMem[pOp->p2];
   69329   pOut = &aMem[pOp->p3];
   69330   assert( pIn1!=pOut );
   69331   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
   69332     sqlite3VdbeMemSetNull(pOut);
   69333     break;
   69334   }
   69335   if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
   69336   Stringify(pIn1, encoding);
   69337   Stringify(pIn2, encoding);
   69338   nByte = pIn1->n + pIn2->n;
   69339   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   69340     goto too_big;
   69341   }
   69342   if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
   69343     goto no_mem;
   69344   }
   69345   MemSetTypeFlag(pOut, MEM_Str);
   69346   if( pOut!=pIn2 ){
   69347     memcpy(pOut->z, pIn2->z, pIn2->n);
   69348   }
   69349   memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
   69350   pOut->z[nByte]=0;
   69351   pOut->z[nByte+1] = 0;
   69352   pOut->flags |= MEM_Term;
   69353   pOut->n = (int)nByte;
   69354   pOut->enc = encoding;
   69355   UPDATE_MAX_BLOBSIZE(pOut);
   69356   break;
   69357 }
   69358 
   69359 /* Opcode: Add P1 P2 P3 * *
   69360 ** Synopsis:  r[P3]=r[P1]+r[P2]
   69361 **
   69362 ** Add the value in register P1 to the value in register P2
   69363 ** and store the result in register P3.
   69364 ** If either input is NULL, the result is NULL.
   69365 */
   69366 /* Opcode: Multiply P1 P2 P3 * *
   69367 ** Synopsis:  r[P3]=r[P1]*r[P2]
   69368 **
   69369 **
   69370 ** Multiply the value in register P1 by the value in register P2
   69371 ** and store the result in register P3.
   69372 ** If either input is NULL, the result is NULL.
   69373 */
   69374 /* Opcode: Subtract P1 P2 P3 * *
   69375 ** Synopsis:  r[P3]=r[P2]-r[P1]
   69376 **
   69377 ** Subtract the value in register P1 from the value in register P2
   69378 ** and store the result in register P3.
   69379 ** If either input is NULL, the result is NULL.
   69380 */
   69381 /* Opcode: Divide P1 P2 P3 * *
   69382 ** Synopsis:  r[P3]=r[P2]/r[P1]
   69383 **
   69384 ** Divide the value in register P1 by the value in register P2
   69385 ** and store the result in register P3 (P3=P2/P1). If the value in
   69386 ** register P1 is zero, then the result is NULL. If either input is
   69387 ** NULL, the result is NULL.
   69388 */
   69389 /* Opcode: Remainder P1 P2 P3 * *
   69390 ** Synopsis:  r[P3]=r[P2]%r[P1]
   69391 **
   69392 ** Compute the remainder after integer register P2 is divided by
   69393 ** register P1 and store the result in register P3.
   69394 ** If the value in register P1 is zero the result is NULL.
   69395 ** If either operand is NULL, the result is NULL.
   69396 */
   69397 case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
   69398 case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
   69399 case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
   69400 case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
   69401 case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
   69402   char bIntint;   /* Started out as two integer operands */
   69403   u16 flags;      /* Combined MEM_* flags from both inputs */
   69404   u16 type1;      /* Numeric type of left operand */
   69405   u16 type2;      /* Numeric type of right operand */
   69406   i64 iA;         /* Integer value of left operand */
   69407   i64 iB;         /* Integer value of right operand */
   69408   double rA;      /* Real value of left operand */
   69409   double rB;      /* Real value of right operand */
   69410 
   69411   pIn1 = &aMem[pOp->p1];
   69412   type1 = numericType(pIn1);
   69413   pIn2 = &aMem[pOp->p2];
   69414   type2 = numericType(pIn2);
   69415   pOut = &aMem[pOp->p3];
   69416   flags = pIn1->flags | pIn2->flags;
   69417   if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
   69418   if( (type1 & type2 & MEM_Int)!=0 ){
   69419     iA = pIn1->u.i;
   69420     iB = pIn2->u.i;
   69421     bIntint = 1;
   69422     switch( pOp->opcode ){
   69423       case OP_Add:       if( sqlite3AddInt64(&iB,iA) ) goto fp_math;  break;
   69424       case OP_Subtract:  if( sqlite3SubInt64(&iB,iA) ) goto fp_math;  break;
   69425       case OP_Multiply:  if( sqlite3MulInt64(&iB,iA) ) goto fp_math;  break;
   69426       case OP_Divide: {
   69427         if( iA==0 ) goto arithmetic_result_is_null;
   69428         if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
   69429         iB /= iA;
   69430         break;
   69431       }
   69432       default: {
   69433         if( iA==0 ) goto arithmetic_result_is_null;
   69434         if( iA==-1 ) iA = 1;
   69435         iB %= iA;
   69436         break;
   69437       }
   69438     }
   69439     pOut->u.i = iB;
   69440     MemSetTypeFlag(pOut, MEM_Int);
   69441   }else{
   69442     bIntint = 0;
   69443 fp_math:
   69444     rA = sqlite3VdbeRealValue(pIn1);
   69445     rB = sqlite3VdbeRealValue(pIn2);
   69446     switch( pOp->opcode ){
   69447       case OP_Add:         rB += rA;       break;
   69448       case OP_Subtract:    rB -= rA;       break;
   69449       case OP_Multiply:    rB *= rA;       break;
   69450       case OP_Divide: {
   69451         /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
   69452         if( rA==(double)0 ) goto arithmetic_result_is_null;
   69453         rB /= rA;
   69454         break;
   69455       }
   69456       default: {
   69457         iA = (i64)rA;
   69458         iB = (i64)rB;
   69459         if( iA==0 ) goto arithmetic_result_is_null;
   69460         if( iA==-1 ) iA = 1;
   69461         rB = (double)(iB % iA);
   69462         break;
   69463       }
   69464     }
   69465 #ifdef SQLITE_OMIT_FLOATING_POINT
   69466     pOut->u.i = rB;
   69467     MemSetTypeFlag(pOut, MEM_Int);
   69468 #else
   69469     if( sqlite3IsNaN(rB) ){
   69470       goto arithmetic_result_is_null;
   69471     }
   69472     pOut->r = rB;
   69473     MemSetTypeFlag(pOut, MEM_Real);
   69474     if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
   69475       sqlite3VdbeIntegerAffinity(pOut);
   69476     }
   69477 #endif
   69478   }
   69479   break;
   69480 
   69481 arithmetic_result_is_null:
   69482   sqlite3VdbeMemSetNull(pOut);
   69483   break;
   69484 }
   69485 
   69486 /* Opcode: CollSeq P1 * * P4
   69487 **
   69488 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
   69489 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
   69490 ** be returned. This is used by the built-in min(), max() and nullif()
   69491 ** functions.
   69492 **
   69493 ** If P1 is not zero, then it is a register that a subsequent min() or
   69494 ** max() aggregate will set to 1 if the current row is not the minimum or
   69495 ** maximum.  The P1 register is initialized to 0 by this instruction.
   69496 **
   69497 ** The interface used by the implementation of the aforementioned functions
   69498 ** to retrieve the collation sequence set by this opcode is not available
   69499 ** publicly, only to user functions defined in func.c.
   69500 */
   69501 case OP_CollSeq: {
   69502   assert( pOp->p4type==P4_COLLSEQ );
   69503   if( pOp->p1 ){
   69504     sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
   69505   }
   69506   break;
   69507 }
   69508 
   69509 /* Opcode: Function P1 P2 P3 P4 P5
   69510 ** Synopsis: r[P3]=func(r[P2@P5])
   69511 **
   69512 ** Invoke a user function (P4 is a pointer to a Function structure that
   69513 ** defines the function) with P5 arguments taken from register P2 and
   69514 ** successors.  The result of the function is stored in register P3.
   69515 ** Register P3 must not be one of the function inputs.
   69516 **
   69517 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
   69518 ** function was determined to be constant at compile time. If the first
   69519 ** argument was constant then bit 0 of P1 is set. This is used to determine
   69520 ** whether meta data associated with a user function argument using the
   69521 ** sqlite3_set_auxdata() API may be safely retained until the next
   69522 ** invocation of this opcode.
   69523 **
   69524 ** See also: AggStep and AggFinal
   69525 */
   69526 case OP_Function: {
   69527   int i;
   69528   Mem *pArg;
   69529   sqlite3_context ctx;
   69530   sqlite3_value **apVal;
   69531   int n;
   69532 
   69533   n = pOp->p5;
   69534   apVal = p->apArg;
   69535   assert( apVal || n==0 );
   69536   assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
   69537   pOut = &aMem[pOp->p3];
   69538   memAboutToChange(p, pOut);
   69539 
   69540   assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem-p->nCursor)+1) );
   69541   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
   69542   pArg = &aMem[pOp->p2];
   69543   for(i=0; i<n; i++, pArg++){
   69544     assert( memIsValid(pArg) );
   69545     apVal[i] = pArg;
   69546     Deephemeralize(pArg);
   69547     REGISTER_TRACE(pOp->p2+i, pArg);
   69548   }
   69549 
   69550   assert( pOp->p4type==P4_FUNCDEF );
   69551   ctx.pFunc = pOp->p4.pFunc;
   69552   ctx.iOp = pc;
   69553   ctx.pVdbe = p;
   69554 
   69555   /* The output cell may already have a buffer allocated. Move
   69556   ** the pointer to ctx.s so in case the user-function can use
   69557   ** the already allocated buffer instead of allocating a new one.
   69558   */
   69559   memcpy(&ctx.s, pOut, sizeof(Mem));
   69560   pOut->flags = MEM_Null;
   69561   pOut->xDel = 0;
   69562   pOut->zMalloc = 0;
   69563   MemSetTypeFlag(&ctx.s, MEM_Null);
   69564 
   69565   ctx.fErrorOrAux = 0;
   69566   if( ctx.pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
   69567     assert( pOp>aOp );
   69568     assert( pOp[-1].p4type==P4_COLLSEQ );
   69569     assert( pOp[-1].opcode==OP_CollSeq );
   69570     ctx.pColl = pOp[-1].p4.pColl;
   69571   }
   69572   db->lastRowid = lastRowid;
   69573   (*ctx.pFunc->xFunc)(&ctx, n, apVal); /* IMP: R-24505-23230 */
   69574   lastRowid = db->lastRowid;
   69575 
   69576   if( db->mallocFailed ){
   69577     /* Even though a malloc() has failed, the implementation of the
   69578     ** user function may have called an sqlite3_result_XXX() function
   69579     ** to return a value. The following call releases any resources
   69580     ** associated with such a value.
   69581     */
   69582     sqlite3VdbeMemRelease(&ctx.s);
   69583     goto no_mem;
   69584   }
   69585 
   69586   /* If the function returned an error, throw an exception */
   69587   if( ctx.fErrorOrAux ){
   69588     if( ctx.isError ){
   69589       sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&ctx.s));
   69590       rc = ctx.isError;
   69591     }
   69592     sqlite3VdbeDeleteAuxData(p, pc, pOp->p1);
   69593   }
   69594 
   69595   /* Copy the result of the function into register P3 */
   69596   sqlite3VdbeChangeEncoding(&ctx.s, encoding);
   69597   assert( pOut->flags==MEM_Null );
   69598   memcpy(pOut, &ctx.s, sizeof(Mem));
   69599   if( sqlite3VdbeMemTooBig(pOut) ){
   69600     goto too_big;
   69601   }
   69602 
   69603 #if 0
   69604   /* The app-defined function has done something that as caused this
   69605   ** statement to expire.  (Perhaps the function called sqlite3_exec()
   69606   ** with a CREATE TABLE statement.)
   69607   */
   69608   if( p->expired ) rc = SQLITE_ABORT;
   69609 #endif
   69610 
   69611   REGISTER_TRACE(pOp->p3, pOut);
   69612   UPDATE_MAX_BLOBSIZE(pOut);
   69613   break;
   69614 }
   69615 
   69616 /* Opcode: BitAnd P1 P2 P3 * *
   69617 ** Synopsis:  r[P3]=r[P1]&r[P2]
   69618 **
   69619 ** Take the bit-wise AND of the values in register P1 and P2 and
   69620 ** store the result in register P3.
   69621 ** If either input is NULL, the result is NULL.
   69622 */
   69623 /* Opcode: BitOr P1 P2 P3 * *
   69624 ** Synopsis:  r[P3]=r[P1]|r[P2]
   69625 **
   69626 ** Take the bit-wise OR of the values in register P1 and P2 and
   69627 ** store the result in register P3.
   69628 ** If either input is NULL, the result is NULL.
   69629 */
   69630 /* Opcode: ShiftLeft P1 P2 P3 * *
   69631 ** Synopsis:  r[P3]=r[P2]<<r[P1]
   69632 **
   69633 ** Shift the integer value in register P2 to the left by the
   69634 ** number of bits specified by the integer in register P1.
   69635 ** Store the result in register P3.
   69636 ** If either input is NULL, the result is NULL.
   69637 */
   69638 /* Opcode: ShiftRight P1 P2 P3 * *
   69639 ** Synopsis:  r[P3]=r[P2]>>r[P1]
   69640 **
   69641 ** Shift the integer value in register P2 to the right by the
   69642 ** number of bits specified by the integer in register P1.
   69643 ** Store the result in register P3.
   69644 ** If either input is NULL, the result is NULL.
   69645 */
   69646 case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
   69647 case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
   69648 case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
   69649 case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
   69650   i64 iA;
   69651   u64 uA;
   69652   i64 iB;
   69653   u8 op;
   69654 
   69655   pIn1 = &aMem[pOp->p1];
   69656   pIn2 = &aMem[pOp->p2];
   69657   pOut = &aMem[pOp->p3];
   69658   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
   69659     sqlite3VdbeMemSetNull(pOut);
   69660     break;
   69661   }
   69662   iA = sqlite3VdbeIntValue(pIn2);
   69663   iB = sqlite3VdbeIntValue(pIn1);
   69664   op = pOp->opcode;
   69665   if( op==OP_BitAnd ){
   69666     iA &= iB;
   69667   }else if( op==OP_BitOr ){
   69668     iA |= iB;
   69669   }else if( iB!=0 ){
   69670     assert( op==OP_ShiftRight || op==OP_ShiftLeft );
   69671 
   69672     /* If shifting by a negative amount, shift in the other direction */
   69673     if( iB<0 ){
   69674       assert( OP_ShiftRight==OP_ShiftLeft+1 );
   69675       op = 2*OP_ShiftLeft + 1 - op;
   69676       iB = iB>(-64) ? -iB : 64;
   69677     }
   69678 
   69679     if( iB>=64 ){
   69680       iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
   69681     }else{
   69682       memcpy(&uA, &iA, sizeof(uA));
   69683       if( op==OP_ShiftLeft ){
   69684         uA <<= iB;
   69685       }else{
   69686         uA >>= iB;
   69687         /* Sign-extend on a right shift of a negative number */
   69688         if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
   69689       }
   69690       memcpy(&iA, &uA, sizeof(iA));
   69691     }
   69692   }
   69693   pOut->u.i = iA;
   69694   MemSetTypeFlag(pOut, MEM_Int);
   69695   break;
   69696 }
   69697 
   69698 /* Opcode: AddImm  P1 P2 * * *
   69699 ** Synopsis:  r[P1]=r[P1]+P2
   69700 **
   69701 ** Add the constant P2 to the value in register P1.
   69702 ** The result is always an integer.
   69703 **
   69704 ** To force any register to be an integer, just add 0.
   69705 */
   69706 case OP_AddImm: {            /* in1 */
   69707   pIn1 = &aMem[pOp->p1];
   69708   memAboutToChange(p, pIn1);
   69709   sqlite3VdbeMemIntegerify(pIn1);
   69710   pIn1->u.i += pOp->p2;
   69711   break;
   69712 }
   69713 
   69714 /* Opcode: MustBeInt P1 P2 * * *
   69715 **
   69716 ** Force the value in register P1 to be an integer.  If the value
   69717 ** in P1 is not an integer and cannot be converted into an integer
   69718 ** without data loss, then jump immediately to P2, or if P2==0
   69719 ** raise an SQLITE_MISMATCH exception.
   69720 */
   69721 case OP_MustBeInt: {            /* jump, in1 */
   69722   pIn1 = &aMem[pOp->p1];
   69723   if( (pIn1->flags & MEM_Int)==0 ){
   69724     applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
   69725     VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
   69726     if( (pIn1->flags & MEM_Int)==0 ){
   69727       if( pOp->p2==0 ){
   69728         rc = SQLITE_MISMATCH;
   69729         goto abort_due_to_error;
   69730       }else{
   69731         pc = pOp->p2 - 1;
   69732         break;
   69733       }
   69734     }
   69735   }
   69736   MemSetTypeFlag(pIn1, MEM_Int);
   69737   break;
   69738 }
   69739 
   69740 #ifndef SQLITE_OMIT_FLOATING_POINT
   69741 /* Opcode: RealAffinity P1 * * * *
   69742 **
   69743 ** If register P1 holds an integer convert it to a real value.
   69744 **
   69745 ** This opcode is used when extracting information from a column that
   69746 ** has REAL affinity.  Such column values may still be stored as
   69747 ** integers, for space efficiency, but after extraction we want them
   69748 ** to have only a real value.
   69749 */
   69750 case OP_RealAffinity: {                  /* in1 */
   69751   pIn1 = &aMem[pOp->p1];
   69752   if( pIn1->flags & MEM_Int ){
   69753     sqlite3VdbeMemRealify(pIn1);
   69754   }
   69755   break;
   69756 }
   69757 #endif
   69758 
   69759 #ifndef SQLITE_OMIT_CAST
   69760 /* Opcode: ToText P1 * * * *
   69761 **
   69762 ** Force the value in register P1 to be text.
   69763 ** If the value is numeric, convert it to a string using the
   69764 ** equivalent of sprintf().  Blob values are unchanged and
   69765 ** are afterwards simply interpreted as text.
   69766 **
   69767 ** A NULL value is not changed by this routine.  It remains NULL.
   69768 */
   69769 case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
   69770   pIn1 = &aMem[pOp->p1];
   69771   memAboutToChange(p, pIn1);
   69772   if( pIn1->flags & MEM_Null ) break;
   69773   assert( MEM_Str==(MEM_Blob>>3) );
   69774   pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
   69775   applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
   69776   rc = ExpandBlob(pIn1);
   69777   assert( pIn1->flags & MEM_Str || db->mallocFailed );
   69778   pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
   69779   UPDATE_MAX_BLOBSIZE(pIn1);
   69780   break;
   69781 }
   69782 
   69783 /* Opcode: ToBlob P1 * * * *
   69784 **
   69785 ** Force the value in register P1 to be a BLOB.
   69786 ** If the value is numeric, convert it to a string first.
   69787 ** Strings are simply reinterpreted as blobs with no change
   69788 ** to the underlying data.
   69789 **
   69790 ** A NULL value is not changed by this routine.  It remains NULL.
   69791 */
   69792 case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
   69793   pIn1 = &aMem[pOp->p1];
   69794   if( pIn1->flags & MEM_Null ) break;
   69795   if( (pIn1->flags & MEM_Blob)==0 ){
   69796     applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
   69797     assert( pIn1->flags & MEM_Str || db->mallocFailed );
   69798     MemSetTypeFlag(pIn1, MEM_Blob);
   69799   }else{
   69800     pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
   69801   }
   69802   UPDATE_MAX_BLOBSIZE(pIn1);
   69803   break;
   69804 }
   69805 
   69806 /* Opcode: ToNumeric P1 * * * *
   69807 **
   69808 ** Force the value in register P1 to be numeric (either an
   69809 ** integer or a floating-point number.)
   69810 ** If the value is text or blob, try to convert it to an using the
   69811 ** equivalent of atoi() or atof() and store 0 if no such conversion
   69812 ** is possible.
   69813 **
   69814 ** A NULL value is not changed by this routine.  It remains NULL.
   69815 */
   69816 case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
   69817   pIn1 = &aMem[pOp->p1];
   69818   sqlite3VdbeMemNumerify(pIn1);
   69819   break;
   69820 }
   69821 #endif /* SQLITE_OMIT_CAST */
   69822 
   69823 /* Opcode: ToInt P1 * * * *
   69824 **
   69825 ** Force the value in register P1 to be an integer.  If
   69826 ** The value is currently a real number, drop its fractional part.
   69827 ** If the value is text or blob, try to convert it to an integer using the
   69828 ** equivalent of atoi() and store 0 if no such conversion is possible.
   69829 **
   69830 ** A NULL value is not changed by this routine.  It remains NULL.
   69831 */
   69832 case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
   69833   pIn1 = &aMem[pOp->p1];
   69834   if( (pIn1->flags & MEM_Null)==0 ){
   69835     sqlite3VdbeMemIntegerify(pIn1);
   69836   }
   69837   break;
   69838 }
   69839 
   69840 #if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
   69841 /* Opcode: ToReal P1 * * * *
   69842 **
   69843 ** Force the value in register P1 to be a floating point number.
   69844 ** If The value is currently an integer, convert it.
   69845 ** If the value is text or blob, try to convert it to an integer using the
   69846 ** equivalent of atoi() and store 0.0 if no such conversion is possible.
   69847 **
   69848 ** A NULL value is not changed by this routine.  It remains NULL.
   69849 */
   69850 case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
   69851   pIn1 = &aMem[pOp->p1];
   69852   memAboutToChange(p, pIn1);
   69853   if( (pIn1->flags & MEM_Null)==0 ){
   69854     sqlite3VdbeMemRealify(pIn1);
   69855   }
   69856   break;
   69857 }
   69858 #endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
   69859 
   69860 /* Opcode: Lt P1 P2 P3 P4 P5
   69861 ** Synopsis: if r[P1]<r[P3] goto P2
   69862 **
   69863 ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
   69864 ** jump to address P2.
   69865 **
   69866 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
   69867 ** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL
   69868 ** bit is clear then fall through if either operand is NULL.
   69869 **
   69870 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
   69871 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
   69872 ** to coerce both inputs according to this affinity before the
   69873 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
   69874 ** affinity is used. Note that the affinity conversions are stored
   69875 ** back into the input registers P1 and P3.  So this opcode can cause
   69876 ** persistent changes to registers P1 and P3.
   69877 **
   69878 ** Once any conversions have taken place, and neither value is NULL,
   69879 ** the values are compared. If both values are blobs then memcmp() is
   69880 ** used to determine the results of the comparison.  If both values
   69881 ** are text, then the appropriate collating function specified in
   69882 ** P4 is  used to do the comparison.  If P4 is not specified then
   69883 ** memcmp() is used to compare text string.  If both values are
   69884 ** numeric, then a numeric comparison is used. If the two values
   69885 ** are of different types, then numbers are considered less than
   69886 ** strings and strings are considered less than blobs.
   69887 **
   69888 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
   69889 ** store a boolean result (either 0, or 1, or NULL) in register P2.
   69890 **
   69891 ** If the SQLITE_NULLEQ bit is set in P5, then NULL values are considered
   69892 ** equal to one another, provided that they do not have their MEM_Cleared
   69893 ** bit set.
   69894 */
   69895 /* Opcode: Ne P1 P2 P3 P4 P5
   69896 ** Synopsis: if r[P1]!=r[P3] goto P2
   69897 **
   69898 ** This works just like the Lt opcode except that the jump is taken if
   69899 ** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
   69900 ** additional information.
   69901 **
   69902 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
   69903 ** true or false and is never NULL.  If both operands are NULL then the result
   69904 ** of comparison is false.  If either operand is NULL then the result is true.
   69905 ** If neither operand is NULL the result is the same as it would be if
   69906 ** the SQLITE_NULLEQ flag were omitted from P5.
   69907 */
   69908 /* Opcode: Eq 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 operands in registers P1 and P3 are equal.
   69913 ** See the Lt opcode for additional information.
   69914 **
   69915 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
   69916 ** true or false and is never NULL.  If both operands are NULL then the result
   69917 ** of comparison is true.  If either operand is NULL then the result is false.
   69918 ** If neither operand is NULL the result is the same as it would be if
   69919 ** the SQLITE_NULLEQ flag were omitted from P5.
   69920 */
   69921 /* Opcode: Le P1 P2 P3 P4 P5
   69922 ** Synopsis: if r[P1]<=r[P3] goto P2
   69923 **
   69924 ** This works just like the Lt opcode except that the jump is taken if
   69925 ** the content of register P3 is less than or equal to the content of
   69926 ** register P1.  See the Lt opcode for additional information.
   69927 */
   69928 /* Opcode: Gt P1 P2 P3 P4 P5
   69929 ** Synopsis: if r[P1]>r[P3] goto P2
   69930 **
   69931 ** This works just like the Lt opcode except that the jump is taken if
   69932 ** the content of register P3 is greater than the content of
   69933 ** register P1.  See the Lt opcode for additional information.
   69934 */
   69935 /* Opcode: Ge P1 P2 P3 P4 P5
   69936 ** Synopsis: if r[P1]>=r[P3] goto P2
   69937 **
   69938 ** This works just like the Lt opcode except that the jump is taken if
   69939 ** the content of register P3 is greater than or equal to the content of
   69940 ** register P1.  See the Lt opcode for additional information.
   69941 */
   69942 case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
   69943 case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
   69944 case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
   69945 case OP_Le:               /* same as TK_LE, jump, in1, in3 */
   69946 case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
   69947 case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
   69948   int res;            /* Result of the comparison of pIn1 against pIn3 */
   69949   char affinity;      /* Affinity to use for comparison */
   69950   u16 flags1;         /* Copy of initial value of pIn1->flags */
   69951   u16 flags3;         /* Copy of initial value of pIn3->flags */
   69952 
   69953   pIn1 = &aMem[pOp->p1];
   69954   pIn3 = &aMem[pOp->p3];
   69955   flags1 = pIn1->flags;
   69956   flags3 = pIn3->flags;
   69957   if( (flags1 | flags3)&MEM_Null ){
   69958     /* One or both operands are NULL */
   69959     if( pOp->p5 & SQLITE_NULLEQ ){
   69960       /* If SQLITE_NULLEQ is set (which will only happen if the operator is
   69961       ** OP_Eq or OP_Ne) then take the jump or not depending on whether
   69962       ** or not both operands are null.
   69963       */
   69964       assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
   69965       assert( (flags1 & MEM_Cleared)==0 );
   69966       assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
   69967       if( (flags1&MEM_Null)!=0
   69968        && (flags3&MEM_Null)!=0
   69969        && (flags3&MEM_Cleared)==0
   69970       ){
   69971         res = 0;  /* Results are equal */
   69972       }else{
   69973         res = 1;  /* Results are not equal */
   69974       }
   69975     }else{
   69976       /* SQLITE_NULLEQ is clear and at least one operand is NULL,
   69977       ** then the result is always NULL.
   69978       ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
   69979       */
   69980       if( pOp->p5 & SQLITE_STOREP2 ){
   69981         pOut = &aMem[pOp->p2];
   69982         MemSetTypeFlag(pOut, MEM_Null);
   69983         REGISTER_TRACE(pOp->p2, pOut);
   69984       }else{
   69985         VdbeBranchTaken(2,3);
   69986         if( pOp->p5 & SQLITE_JUMPIFNULL ){
   69987           pc = pOp->p2-1;
   69988         }
   69989       }
   69990       break;
   69991     }
   69992   }else{
   69993     /* Neither operand is NULL.  Do a comparison. */
   69994     affinity = pOp->p5 & SQLITE_AFF_MASK;
   69995     if( affinity ){
   69996       applyAffinity(pIn1, affinity, encoding);
   69997       applyAffinity(pIn3, affinity, encoding);
   69998       if( db->mallocFailed ) goto no_mem;
   69999     }
   70000 
   70001     assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
   70002     ExpandBlob(pIn1);
   70003     ExpandBlob(pIn3);
   70004     res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
   70005   }
   70006   switch( pOp->opcode ){
   70007     case OP_Eq:    res = res==0;     break;
   70008     case OP_Ne:    res = res!=0;     break;
   70009     case OP_Lt:    res = res<0;      break;
   70010     case OP_Le:    res = res<=0;     break;
   70011     case OP_Gt:    res = res>0;      break;
   70012     default:       res = res>=0;     break;
   70013   }
   70014 
   70015   if( pOp->p5 & SQLITE_STOREP2 ){
   70016     pOut = &aMem[pOp->p2];
   70017     memAboutToChange(p, pOut);
   70018     MemSetTypeFlag(pOut, MEM_Int);
   70019     pOut->u.i = res;
   70020     REGISTER_TRACE(pOp->p2, pOut);
   70021   }else{
   70022     VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
   70023     if( res ){
   70024       pc = pOp->p2-1;
   70025     }
   70026   }
   70027   /* Undo any changes made by applyAffinity() to the input registers. */
   70028   pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (flags1&MEM_TypeMask);
   70029   pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (flags3&MEM_TypeMask);
   70030   break;
   70031 }
   70032 
   70033 /* Opcode: Permutation * * * P4 *
   70034 **
   70035 ** Set the permutation used by the OP_Compare operator to be the array
   70036 ** of integers in P4.
   70037 **
   70038 ** The permutation is only valid until the next OP_Compare that has
   70039 ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
   70040 ** occur immediately prior to the OP_Compare.
   70041 */
   70042 case OP_Permutation: {
   70043   assert( pOp->p4type==P4_INTARRAY );
   70044   assert( pOp->p4.ai );
   70045   aPermute = pOp->p4.ai;
   70046   break;
   70047 }
   70048 
   70049 /* Opcode: Compare P1 P2 P3 P4 P5
   70050 ** Synopsis: r[P1@P3] <-> r[P2@P3]
   70051 **
   70052 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
   70053 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
   70054 ** the comparison for use by the next OP_Jump instruct.
   70055 **
   70056 ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
   70057 ** determined by the most recent OP_Permutation operator.  If the
   70058 ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
   70059 ** order.
   70060 **
   70061 ** P4 is a KeyInfo structure that defines collating sequences and sort
   70062 ** orders for the comparison.  The permutation applies to registers
   70063 ** only.  The KeyInfo elements are used sequentially.
   70064 **
   70065 ** The comparison is a sort comparison, so NULLs compare equal,
   70066 ** NULLs are less than numbers, numbers are less than strings,
   70067 ** and strings are less than blobs.
   70068 */
   70069 case OP_Compare: {
   70070   int n;
   70071   int i;
   70072   int p1;
   70073   int p2;
   70074   const KeyInfo *pKeyInfo;
   70075   int idx;
   70076   CollSeq *pColl;    /* Collating sequence to use on this term */
   70077   int bRev;          /* True for DESCENDING sort order */
   70078 
   70079   if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0;
   70080   n = pOp->p3;
   70081   pKeyInfo = pOp->p4.pKeyInfo;
   70082   assert( n>0 );
   70083   assert( pKeyInfo!=0 );
   70084   p1 = pOp->p1;
   70085   p2 = pOp->p2;
   70086 #if SQLITE_DEBUG
   70087   if( aPermute ){
   70088     int k, mx = 0;
   70089     for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
   70090     assert( p1>0 && p1+mx<=(p->nMem-p->nCursor)+1 );
   70091     assert( p2>0 && p2+mx<=(p->nMem-p->nCursor)+1 );
   70092   }else{
   70093     assert( p1>0 && p1+n<=(p->nMem-p->nCursor)+1 );
   70094     assert( p2>0 && p2+n<=(p->nMem-p->nCursor)+1 );
   70095   }
   70096 #endif /* SQLITE_DEBUG */
   70097   for(i=0; i<n; i++){
   70098     idx = aPermute ? aPermute[i] : i;
   70099     assert( memIsValid(&aMem[p1+idx]) );
   70100     assert( memIsValid(&aMem[p2+idx]) );
   70101     REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
   70102     REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
   70103     assert( i<pKeyInfo->nField );
   70104     pColl = pKeyInfo->aColl[i];
   70105     bRev = pKeyInfo->aSortOrder[i];
   70106     iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
   70107     if( iCompare ){
   70108       if( bRev ) iCompare = -iCompare;
   70109       break;
   70110     }
   70111   }
   70112   aPermute = 0;
   70113   break;
   70114 }
   70115 
   70116 /* Opcode: Jump P1 P2 P3 * *
   70117 **
   70118 ** Jump to the instruction at address P1, P2, or P3 depending on whether
   70119 ** in the most recent OP_Compare instruction the P1 vector was less than
   70120 ** equal to, or greater than the P2 vector, respectively.
   70121 */
   70122 case OP_Jump: {             /* jump */
   70123   if( iCompare<0 ){
   70124     pc = pOp->p1 - 1;  VdbeBranchTaken(0,3);
   70125   }else if( iCompare==0 ){
   70126     pc = pOp->p2 - 1;  VdbeBranchTaken(1,3);
   70127   }else{
   70128     pc = pOp->p3 - 1;  VdbeBranchTaken(2,3);
   70129   }
   70130   break;
   70131 }
   70132 
   70133 /* Opcode: And P1 P2 P3 * *
   70134 ** Synopsis: r[P3]=(r[P1] && r[P2])
   70135 **
   70136 ** Take the logical AND of the values in registers P1 and P2 and
   70137 ** write the result into register P3.
   70138 **
   70139 ** If either P1 or P2 is 0 (false) then the result is 0 even if
   70140 ** the other input is NULL.  A NULL and true or two NULLs give
   70141 ** a NULL output.
   70142 */
   70143 /* Opcode: Or P1 P2 P3 * *
   70144 ** Synopsis: r[P3]=(r[P1] || r[P2])
   70145 **
   70146 ** Take the logical OR of the values in register P1 and P2 and
   70147 ** store the answer in register P3.
   70148 **
   70149 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
   70150 ** even if the other input is NULL.  A NULL and false or two NULLs
   70151 ** give a NULL output.
   70152 */
   70153 case OP_And:              /* same as TK_AND, in1, in2, out3 */
   70154 case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
   70155   int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
   70156   int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
   70157 
   70158   pIn1 = &aMem[pOp->p1];
   70159   if( pIn1->flags & MEM_Null ){
   70160     v1 = 2;
   70161   }else{
   70162     v1 = sqlite3VdbeIntValue(pIn1)!=0;
   70163   }
   70164   pIn2 = &aMem[pOp->p2];
   70165   if( pIn2->flags & MEM_Null ){
   70166     v2 = 2;
   70167   }else{
   70168     v2 = sqlite3VdbeIntValue(pIn2)!=0;
   70169   }
   70170   if( pOp->opcode==OP_And ){
   70171     static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
   70172     v1 = and_logic[v1*3+v2];
   70173   }else{
   70174     static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
   70175     v1 = or_logic[v1*3+v2];
   70176   }
   70177   pOut = &aMem[pOp->p3];
   70178   if( v1==2 ){
   70179     MemSetTypeFlag(pOut, MEM_Null);
   70180   }else{
   70181     pOut->u.i = v1;
   70182     MemSetTypeFlag(pOut, MEM_Int);
   70183   }
   70184   break;
   70185 }
   70186 
   70187 /* Opcode: Not P1 P2 * * *
   70188 ** Synopsis: r[P2]= !r[P1]
   70189 **
   70190 ** Interpret the value in register P1 as a boolean value.  Store the
   70191 ** boolean complement in register P2.  If the value in register P1 is
   70192 ** NULL, then a NULL is stored in P2.
   70193 */
   70194 case OP_Not: {                /* same as TK_NOT, in1, out2 */
   70195   pIn1 = &aMem[pOp->p1];
   70196   pOut = &aMem[pOp->p2];
   70197   if( pIn1->flags & MEM_Null ){
   70198     sqlite3VdbeMemSetNull(pOut);
   70199   }else{
   70200     sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
   70201   }
   70202   break;
   70203 }
   70204 
   70205 /* Opcode: BitNot P1 P2 * * *
   70206 ** Synopsis: r[P1]= ~r[P1]
   70207 **
   70208 ** Interpret the content of register P1 as an integer.  Store the
   70209 ** ones-complement of the P1 value into register P2.  If P1 holds
   70210 ** a NULL then store a NULL in P2.
   70211 */
   70212 case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
   70213   pIn1 = &aMem[pOp->p1];
   70214   pOut = &aMem[pOp->p2];
   70215   if( pIn1->flags & MEM_Null ){
   70216     sqlite3VdbeMemSetNull(pOut);
   70217   }else{
   70218     sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
   70219   }
   70220   break;
   70221 }
   70222 
   70223 /* Opcode: Once P1 P2 * * *
   70224 **
   70225 ** Check the "once" flag number P1. If it is set, jump to instruction P2.
   70226 ** Otherwise, set the flag and fall through to the next instruction.
   70227 ** In other words, this opcode causes all following opcodes up through P2
   70228 ** (but not including P2) to run just once and to be skipped on subsequent
   70229 ** times through the loop.
   70230 **
   70231 ** All "once" flags are initially cleared whenever a prepared statement
   70232 ** first begins to run.
   70233 */
   70234 case OP_Once: {             /* jump */
   70235   assert( pOp->p1<p->nOnceFlag );
   70236   VdbeBranchTaken(p->aOnceFlag[pOp->p1]!=0, 2);
   70237   if( p->aOnceFlag[pOp->p1] ){
   70238     pc = pOp->p2-1;
   70239   }else{
   70240     p->aOnceFlag[pOp->p1] = 1;
   70241   }
   70242   break;
   70243 }
   70244 
   70245 /* Opcode: If P1 P2 P3 * *
   70246 **
   70247 ** Jump to P2 if the value in register P1 is true.  The value
   70248 ** is considered true if it is numeric and non-zero.  If the value
   70249 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
   70250 */
   70251 /* Opcode: IfNot P1 P2 P3 * *
   70252 **
   70253 ** Jump to P2 if the value in register P1 is False.  The value
   70254 ** is considered false if it has a numeric value of zero.  If the value
   70255 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
   70256 */
   70257 case OP_If:                 /* jump, in1 */
   70258 case OP_IfNot: {            /* jump, in1 */
   70259   int c;
   70260   pIn1 = &aMem[pOp->p1];
   70261   if( pIn1->flags & MEM_Null ){
   70262     c = pOp->p3;
   70263   }else{
   70264 #ifdef SQLITE_OMIT_FLOATING_POINT
   70265     c = sqlite3VdbeIntValue(pIn1)!=0;
   70266 #else
   70267     c = sqlite3VdbeRealValue(pIn1)!=0.0;
   70268 #endif
   70269     if( pOp->opcode==OP_IfNot ) c = !c;
   70270   }
   70271   VdbeBranchTaken(c!=0, 2);
   70272   if( c ){
   70273     pc = pOp->p2-1;
   70274   }
   70275   break;
   70276 }
   70277 
   70278 /* Opcode: IsNull P1 P2 * * *
   70279 ** Synopsis:  if r[P1]==NULL goto P2
   70280 **
   70281 ** Jump to P2 if the value in register P1 is NULL.
   70282 */
   70283 case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
   70284   pIn1 = &aMem[pOp->p1];
   70285   VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
   70286   if( (pIn1->flags & MEM_Null)!=0 ){
   70287     pc = pOp->p2 - 1;
   70288   }
   70289   break;
   70290 }
   70291 
   70292 /* Opcode: NotNull P1 P2 * * *
   70293 ** Synopsis: if r[P1]!=NULL goto P2
   70294 **
   70295 ** Jump to P2 if the value in register P1 is not NULL.
   70296 */
   70297 case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
   70298   pIn1 = &aMem[pOp->p1];
   70299   VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
   70300   if( (pIn1->flags & MEM_Null)==0 ){
   70301     pc = pOp->p2 - 1;
   70302   }
   70303   break;
   70304 }
   70305 
   70306 /* Opcode: Column P1 P2 P3 P4 P5
   70307 ** Synopsis:  r[P3]=PX
   70308 **
   70309 ** Interpret the data that cursor P1 points to as a structure built using
   70310 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
   70311 ** information about the format of the data.)  Extract the P2-th column
   70312 ** from this record.  If there are less that (P2+1)
   70313 ** values in the record, extract a NULL.
   70314 **
   70315 ** The value extracted is stored in register P3.
   70316 **
   70317 ** If the column contains fewer than P2 fields, then extract a NULL.  Or,
   70318 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
   70319 ** the result.
   70320 **
   70321 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
   70322 ** then the cache of the cursor is reset prior to extracting the column.
   70323 ** The first OP_Column against a pseudo-table after the value of the content
   70324 ** register has changed should have this bit set.
   70325 **
   70326 ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
   70327 ** the result is guaranteed to only be used as the argument of a length()
   70328 ** or typeof() function, respectively.  The loading of large blobs can be
   70329 ** skipped for length() and all content loading can be skipped for typeof().
   70330 */
   70331 case OP_Column: {
   70332   i64 payloadSize64; /* Number of bytes in the record */
   70333   int p2;            /* column number to retrieve */
   70334   VdbeCursor *pC;    /* The VDBE cursor */
   70335   BtCursor *pCrsr;   /* The BTree cursor */
   70336   u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
   70337   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
   70338   int len;           /* The length of the serialized data for the column */
   70339   int i;             /* Loop counter */
   70340   Mem *pDest;        /* Where to write the extracted value */
   70341   Mem sMem;          /* For storing the record being decoded */
   70342   const u8 *zData;   /* Part of the record being decoded */
   70343   const u8 *zHdr;    /* Next unparsed byte of the header */
   70344   const u8 *zEndHdr; /* Pointer to first byte after the header */
   70345   u32 offset;        /* Offset into the data */
   70346   u32 szField;       /* Number of bytes in the content of a field */
   70347   u32 avail;         /* Number of bytes of available data */
   70348   u32 t;             /* A type code from the record header */
   70349   Mem *pReg;         /* PseudoTable input register */
   70350 
   70351   p2 = pOp->p2;
   70352   assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
   70353   pDest = &aMem[pOp->p3];
   70354   memAboutToChange(p, pDest);
   70355   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   70356   pC = p->apCsr[pOp->p1];
   70357   assert( pC!=0 );
   70358   assert( p2<pC->nField );
   70359   aType = pC->aType;
   70360   aOffset = aType + pC->nField;
   70361 #ifndef SQLITE_OMIT_VIRTUALTABLE
   70362   assert( pC->pVtabCursor==0 ); /* OP_Column never called on virtual table */
   70363 #endif
   70364   pCrsr = pC->pCursor;
   70365   assert( pCrsr!=0 || pC->pseudoTableReg>0 ); /* pCrsr NULL on PseudoTables */
   70366   assert( pCrsr!=0 || pC->nullRow );          /* pC->nullRow on PseudoTables */
   70367 
   70368   /* If the cursor cache is stale, bring it up-to-date */
   70369   rc = sqlite3VdbeCursorMoveto(pC);
   70370   if( rc ) goto abort_due_to_error;
   70371   if( pC->cacheStatus!=p->cacheCtr || (pOp->p5&OPFLAG_CLEARCACHE)!=0 ){
   70372     if( pC->nullRow ){
   70373       if( pCrsr==0 ){
   70374         assert( pC->pseudoTableReg>0 );
   70375         pReg = &aMem[pC->pseudoTableReg];
   70376         assert( pReg->flags & MEM_Blob );
   70377         assert( memIsValid(pReg) );
   70378         pC->payloadSize = pC->szRow = avail = pReg->n;
   70379         pC->aRow = (u8*)pReg->z;
   70380       }else{
   70381         MemSetTypeFlag(pDest, MEM_Null);
   70382         goto op_column_out;
   70383       }
   70384     }else{
   70385       assert( pCrsr );
   70386       if( pC->isTable==0 ){
   70387         assert( sqlite3BtreeCursorIsValid(pCrsr) );
   70388         VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &payloadSize64);
   70389         assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
   70390         /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
   70391         ** payload size, so it is impossible for payloadSize64 to be
   70392         ** larger than 32 bits. */
   70393         assert( (payloadSize64 & SQLITE_MAX_U32)==(u64)payloadSize64 );
   70394         pC->aRow = sqlite3BtreeKeyFetch(pCrsr, &avail);
   70395         pC->payloadSize = (u32)payloadSize64;
   70396       }else{
   70397         assert( sqlite3BtreeCursorIsValid(pCrsr) );
   70398         VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &pC->payloadSize);
   70399         assert( rc==SQLITE_OK );   /* DataSize() cannot fail */
   70400         pC->aRow = sqlite3BtreeDataFetch(pCrsr, &avail);
   70401       }
   70402       assert( avail<=65536 );  /* Maximum page size is 64KiB */
   70403       if( pC->payloadSize <= (u32)avail ){
   70404         pC->szRow = pC->payloadSize;
   70405       }else{
   70406         pC->szRow = avail;
   70407       }
   70408       if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
   70409         goto too_big;
   70410       }
   70411     }
   70412     pC->cacheStatus = p->cacheCtr;
   70413     pC->iHdrOffset = getVarint32(pC->aRow, offset);
   70414     pC->nHdrParsed = 0;
   70415     aOffset[0] = offset;
   70416     if( avail<offset ){
   70417       /* pC->aRow does not have to hold the entire row, but it does at least
   70418       ** need to cover the header of the record.  If pC->aRow does not contain
   70419       ** the complete header, then set it to zero, forcing the header to be
   70420       ** dynamically allocated. */
   70421       pC->aRow = 0;
   70422       pC->szRow = 0;
   70423     }
   70424 
   70425     /* Make sure a corrupt database has not given us an oversize header.
   70426     ** Do this now to avoid an oversize memory allocation.
   70427     **
   70428     ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
   70429     ** types use so much data space that there can only be 4096 and 32 of
   70430     ** them, respectively.  So the maximum header length results from a
   70431     ** 3-byte type for each of the maximum of 32768 columns plus three
   70432     ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
   70433     */
   70434     if( offset > 98307 || offset > pC->payloadSize ){
   70435       rc = SQLITE_CORRUPT_BKPT;
   70436       goto op_column_error;
   70437     }
   70438   }
   70439 
   70440   /* Make sure at least the first p2+1 entries of the header have been
   70441   ** parsed and valid information is in aOffset[] and aType[].
   70442   */
   70443   if( pC->nHdrParsed<=p2 ){
   70444     /* If there is more header available for parsing in the record, try
   70445     ** to extract additional fields up through the p2+1-th field
   70446     */
   70447     if( pC->iHdrOffset<aOffset[0] ){
   70448       /* Make sure zData points to enough of the record to cover the header. */
   70449       if( pC->aRow==0 ){
   70450         memset(&sMem, 0, sizeof(sMem));
   70451         rc = sqlite3VdbeMemFromBtree(pCrsr, 0, aOffset[0],
   70452                                      !pC->isTable, &sMem);
   70453         if( rc!=SQLITE_OK ){
   70454           goto op_column_error;
   70455         }
   70456         zData = (u8*)sMem.z;
   70457       }else{
   70458         zData = pC->aRow;
   70459       }
   70460 
   70461       /* Fill in aType[i] and aOffset[i] values through the p2-th field. */
   70462       i = pC->nHdrParsed;
   70463       offset = aOffset[i];
   70464       zHdr = zData + pC->iHdrOffset;
   70465       zEndHdr = zData + aOffset[0];
   70466       assert( i<=p2 && zHdr<zEndHdr );
   70467       do{
   70468         if( zHdr[0]<0x80 ){
   70469           t = zHdr[0];
   70470           zHdr++;
   70471         }else{
   70472           zHdr += sqlite3GetVarint32(zHdr, &t);
   70473         }
   70474         aType[i] = t;
   70475         szField = sqlite3VdbeSerialTypeLen(t);
   70476         offset += szField;
   70477         if( offset<szField ){  /* True if offset overflows */
   70478           zHdr = &zEndHdr[1];  /* Forces SQLITE_CORRUPT return below */
   70479           break;
   70480         }
   70481         i++;
   70482         aOffset[i] = offset;
   70483       }while( i<=p2 && zHdr<zEndHdr );
   70484       pC->nHdrParsed = i;
   70485       pC->iHdrOffset = (u32)(zHdr - zData);
   70486       if( pC->aRow==0 ){
   70487         sqlite3VdbeMemRelease(&sMem);
   70488         sMem.flags = MEM_Null;
   70489       }
   70490 
   70491       /* If we have read more header data than was contained in the header,
   70492       ** or if the end of the last field appears to be past the end of the
   70493       ** record, or if the end of the last field appears to be before the end
   70494       ** of the record (when all fields present), then we must be dealing
   70495       ** with a corrupt database.
   70496       */
   70497       if( (zHdr > zEndHdr)
   70498        || (offset > pC->payloadSize)
   70499        || (zHdr==zEndHdr && offset!=pC->payloadSize)
   70500       ){
   70501         rc = SQLITE_CORRUPT_BKPT;
   70502         goto op_column_error;
   70503       }
   70504     }
   70505 
   70506     /* If after trying to extra new entries from the header, nHdrParsed is
   70507     ** still not up to p2, that means that the record has fewer than p2
   70508     ** columns.  So the result will be either the default value or a NULL.
   70509     */
   70510     if( pC->nHdrParsed<=p2 ){
   70511       if( pOp->p4type==P4_MEM ){
   70512         sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
   70513       }else{
   70514         MemSetTypeFlag(pDest, MEM_Null);
   70515       }
   70516       goto op_column_out;
   70517     }
   70518   }
   70519 
   70520   /* Extract the content for the p2+1-th column.  Control can only
   70521   ** reach this point if aOffset[p2], aOffset[p2+1], and aType[p2] are
   70522   ** all valid.
   70523   */
   70524   assert( p2<pC->nHdrParsed );
   70525   assert( rc==SQLITE_OK );
   70526   assert( sqlite3VdbeCheckMemInvariants(pDest) );
   70527   if( pC->szRow>=aOffset[p2+1] ){
   70528     /* This is the common case where the desired content fits on the original
   70529     ** page - where the content is not on an overflow page */
   70530     VdbeMemRelease(pDest);
   70531     sqlite3VdbeSerialGet(pC->aRow+aOffset[p2], aType[p2], pDest);
   70532   }else{
   70533     /* This branch happens only when content is on overflow pages */
   70534     t = aType[p2];
   70535     if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
   70536           && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
   70537      || (len = sqlite3VdbeSerialTypeLen(t))==0
   70538     ){
   70539       /* Content is irrelevant for the typeof() function and for
   70540       ** the length(X) function if X is a blob.  So we might as well use
   70541       ** bogus content rather than reading content from disk.  NULL works
   70542       ** for text and blob and whatever is in the payloadSize64 variable
   70543       ** will work for everything else.  Content is also irrelevant if
   70544       ** the content length is 0. */
   70545       zData = t<=13 ? (u8*)&payloadSize64 : 0;
   70546       sMem.zMalloc = 0;
   70547     }else{
   70548       memset(&sMem, 0, sizeof(sMem));
   70549       sqlite3VdbeMemMove(&sMem, pDest);
   70550       rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, !pC->isTable,
   70551                                    &sMem);
   70552       if( rc!=SQLITE_OK ){
   70553         goto op_column_error;
   70554       }
   70555       zData = (u8*)sMem.z;
   70556     }
   70557     sqlite3VdbeSerialGet(zData, t, pDest);
   70558     /* If we dynamically allocated space to hold the data (in the
   70559     ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
   70560     ** dynamically allocated space over to the pDest structure.
   70561     ** This prevents a memory copy. */
   70562     if( sMem.zMalloc ){
   70563       assert( sMem.z==sMem.zMalloc );
   70564       assert( VdbeMemDynamic(pDest)==0 );
   70565       assert( (pDest->flags & (MEM_Blob|MEM_Str))==0 || pDest->z==sMem.z );
   70566       pDest->flags &= ~(MEM_Ephem|MEM_Static);
   70567       pDest->flags |= MEM_Term;
   70568       pDest->z = sMem.z;
   70569       pDest->zMalloc = sMem.zMalloc;
   70570     }
   70571   }
   70572   pDest->enc = encoding;
   70573 
   70574 op_column_out:
   70575   Deephemeralize(pDest);
   70576 op_column_error:
   70577   UPDATE_MAX_BLOBSIZE(pDest);
   70578   REGISTER_TRACE(pOp->p3, pDest);
   70579   break;
   70580 }
   70581 
   70582 /* Opcode: Affinity P1 P2 * P4 *
   70583 ** Synopsis: affinity(r[P1@P2])
   70584 **
   70585 ** Apply affinities to a range of P2 registers starting with P1.
   70586 **
   70587 ** P4 is a string that is P2 characters long. The nth character of the
   70588 ** string indicates the column affinity that should be used for the nth
   70589 ** memory cell in the range.
   70590 */
   70591 case OP_Affinity: {
   70592   const char *zAffinity;   /* The affinity to be applied */
   70593   char cAff;               /* A single character of affinity */
   70594 
   70595   zAffinity = pOp->p4.z;
   70596   assert( zAffinity!=0 );
   70597   assert( zAffinity[pOp->p2]==0 );
   70598   pIn1 = &aMem[pOp->p1];
   70599   while( (cAff = *(zAffinity++))!=0 ){
   70600     assert( pIn1 <= &p->aMem[(p->nMem-p->nCursor)] );
   70601     assert( memIsValid(pIn1) );
   70602     applyAffinity(pIn1, cAff, encoding);
   70603     pIn1++;
   70604   }
   70605   break;
   70606 }
   70607 
   70608 /* Opcode: MakeRecord P1 P2 P3 P4 *
   70609 ** Synopsis: r[P3]=mkrec(r[P1@P2])
   70610 **
   70611 ** Convert P2 registers beginning with P1 into the [record format]
   70612 ** use as a data record in a database table or as a key
   70613 ** in an index.  The OP_Column opcode can decode the record later.
   70614 **
   70615 ** P4 may be a string that is P2 characters long.  The nth character of the
   70616 ** string indicates the column affinity that should be used for the nth
   70617 ** field of the index key.
   70618 **
   70619 ** The mapping from character to affinity is given by the SQLITE_AFF_
   70620 ** macros defined in sqliteInt.h.
   70621 **
   70622 ** If P4 is NULL then all index fields have the affinity NONE.
   70623 */
   70624 case OP_MakeRecord: {
   70625   u8 *zNewRecord;        /* A buffer to hold the data for the new record */
   70626   Mem *pRec;             /* The new record */
   70627   u64 nData;             /* Number of bytes of data space */
   70628   int nHdr;              /* Number of bytes of header space */
   70629   i64 nByte;             /* Data space required for this record */
   70630   int nZero;             /* Number of zero bytes at the end of the record */
   70631   int nVarint;           /* Number of bytes in a varint */
   70632   u32 serial_type;       /* Type field */
   70633   Mem *pData0;           /* First field to be combined into the record */
   70634   Mem *pLast;            /* Last field of the record */
   70635   int nField;            /* Number of fields in the record */
   70636   char *zAffinity;       /* The affinity string for the record */
   70637   int file_format;       /* File format to use for encoding */
   70638   int i;                 /* Space used in zNewRecord[] header */
   70639   int j;                 /* Space used in zNewRecord[] content */
   70640   int len;               /* Length of a field */
   70641 
   70642   /* Assuming the record contains N fields, the record format looks
   70643   ** like this:
   70644   **
   70645   ** ------------------------------------------------------------------------
   70646   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
   70647   ** ------------------------------------------------------------------------
   70648   **
   70649   ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
   70650   ** and so froth.
   70651   **
   70652   ** Each type field is a varint representing the serial type of the
   70653   ** corresponding data element (see sqlite3VdbeSerialType()). The
   70654   ** hdr-size field is also a varint which is the offset from the beginning
   70655   ** of the record to data0.
   70656   */
   70657   nData = 0;         /* Number of bytes of data space */
   70658   nHdr = 0;          /* Number of bytes of header space */
   70659   nZero = 0;         /* Number of zero bytes at the end of the record */
   70660   nField = pOp->p1;
   70661   zAffinity = pOp->p4.z;
   70662   assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem-p->nCursor)+1 );
   70663   pData0 = &aMem[nField];
   70664   nField = pOp->p2;
   70665   pLast = &pData0[nField-1];
   70666   file_format = p->minWriteFileFormat;
   70667 
   70668   /* Identify the output register */
   70669   assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
   70670   pOut = &aMem[pOp->p3];
   70671   memAboutToChange(p, pOut);
   70672 
   70673   /* Apply the requested affinity to all inputs
   70674   */
   70675   assert( pData0<=pLast );
   70676   if( zAffinity ){
   70677     pRec = pData0;
   70678     do{
   70679       applyAffinity(pRec++, *(zAffinity++), encoding);
   70680       assert( zAffinity[0]==0 || pRec<=pLast );
   70681     }while( zAffinity[0] );
   70682   }
   70683 
   70684   /* Loop through the elements that will make up the record to figure
   70685   ** out how much space is required for the new record.
   70686   */
   70687   pRec = pLast;
   70688   do{
   70689     assert( memIsValid(pRec) );
   70690     serial_type = sqlite3VdbeSerialType(pRec, file_format);
   70691     len = sqlite3VdbeSerialTypeLen(serial_type);
   70692     if( pRec->flags & MEM_Zero ){
   70693       if( nData ){
   70694         sqlite3VdbeMemExpandBlob(pRec);
   70695       }else{
   70696         nZero += pRec->u.nZero;
   70697         len -= pRec->u.nZero;
   70698       }
   70699     }
   70700     nData += len;
   70701     testcase( serial_type==127 );
   70702     testcase( serial_type==128 );
   70703     nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
   70704   }while( (--pRec)>=pData0 );
   70705 
   70706   /* Add the initial header varint and total the size */
   70707   testcase( nHdr==126 );
   70708   testcase( nHdr==127 );
   70709   if( nHdr<=126 ){
   70710     /* The common case */
   70711     nHdr += 1;
   70712   }else{
   70713     /* Rare case of a really large header */
   70714     nVarint = sqlite3VarintLen(nHdr);
   70715     nHdr += nVarint;
   70716     if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
   70717   }
   70718   nByte = nHdr+nData;
   70719   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   70720     goto too_big;
   70721   }
   70722 
   70723   /* Make sure the output register has a buffer large enough to store
   70724   ** the new record. The output register (pOp->p3) is not allowed to
   70725   ** be one of the input registers (because the following call to
   70726   ** sqlite3VdbeMemGrow() could clobber the value before it is used).
   70727   */
   70728   if( sqlite3VdbeMemGrow(pOut, (int)nByte, 0) ){
   70729     goto no_mem;
   70730   }
   70731   zNewRecord = (u8 *)pOut->z;
   70732 
   70733   /* Write the record */
   70734   i = putVarint32(zNewRecord, nHdr);
   70735   j = nHdr;
   70736   assert( pData0<=pLast );
   70737   pRec = pData0;
   70738   do{
   70739     serial_type = sqlite3VdbeSerialType(pRec, file_format);
   70740     i += putVarint32(&zNewRecord[i], serial_type);            /* serial type */
   70741     j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
   70742   }while( (++pRec)<=pLast );
   70743   assert( i==nHdr );
   70744   assert( j==nByte );
   70745 
   70746   assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
   70747   pOut->n = (int)nByte;
   70748   pOut->flags = MEM_Blob;
   70749   pOut->xDel = 0;
   70750   if( nZero ){
   70751     pOut->u.nZero = nZero;
   70752     pOut->flags |= MEM_Zero;
   70753   }
   70754   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
   70755   REGISTER_TRACE(pOp->p3, pOut);
   70756   UPDATE_MAX_BLOBSIZE(pOut);
   70757   break;
   70758 }
   70759 
   70760 /* Opcode: Count P1 P2 * * *
   70761 ** Synopsis: r[P2]=count()
   70762 **
   70763 ** Store the number of entries (an integer value) in the table or index
   70764 ** opened by cursor P1 in register P2
   70765 */
   70766 #ifndef SQLITE_OMIT_BTREECOUNT
   70767 case OP_Count: {         /* out2-prerelease */
   70768   i64 nEntry;
   70769   BtCursor *pCrsr;
   70770 
   70771   pCrsr = p->apCsr[pOp->p1]->pCursor;
   70772   assert( pCrsr );
   70773   nEntry = 0;  /* Not needed.  Only used to silence a warning. */
   70774   rc = sqlite3BtreeCount(pCrsr, &nEntry);
   70775   pOut->u.i = nEntry;
   70776   break;
   70777 }
   70778 #endif
   70779 
   70780 /* Opcode: Savepoint P1 * * P4 *
   70781 **
   70782 ** Open, release or rollback the savepoint named by parameter P4, depending
   70783 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
   70784 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
   70785 */
   70786 case OP_Savepoint: {
   70787   int p1;                         /* Value of P1 operand */
   70788   char *zName;                    /* Name of savepoint */
   70789   int nName;
   70790   Savepoint *pNew;
   70791   Savepoint *pSavepoint;
   70792   Savepoint *pTmp;
   70793   int iSavepoint;
   70794   int ii;
   70795 
   70796   p1 = pOp->p1;
   70797   zName = pOp->p4.z;
   70798 
   70799   /* Assert that the p1 parameter is valid. Also that if there is no open
   70800   ** transaction, then there cannot be any savepoints.
   70801   */
   70802   assert( db->pSavepoint==0 || db->autoCommit==0 );
   70803   assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
   70804   assert( db->pSavepoint || db->isTransactionSavepoint==0 );
   70805   assert( checkSavepointCount(db) );
   70806   assert( p->bIsReader );
   70807 
   70808   if( p1==SAVEPOINT_BEGIN ){
   70809     if( db->nVdbeWrite>0 ){
   70810       /* A new savepoint cannot be created if there are active write
   70811       ** statements (i.e. open read/write incremental blob handles).
   70812       */
   70813       sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
   70814         "SQL statements in progress");
   70815       rc = SQLITE_BUSY;
   70816     }else{
   70817       nName = sqlite3Strlen30(zName);
   70818 
   70819 #ifndef SQLITE_OMIT_VIRTUALTABLE
   70820       /* This call is Ok even if this savepoint is actually a transaction
   70821       ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
   70822       ** If this is a transaction savepoint being opened, it is guaranteed
   70823       ** that the db->aVTrans[] array is empty.  */
   70824       assert( db->autoCommit==0 || db->nVTrans==0 );
   70825       rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
   70826                                 db->nStatement+db->nSavepoint);
   70827       if( rc!=SQLITE_OK ) goto abort_due_to_error;
   70828 #endif
   70829 
   70830       /* Create a new savepoint structure. */
   70831       pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+nName+1);
   70832       if( pNew ){
   70833         pNew->zName = (char *)&pNew[1];
   70834         memcpy(pNew->zName, zName, nName+1);
   70835 
   70836         /* If there is no open transaction, then mark this as a special
   70837         ** "transaction savepoint". */
   70838         if( db->autoCommit ){
   70839           db->autoCommit = 0;
   70840           db->isTransactionSavepoint = 1;
   70841         }else{
   70842           db->nSavepoint++;
   70843         }
   70844 
   70845         /* Link the new savepoint into the database handle's list. */
   70846         pNew->pNext = db->pSavepoint;
   70847         db->pSavepoint = pNew;
   70848         pNew->nDeferredCons = db->nDeferredCons;
   70849         pNew->nDeferredImmCons = db->nDeferredImmCons;
   70850       }
   70851     }
   70852   }else{
   70853     iSavepoint = 0;
   70854 
   70855     /* Find the named savepoint. If there is no such savepoint, then an
   70856     ** an error is returned to the user.  */
   70857     for(
   70858       pSavepoint = db->pSavepoint;
   70859       pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
   70860       pSavepoint = pSavepoint->pNext
   70861     ){
   70862       iSavepoint++;
   70863     }
   70864     if( !pSavepoint ){
   70865       sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", zName);
   70866       rc = SQLITE_ERROR;
   70867     }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
   70868       /* It is not possible to release (commit) a savepoint if there are
   70869       ** active write statements.
   70870       */
   70871       sqlite3SetString(&p->zErrMsg, db,
   70872         "cannot release savepoint - SQL statements in progress"
   70873       );
   70874       rc = SQLITE_BUSY;
   70875     }else{
   70876 
   70877       /* Determine whether or not this is a transaction savepoint. If so,
   70878       ** and this is a RELEASE command, then the current transaction
   70879       ** is committed.
   70880       */
   70881       int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
   70882       if( isTransaction && p1==SAVEPOINT_RELEASE ){
   70883         if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
   70884           goto vdbe_return;
   70885         }
   70886         db->autoCommit = 1;
   70887         if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
   70888           p->pc = pc;
   70889           db->autoCommit = 0;
   70890           p->rc = rc = SQLITE_BUSY;
   70891           goto vdbe_return;
   70892         }
   70893         db->isTransactionSavepoint = 0;
   70894         rc = p->rc;
   70895       }else{
   70896         iSavepoint = db->nSavepoint - iSavepoint - 1;
   70897         if( p1==SAVEPOINT_ROLLBACK ){
   70898           for(ii=0; ii<db->nDb; ii++){
   70899             sqlite3BtreeTripAllCursors(db->aDb[ii].pBt, SQLITE_ABORT);
   70900           }
   70901         }
   70902         for(ii=0; ii<db->nDb; ii++){
   70903           rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
   70904           if( rc!=SQLITE_OK ){
   70905             goto abort_due_to_error;
   70906           }
   70907         }
   70908         if( p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
   70909           sqlite3ExpirePreparedStatements(db);
   70910           sqlite3ResetAllSchemasOfConnection(db);
   70911           db->flags = (db->flags | SQLITE_InternChanges);
   70912         }
   70913       }
   70914 
   70915       /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
   70916       ** savepoints nested inside of the savepoint being operated on. */
   70917       while( db->pSavepoint!=pSavepoint ){
   70918         pTmp = db->pSavepoint;
   70919         db->pSavepoint = pTmp->pNext;
   70920         sqlite3DbFree(db, pTmp);
   70921         db->nSavepoint--;
   70922       }
   70923 
   70924       /* If it is a RELEASE, then destroy the savepoint being operated on
   70925       ** too. If it is a ROLLBACK TO, then set the number of deferred
   70926       ** constraint violations present in the database to the value stored
   70927       ** when the savepoint was created.  */
   70928       if( p1==SAVEPOINT_RELEASE ){
   70929         assert( pSavepoint==db->pSavepoint );
   70930         db->pSavepoint = pSavepoint->pNext;
   70931         sqlite3DbFree(db, pSavepoint);
   70932         if( !isTransaction ){
   70933           db->nSavepoint--;
   70934         }
   70935       }else{
   70936         db->nDeferredCons = pSavepoint->nDeferredCons;
   70937         db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
   70938       }
   70939 
   70940       if( !isTransaction ){
   70941         rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
   70942         if( rc!=SQLITE_OK ) goto abort_due_to_error;
   70943       }
   70944     }
   70945   }
   70946 
   70947   break;
   70948 }
   70949 
   70950 /* Opcode: AutoCommit P1 P2 * * *
   70951 **
   70952 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
   70953 ** back any currently active btree transactions. If there are any active
   70954 ** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
   70955 ** there are active writing VMs or active VMs that use shared cache.
   70956 **
   70957 ** This instruction causes the VM to halt.
   70958 */
   70959 case OP_AutoCommit: {
   70960   int desiredAutoCommit;
   70961   int iRollback;
   70962   int turnOnAC;
   70963 
   70964   desiredAutoCommit = pOp->p1;
   70965   iRollback = pOp->p2;
   70966   turnOnAC = desiredAutoCommit && !db->autoCommit;
   70967   assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
   70968   assert( desiredAutoCommit==1 || iRollback==0 );
   70969   assert( db->nVdbeActive>0 );  /* At least this one VM is active */
   70970   assert( p->bIsReader );
   70971 
   70972 #if 0
   70973   if( turnOnAC && iRollback && db->nVdbeActive>1 ){
   70974     /* If this instruction implements a ROLLBACK and other VMs are
   70975     ** still running, and a transaction is active, return an error indicating
   70976     ** that the other VMs must complete first.
   70977     */
   70978     sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
   70979         "SQL statements in progress");
   70980     rc = SQLITE_BUSY;
   70981   }else
   70982 #endif
   70983   if( turnOnAC && !iRollback && db->nVdbeWrite>0 ){
   70984     /* If this instruction implements a COMMIT and other VMs are writing
   70985     ** return an error indicating that the other VMs must complete first.
   70986     */
   70987     sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
   70988         "SQL statements in progress");
   70989     rc = SQLITE_BUSY;
   70990   }else if( desiredAutoCommit!=db->autoCommit ){
   70991     if( iRollback ){
   70992       assert( desiredAutoCommit==1 );
   70993       sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
   70994       db->autoCommit = 1;
   70995     }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
   70996       goto vdbe_return;
   70997     }else{
   70998       db->autoCommit = (u8)desiredAutoCommit;
   70999       if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
   71000         p->pc = pc;
   71001         db->autoCommit = (u8)(1-desiredAutoCommit);
   71002         p->rc = rc = SQLITE_BUSY;
   71003         goto vdbe_return;
   71004       }
   71005     }
   71006     assert( db->nStatement==0 );
   71007     sqlite3CloseSavepoints(db);
   71008     if( p->rc==SQLITE_OK ){
   71009       rc = SQLITE_DONE;
   71010     }else{
   71011       rc = SQLITE_ERROR;
   71012     }
   71013     goto vdbe_return;
   71014   }else{
   71015     sqlite3SetString(&p->zErrMsg, db,
   71016         (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
   71017         (iRollback)?"cannot rollback - no transaction is active":
   71018                    "cannot commit - no transaction is active"));
   71019 
   71020     rc = SQLITE_ERROR;
   71021   }
   71022   break;
   71023 }
   71024 
   71025 /* Opcode: Transaction P1 P2 P3 P4 P5
   71026 **
   71027 ** Begin a transaction on database P1 if a transaction is not already
   71028 ** active.
   71029 ** If P2 is non-zero, then a write-transaction is started, or if a
   71030 ** read-transaction is already active, it is upgraded to a write-transaction.
   71031 ** If P2 is zero, then a read-transaction is started.
   71032 **
   71033 ** P1 is the index of the database file on which the transaction is
   71034 ** started.  Index 0 is the main database file and index 1 is the
   71035 ** file used for temporary tables.  Indices of 2 or more are used for
   71036 ** attached databases.
   71037 **
   71038 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
   71039 ** true (this flag is set if the Vdbe may modify more than one row and may
   71040 ** throw an ABORT exception), a statement transaction may also be opened.
   71041 ** More specifically, a statement transaction is opened iff the database
   71042 ** connection is currently not in autocommit mode, or if there are other
   71043 ** active statements. A statement transaction allows the changes made by this
   71044 ** VDBE to be rolled back after an error without having to roll back the
   71045 ** entire transaction. If no error is encountered, the statement transaction
   71046 ** will automatically commit when the VDBE halts.
   71047 **
   71048 ** If P5!=0 then this opcode also checks the schema cookie against P3
   71049 ** and the schema generation counter against P4.
   71050 ** The cookie changes its value whenever the database schema changes.
   71051 ** This operation is used to detect when that the cookie has changed
   71052 ** and that the current process needs to reread the schema.  If the schema
   71053 ** cookie in P3 differs from the schema cookie in the database header or
   71054 ** if the schema generation counter in P4 differs from the current
   71055 ** generation counter, then an SQLITE_SCHEMA error is raised and execution
   71056 ** halts.  The sqlite3_step() wrapper function might then reprepare the
   71057 ** statement and rerun it from the beginning.
   71058 */
   71059 case OP_Transaction: {
   71060   Btree *pBt;
   71061   int iMeta;
   71062   int iGen;
   71063 
   71064   assert( p->bIsReader );
   71065   assert( p->readOnly==0 || pOp->p2==0 );
   71066   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   71067   assert( DbMaskTest(p->btreeMask, pOp->p1) );
   71068   if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
   71069     rc = SQLITE_READONLY;
   71070     goto abort_due_to_error;
   71071   }
   71072   pBt = db->aDb[pOp->p1].pBt;
   71073 
   71074   if( pBt ){
   71075     rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
   71076     if( rc==SQLITE_BUSY ){
   71077       p->pc = pc;
   71078       p->rc = rc = SQLITE_BUSY;
   71079       goto vdbe_return;
   71080     }
   71081     if( rc!=SQLITE_OK ){
   71082       goto abort_due_to_error;
   71083     }
   71084 
   71085     if( pOp->p2 && p->usesStmtJournal
   71086      && (db->autoCommit==0 || db->nVdbeRead>1)
   71087     ){
   71088       assert( sqlite3BtreeIsInTrans(pBt) );
   71089       if( p->iStatement==0 ){
   71090         assert( db->nStatement>=0 && db->nSavepoint>=0 );
   71091         db->nStatement++;
   71092         p->iStatement = db->nSavepoint + db->nStatement;
   71093       }
   71094 
   71095       rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
   71096       if( rc==SQLITE_OK ){
   71097         rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
   71098       }
   71099 
   71100       /* Store the current value of the database handles deferred constraint
   71101       ** counter. If the statement transaction needs to be rolled back,
   71102       ** the value of this counter needs to be restored too.  */
   71103       p->nStmtDefCons = db->nDeferredCons;
   71104       p->nStmtDefImmCons = db->nDeferredImmCons;
   71105     }
   71106 
   71107     /* Gather the schema version number for checking */
   71108     sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta);
   71109     iGen = db->aDb[pOp->p1].pSchema->iGeneration;
   71110   }else{
   71111     iGen = iMeta = 0;
   71112   }
   71113   assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
   71114   if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){
   71115     sqlite3DbFree(db, p->zErrMsg);
   71116     p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
   71117     /* If the schema-cookie from the database file matches the cookie
   71118     ** stored with the in-memory representation of the schema, do
   71119     ** not reload the schema from the database file.
   71120     **
   71121     ** If virtual-tables are in use, this is not just an optimization.
   71122     ** Often, v-tables store their data in other SQLite tables, which
   71123     ** are queried from within xNext() and other v-table methods using
   71124     ** prepared queries. If such a query is out-of-date, we do not want to
   71125     ** discard the database schema, as the user code implementing the
   71126     ** v-table would have to be ready for the sqlite3_vtab structure itself
   71127     ** to be invalidated whenever sqlite3_step() is called from within
   71128     ** a v-table method.
   71129     */
   71130     if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
   71131       sqlite3ResetOneSchema(db, pOp->p1);
   71132     }
   71133     p->expired = 1;
   71134     rc = SQLITE_SCHEMA;
   71135   }
   71136   break;
   71137 }
   71138 
   71139 /* Opcode: ReadCookie P1 P2 P3 * *
   71140 **
   71141 ** Read cookie number P3 from database P1 and write it into register P2.
   71142 ** P3==1 is the schema version.  P3==2 is the database format.
   71143 ** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
   71144 ** the main database file and P1==1 is the database file used to store
   71145 ** temporary tables.
   71146 **
   71147 ** There must be a read-lock on the database (either a transaction
   71148 ** must be started or there must be an open cursor) before
   71149 ** executing this instruction.
   71150 */
   71151 case OP_ReadCookie: {               /* out2-prerelease */
   71152   int iMeta;
   71153   int iDb;
   71154   int iCookie;
   71155 
   71156   assert( p->bIsReader );
   71157   iDb = pOp->p1;
   71158   iCookie = pOp->p3;
   71159   assert( pOp->p3<SQLITE_N_BTREE_META );
   71160   assert( iDb>=0 && iDb<db->nDb );
   71161   assert( db->aDb[iDb].pBt!=0 );
   71162   assert( DbMaskTest(p->btreeMask, iDb) );
   71163 
   71164   sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
   71165   pOut->u.i = iMeta;
   71166   break;
   71167 }
   71168 
   71169 /* Opcode: SetCookie P1 P2 P3 * *
   71170 **
   71171 ** Write the content of register P3 (interpreted as an integer)
   71172 ** into cookie number P2 of database P1.  P2==1 is the schema version.
   71173 ** P2==2 is the database format. P2==3 is the recommended pager cache
   71174 ** size, and so forth.  P1==0 is the main database file and P1==1 is the
   71175 ** database file used to store temporary tables.
   71176 **
   71177 ** A transaction must be started before executing this opcode.
   71178 */
   71179 case OP_SetCookie: {       /* in3 */
   71180   Db *pDb;
   71181   assert( pOp->p2<SQLITE_N_BTREE_META );
   71182   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   71183   assert( DbMaskTest(p->btreeMask, pOp->p1) );
   71184   assert( p->readOnly==0 );
   71185   pDb = &db->aDb[pOp->p1];
   71186   assert( pDb->pBt!=0 );
   71187   assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
   71188   pIn3 = &aMem[pOp->p3];
   71189   sqlite3VdbeMemIntegerify(pIn3);
   71190   /* See note about index shifting on OP_ReadCookie */
   71191   rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, (int)pIn3->u.i);
   71192   if( pOp->p2==BTREE_SCHEMA_VERSION ){
   71193     /* When the schema cookie changes, record the new cookie internally */
   71194     pDb->pSchema->schema_cookie = (int)pIn3->u.i;
   71195     db->flags |= SQLITE_InternChanges;
   71196   }else if( pOp->p2==BTREE_FILE_FORMAT ){
   71197     /* Record changes in the file format */
   71198     pDb->pSchema->file_format = (u8)pIn3->u.i;
   71199   }
   71200   if( pOp->p1==1 ){
   71201     /* Invalidate all prepared statements whenever the TEMP database
   71202     ** schema is changed.  Ticket #1644 */
   71203     sqlite3ExpirePreparedStatements(db);
   71204     p->expired = 0;
   71205   }
   71206   break;
   71207 }
   71208 
   71209 /* Opcode: OpenRead P1 P2 P3 P4 P5
   71210 ** Synopsis: root=P2 iDb=P3
   71211 **
   71212 ** Open a read-only cursor for the database table whose root page is
   71213 ** P2 in a database file.  The database file is determined by P3.
   71214 ** P3==0 means the main database, P3==1 means the database used for
   71215 ** temporary tables, and P3>1 means used the corresponding attached
   71216 ** database.  Give the new cursor an identifier of P1.  The P1
   71217 ** values need not be contiguous but all P1 values should be small integers.
   71218 ** It is an error for P1 to be negative.
   71219 **
   71220 ** If P5!=0 then use the content of register P2 as the root page, not
   71221 ** the value of P2 itself.
   71222 **
   71223 ** There will be a read lock on the database whenever there is an
   71224 ** open cursor.  If the database was unlocked prior to this instruction
   71225 ** then a read lock is acquired as part of this instruction.  A read
   71226 ** lock allows other processes to read the database but prohibits
   71227 ** any other process from modifying the database.  The read lock is
   71228 ** released when all cursors are closed.  If this instruction attempts
   71229 ** to get a read lock but fails, the script terminates with an
   71230 ** SQLITE_BUSY error code.
   71231 **
   71232 ** The P4 value may be either an integer (P4_INT32) or a pointer to
   71233 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
   71234 ** structure, then said structure defines the content and collating
   71235 ** sequence of the index being opened. Otherwise, if P4 is an integer
   71236 ** value, it is set to the number of columns in the table.
   71237 **
   71238 ** See also: OpenWrite, ReopenIdx
   71239 */
   71240 /* Opcode: ReopenIdx P1 P2 P3 P4 P5
   71241 ** Synopsis: root=P2 iDb=P3
   71242 **
   71243 ** The ReopenIdx opcode works exactly like ReadOpen except that it first
   71244 ** checks to see if the cursor on P1 is already open with a root page
   71245 ** number of P2 and if it is this opcode becomes a no-op.  In other words,
   71246 ** if the cursor is already open, do not reopen it.
   71247 **
   71248 ** The ReopenIdx opcode may only be used with P5==0 and with P4 being
   71249 ** a P4_KEYINFO object.  Furthermore, the P3 value must be the same as
   71250 ** every other ReopenIdx or OpenRead for the same cursor number.
   71251 **
   71252 ** See the OpenRead opcode documentation for additional information.
   71253 */
   71254 /* Opcode: OpenWrite P1 P2 P3 P4 P5
   71255 ** Synopsis: root=P2 iDb=P3
   71256 **
   71257 ** Open a read/write cursor named P1 on the table or index whose root
   71258 ** page is P2.  Or if P5!=0 use the content of register P2 to find the
   71259 ** root page.
   71260 **
   71261 ** The P4 value may be either an integer (P4_INT32) or a pointer to
   71262 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
   71263 ** structure, then said structure defines the content and collating
   71264 ** sequence of the index being opened. Otherwise, if P4 is an integer
   71265 ** value, it is set to the number of columns in the table, or to the
   71266 ** largest index of any column of the table that is actually used.
   71267 **
   71268 ** This instruction works just like OpenRead except that it opens the cursor
   71269 ** in read/write mode.  For a given table, there can be one or more read-only
   71270 ** cursors or a single read/write cursor but not both.
   71271 **
   71272 ** See also OpenRead.
   71273 */
   71274 case OP_ReopenIdx: {
   71275   VdbeCursor *pCur;
   71276 
   71277   assert( pOp->p5==0 );
   71278   assert( pOp->p4type==P4_KEYINFO );
   71279   pCur = p->apCsr[pOp->p1];
   71280   if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
   71281     assert( pCur->iDb==pOp->p3 );      /* Guaranteed by the code generator */
   71282     break;
   71283   }
   71284   /* If the cursor is not currently open or is open on a different
   71285   ** index, then fall through into OP_OpenRead to force a reopen */
   71286 }
   71287 case OP_OpenRead:
   71288 case OP_OpenWrite: {
   71289   int nField;
   71290   KeyInfo *pKeyInfo;
   71291   int p2;
   71292   int iDb;
   71293   int wrFlag;
   71294   Btree *pX;
   71295   VdbeCursor *pCur;
   71296   Db *pDb;
   71297 
   71298   assert( (pOp->p5&(OPFLAG_P2ISREG|OPFLAG_BULKCSR))==pOp->p5 );
   71299   assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 );
   71300   assert( p->bIsReader );
   71301   assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
   71302           || p->readOnly==0 );
   71303 
   71304   if( p->expired ){
   71305     rc = SQLITE_ABORT;
   71306     break;
   71307   }
   71308 
   71309   nField = 0;
   71310   pKeyInfo = 0;
   71311   p2 = pOp->p2;
   71312   iDb = pOp->p3;
   71313   assert( iDb>=0 && iDb<db->nDb );
   71314   assert( DbMaskTest(p->btreeMask, iDb) );
   71315   pDb = &db->aDb[iDb];
   71316   pX = pDb->pBt;
   71317   assert( pX!=0 );
   71318   if( pOp->opcode==OP_OpenWrite ){
   71319     wrFlag = 1;
   71320     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   71321     if( pDb->pSchema->file_format < p->minWriteFileFormat ){
   71322       p->minWriteFileFormat = pDb->pSchema->file_format;
   71323     }
   71324   }else{
   71325     wrFlag = 0;
   71326   }
   71327   if( pOp->p5 & OPFLAG_P2ISREG ){
   71328     assert( p2>0 );
   71329     assert( p2<=(p->nMem-p->nCursor) );
   71330     pIn2 = &aMem[p2];
   71331     assert( memIsValid(pIn2) );
   71332     assert( (pIn2->flags & MEM_Int)!=0 );
   71333     sqlite3VdbeMemIntegerify(pIn2);
   71334     p2 = (int)pIn2->u.i;
   71335     /* The p2 value always comes from a prior OP_CreateTable opcode and
   71336     ** that opcode will always set the p2 value to 2 or more or else fail.
   71337     ** If there were a failure, the prepared statement would have halted
   71338     ** before reaching this instruction. */
   71339     if( NEVER(p2<2) ) {
   71340       rc = SQLITE_CORRUPT_BKPT;
   71341       goto abort_due_to_error;
   71342     }
   71343   }
   71344   if( pOp->p4type==P4_KEYINFO ){
   71345     pKeyInfo = pOp->p4.pKeyInfo;
   71346     assert( pKeyInfo->enc==ENC(db) );
   71347     assert( pKeyInfo->db==db );
   71348     nField = pKeyInfo->nField+pKeyInfo->nXField;
   71349   }else if( pOp->p4type==P4_INT32 ){
   71350     nField = pOp->p4.i;
   71351   }
   71352   assert( pOp->p1>=0 );
   71353   assert( nField>=0 );
   71354   testcase( nField==0 );  /* Table with INTEGER PRIMARY KEY and nothing else */
   71355   pCur = allocateCursor(p, pOp->p1, nField, iDb, 1);
   71356   if( pCur==0 ) goto no_mem;
   71357   pCur->nullRow = 1;
   71358   pCur->isOrdered = 1;
   71359   pCur->pgnoRoot = p2;
   71360   rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->pCursor);
   71361   pCur->pKeyInfo = pKeyInfo;
   71362   assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
   71363   sqlite3BtreeCursorHints(pCur->pCursor, (pOp->p5 & OPFLAG_BULKCSR));
   71364 
   71365   /* Since it performs no memory allocation or IO, the only value that
   71366   ** sqlite3BtreeCursor() may return is SQLITE_OK. */
   71367   assert( rc==SQLITE_OK );
   71368 
   71369   /* Set the VdbeCursor.isTable variable. Previous versions of
   71370   ** SQLite used to check if the root-page flags were sane at this point
   71371   ** and report database corruption if they were not, but this check has
   71372   ** since moved into the btree layer.  */
   71373   pCur->isTable = pOp->p4type!=P4_KEYINFO;
   71374   break;
   71375 }
   71376 
   71377 /* Opcode: OpenEphemeral P1 P2 * P4 P5
   71378 ** Synopsis: nColumn=P2
   71379 **
   71380 ** Open a new cursor P1 to a transient table.
   71381 ** The cursor is always opened read/write even if
   71382 ** the main database is read-only.  The ephemeral
   71383 ** table is deleted automatically when the cursor is closed.
   71384 **
   71385 ** P2 is the number of columns in the ephemeral table.
   71386 ** The cursor points to a BTree table if P4==0 and to a BTree index
   71387 ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
   71388 ** that defines the format of keys in the index.
   71389 **
   71390 ** The P5 parameter can be a mask of the BTREE_* flags defined
   71391 ** in btree.h.  These flags control aspects of the operation of
   71392 ** the btree.  The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
   71393 ** added automatically.
   71394 */
   71395 /* Opcode: OpenAutoindex P1 P2 * P4 *
   71396 ** Synopsis: nColumn=P2
   71397 **
   71398 ** This opcode works the same as OP_OpenEphemeral.  It has a
   71399 ** different name to distinguish its use.  Tables created using
   71400 ** by this opcode will be used for automatically created transient
   71401 ** indices in joins.
   71402 */
   71403 case OP_OpenAutoindex:
   71404 case OP_OpenEphemeral: {
   71405   VdbeCursor *pCx;
   71406   KeyInfo *pKeyInfo;
   71407 
   71408   static const int vfsFlags =
   71409       SQLITE_OPEN_READWRITE |
   71410       SQLITE_OPEN_CREATE |
   71411       SQLITE_OPEN_EXCLUSIVE |
   71412       SQLITE_OPEN_DELETEONCLOSE |
   71413       SQLITE_OPEN_TRANSIENT_DB;
   71414   assert( pOp->p1>=0 );
   71415   assert( pOp->p2>=0 );
   71416   pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
   71417   if( pCx==0 ) goto no_mem;
   71418   pCx->nullRow = 1;
   71419   pCx->isEphemeral = 1;
   71420   rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBt,
   71421                         BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
   71422   if( rc==SQLITE_OK ){
   71423     rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
   71424   }
   71425   if( rc==SQLITE_OK ){
   71426     /* If a transient index is required, create it by calling
   71427     ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
   71428     ** opening it. If a transient table is required, just use the
   71429     ** automatically created table with root-page 1 (an BLOB_INTKEY table).
   71430     */
   71431     if( (pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
   71432       int pgno;
   71433       assert( pOp->p4type==P4_KEYINFO );
   71434       rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
   71435       if( rc==SQLITE_OK ){
   71436         assert( pgno==MASTER_ROOT+1 );
   71437         assert( pKeyInfo->db==db );
   71438         assert( pKeyInfo->enc==ENC(db) );
   71439         pCx->pKeyInfo = pKeyInfo;
   71440         rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1, pKeyInfo, pCx->pCursor);
   71441       }
   71442       pCx->isTable = 0;
   71443     }else{
   71444       rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, 1, 0, pCx->pCursor);
   71445       pCx->isTable = 1;
   71446     }
   71447   }
   71448   pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
   71449   break;
   71450 }
   71451 
   71452 /* Opcode: SorterOpen P1 P2 * P4 *
   71453 **
   71454 ** This opcode works like OP_OpenEphemeral except that it opens
   71455 ** a transient index that is specifically designed to sort large
   71456 ** tables using an external merge-sort algorithm.
   71457 */
   71458 case OP_SorterOpen: {
   71459   VdbeCursor *pCx;
   71460 
   71461   assert( pOp->p1>=0 );
   71462   assert( pOp->p2>=0 );
   71463   pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
   71464   if( pCx==0 ) goto no_mem;
   71465   pCx->pKeyInfo = pOp->p4.pKeyInfo;
   71466   assert( pCx->pKeyInfo->db==db );
   71467   assert( pCx->pKeyInfo->enc==ENC(db) );
   71468   rc = sqlite3VdbeSorterInit(db, pCx);
   71469   break;
   71470 }
   71471 
   71472 /* Opcode: OpenPseudo P1 P2 P3 * *
   71473 ** Synopsis: P3 columns in r[P2]
   71474 **
   71475 ** Open a new cursor that points to a fake table that contains a single
   71476 ** row of data.  The content of that one row is the content of memory
   71477 ** register P2.  In other words, cursor P1 becomes an alias for the
   71478 ** MEM_Blob content contained in register P2.
   71479 **
   71480 ** A pseudo-table created by this opcode is used to hold a single
   71481 ** row output from the sorter so that the row can be decomposed into
   71482 ** individual columns using the OP_Column opcode.  The OP_Column opcode
   71483 ** is the only cursor opcode that works with a pseudo-table.
   71484 **
   71485 ** P3 is the number of fields in the records that will be stored by
   71486 ** the pseudo-table.
   71487 */
   71488 case OP_OpenPseudo: {
   71489   VdbeCursor *pCx;
   71490 
   71491   assert( pOp->p1>=0 );
   71492   assert( pOp->p3>=0 );
   71493   pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
   71494   if( pCx==0 ) goto no_mem;
   71495   pCx->nullRow = 1;
   71496   pCx->pseudoTableReg = pOp->p2;
   71497   pCx->isTable = 1;
   71498   assert( pOp->p5==0 );
   71499   break;
   71500 }
   71501 
   71502 /* Opcode: Close P1 * * * *
   71503 **
   71504 ** Close a cursor previously opened as P1.  If P1 is not
   71505 ** currently open, this instruction is a no-op.
   71506 */
   71507 case OP_Close: {
   71508   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   71509   sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
   71510   p->apCsr[pOp->p1] = 0;
   71511   break;
   71512 }
   71513 
   71514 /* Opcode: SeekGE P1 P2 P3 P4 *
   71515 ** Synopsis: key=r[P3@P4]
   71516 **
   71517 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
   71518 ** use the value in register P3 as the key.  If cursor P1 refers
   71519 ** to an SQL index, then P3 is the first in an array of P4 registers
   71520 ** that are used as an unpacked index key.
   71521 **
   71522 ** Reposition cursor P1 so that  it points to the smallest entry that
   71523 ** is greater than or equal to the key value. If there are no records
   71524 ** greater than or equal to the key and P2 is not zero, then jump to P2.
   71525 **
   71526 ** This opcode leaves the cursor configured to move in forward order,
   71527 ** from the beginning toward the end.  In other words, the cursor is
   71528 ** configured to use Next, not Prev.
   71529 **
   71530 ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
   71531 */
   71532 /* Opcode: SeekGT P1 P2 P3 P4 *
   71533 ** Synopsis: key=r[P3@P4]
   71534 **
   71535 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
   71536 ** use the value in register P3 as a key. If cursor P1 refers
   71537 ** to an SQL index, then P3 is the first in an array of P4 registers
   71538 ** that are used as an unpacked index key.
   71539 **
   71540 ** Reposition cursor P1 so that  it points to the smallest entry that
   71541 ** is greater than the key value. If there are no records greater than
   71542 ** the key and P2 is not zero, then jump to P2.
   71543 **
   71544 ** This opcode leaves the cursor configured to move in forward order,
   71545 ** from the beginning toward the end.  In other words, the cursor is
   71546 ** configured to use Next, not Prev.
   71547 **
   71548 ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
   71549 */
   71550 /* Opcode: SeekLT P1 P2 P3 P4 *
   71551 ** Synopsis: key=r[P3@P4]
   71552 **
   71553 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
   71554 ** use the value in register P3 as a key. If cursor P1 refers
   71555 ** to an SQL index, then P3 is the first in an array of P4 registers
   71556 ** that are used as an unpacked index key.
   71557 **
   71558 ** Reposition cursor P1 so that  it points to the largest entry that
   71559 ** is less than the key value. If there are no records less than
   71560 ** the key and P2 is not zero, then jump to P2.
   71561 **
   71562 ** This opcode leaves the cursor configured to move in reverse order,
   71563 ** from the end toward the beginning.  In other words, the cursor is
   71564 ** configured to use Prev, not Next.
   71565 **
   71566 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
   71567 */
   71568 /* Opcode: SeekLE P1 P2 P3 P4 *
   71569 ** Synopsis: key=r[P3@P4]
   71570 **
   71571 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
   71572 ** use the value in register P3 as a key. If cursor P1 refers
   71573 ** to an SQL index, then P3 is the first in an array of P4 registers
   71574 ** that are used as an unpacked index key.
   71575 **
   71576 ** Reposition cursor P1 so that it points to the largest entry that
   71577 ** is less than or equal to the key value. If there are no records
   71578 ** less than or equal to the key and P2 is not zero, then jump to P2.
   71579 **
   71580 ** This opcode leaves the cursor configured to move in reverse order,
   71581 ** from the end toward the beginning.  In other words, the cursor is
   71582 ** configured to use Prev, not Next.
   71583 **
   71584 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
   71585 */
   71586 case OP_SeekLT:         /* jump, in3 */
   71587 case OP_SeekLE:         /* jump, in3 */
   71588 case OP_SeekGE:         /* jump, in3 */
   71589 case OP_SeekGT: {       /* jump, in3 */
   71590   int res;
   71591   int oc;
   71592   VdbeCursor *pC;
   71593   UnpackedRecord r;
   71594   int nField;
   71595   i64 iKey;      /* The rowid we are to seek to */
   71596 
   71597   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   71598   assert( pOp->p2!=0 );
   71599   pC = p->apCsr[pOp->p1];
   71600   assert( pC!=0 );
   71601   assert( pC->pseudoTableReg==0 );
   71602   assert( OP_SeekLE == OP_SeekLT+1 );
   71603   assert( OP_SeekGE == OP_SeekLT+2 );
   71604   assert( OP_SeekGT == OP_SeekLT+3 );
   71605   assert( pC->isOrdered );
   71606   assert( pC->pCursor!=0 );
   71607   oc = pOp->opcode;
   71608   pC->nullRow = 0;
   71609 #ifdef SQLITE_DEBUG
   71610   pC->seekOp = pOp->opcode;
   71611 #endif
   71612   if( pC->isTable ){
   71613     /* The input value in P3 might be of any type: integer, real, string,
   71614     ** blob, or NULL.  But it needs to be an integer before we can do
   71615     ** the seek, so covert it. */
   71616     pIn3 = &aMem[pOp->p3];
   71617     ApplyNumericAffinity(pIn3);
   71618     iKey = sqlite3VdbeIntValue(pIn3);
   71619     pC->rowidIsValid = 0;
   71620 
   71621     /* If the P3 value could not be converted into an integer without
   71622     ** loss of information, then special processing is required... */
   71623     if( (pIn3->flags & MEM_Int)==0 ){
   71624       if( (pIn3->flags & MEM_Real)==0 ){
   71625         /* If the P3 value cannot be converted into any kind of a number,
   71626         ** then the seek is not possible, so jump to P2 */
   71627         pc = pOp->p2 - 1;  VdbeBranchTaken(1,2);
   71628         break;
   71629       }
   71630 
   71631       /* If the approximation iKey is larger than the actual real search
   71632       ** term, substitute >= for > and < for <=. e.g. if the search term
   71633       ** is 4.9 and the integer approximation 5:
   71634       **
   71635       **        (x >  4.9)    ->     (x >= 5)
   71636       **        (x <= 4.9)    ->     (x <  5)
   71637       */
   71638       if( pIn3->r<(double)iKey ){
   71639         assert( OP_SeekGE==(OP_SeekGT-1) );
   71640         assert( OP_SeekLT==(OP_SeekLE-1) );
   71641         assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
   71642         if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
   71643       }
   71644 
   71645       /* If the approximation iKey is smaller than the actual real search
   71646       ** term, substitute <= for < and > for >=.  */
   71647       else if( pIn3->r>(double)iKey ){
   71648         assert( OP_SeekLE==(OP_SeekLT+1) );
   71649         assert( OP_SeekGT==(OP_SeekGE+1) );
   71650         assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
   71651         if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
   71652       }
   71653     }
   71654     rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)iKey, 0, &res);
   71655     if( rc!=SQLITE_OK ){
   71656       goto abort_due_to_error;
   71657     }
   71658     if( res==0 ){
   71659       pC->rowidIsValid = 1;
   71660       pC->lastRowid = iKey;
   71661     }
   71662   }else{
   71663     nField = pOp->p4.i;
   71664     assert( pOp->p4type==P4_INT32 );
   71665     assert( nField>0 );
   71666     r.pKeyInfo = pC->pKeyInfo;
   71667     r.nField = (u16)nField;
   71668 
   71669     /* The next line of code computes as follows, only faster:
   71670     **   if( oc==OP_SeekGT || oc==OP_SeekLE ){
   71671     **     r.default_rc = -1;
   71672     **   }else{
   71673     **     r.default_rc = +1;
   71674     **   }
   71675     */
   71676     r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
   71677     assert( oc!=OP_SeekGT || r.default_rc==-1 );
   71678     assert( oc!=OP_SeekLE || r.default_rc==-1 );
   71679     assert( oc!=OP_SeekGE || r.default_rc==+1 );
   71680     assert( oc!=OP_SeekLT || r.default_rc==+1 );
   71681 
   71682     r.aMem = &aMem[pOp->p3];
   71683 #ifdef SQLITE_DEBUG
   71684     { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
   71685 #endif
   71686     ExpandBlob(r.aMem);
   71687     rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, &r, 0, 0, &res);
   71688     if( rc!=SQLITE_OK ){
   71689       goto abort_due_to_error;
   71690     }
   71691     pC->rowidIsValid = 0;
   71692   }
   71693   pC->deferredMoveto = 0;
   71694   pC->cacheStatus = CACHE_STALE;
   71695 #ifdef SQLITE_TEST
   71696   sqlite3_search_count++;
   71697 #endif
   71698   if( oc>=OP_SeekGE ){  assert( oc==OP_SeekGE || oc==OP_SeekGT );
   71699     if( res<0 || (res==0 && oc==OP_SeekGT) ){
   71700       res = 0;
   71701       rc = sqlite3BtreeNext(pC->pCursor, &res);
   71702       if( rc!=SQLITE_OK ) goto abort_due_to_error;
   71703       pC->rowidIsValid = 0;
   71704     }else{
   71705       res = 0;
   71706     }
   71707   }else{
   71708     assert( oc==OP_SeekLT || oc==OP_SeekLE );
   71709     if( res>0 || (res==0 && oc==OP_SeekLT) ){
   71710       res = 0;
   71711       rc = sqlite3BtreePrevious(pC->pCursor, &res);
   71712       if( rc!=SQLITE_OK ) goto abort_due_to_error;
   71713       pC->rowidIsValid = 0;
   71714     }else{
   71715       /* res might be negative because the table is empty.  Check to
   71716       ** see if this is the case.
   71717       */
   71718       res = sqlite3BtreeEof(pC->pCursor);
   71719     }
   71720   }
   71721   assert( pOp->p2>0 );
   71722   VdbeBranchTaken(res!=0,2);
   71723   if( res ){
   71724     pc = pOp->p2 - 1;
   71725   }
   71726   break;
   71727 }
   71728 
   71729 /* Opcode: Seek P1 P2 * * *
   71730 ** Synopsis:  intkey=r[P2]
   71731 **
   71732 ** P1 is an open table cursor and P2 is a rowid integer.  Arrange
   71733 ** for P1 to move so that it points to the rowid given by P2.
   71734 **
   71735 ** This is actually a deferred seek.  Nothing actually happens until
   71736 ** the cursor is used to read a record.  That way, if no reads
   71737 ** occur, no unnecessary I/O happens.
   71738 */
   71739 case OP_Seek: {    /* in2 */
   71740   VdbeCursor *pC;
   71741 
   71742   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   71743   pC = p->apCsr[pOp->p1];
   71744   assert( pC!=0 );
   71745   assert( pC->pCursor!=0 );
   71746   assert( pC->isTable );
   71747   pC->nullRow = 0;
   71748   pIn2 = &aMem[pOp->p2];
   71749   pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
   71750   pC->rowidIsValid = 0;
   71751   pC->deferredMoveto = 1;
   71752   break;
   71753 }
   71754 
   71755 
   71756 /* Opcode: Found P1 P2 P3 P4 *
   71757 ** Synopsis: key=r[P3@P4]
   71758 **
   71759 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
   71760 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
   71761 ** record.
   71762 **
   71763 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
   71764 ** is a prefix of any entry in P1 then a jump is made to P2 and
   71765 ** P1 is left pointing at the matching entry.
   71766 **
   71767 ** This operation leaves the cursor in a state where it can be
   71768 ** advanced in the forward direction.  The Next instruction will work,
   71769 ** but not the Prev instruction.
   71770 **
   71771 ** See also: NotFound, NoConflict, NotExists. SeekGe
   71772 */
   71773 /* Opcode: NotFound P1 P2 P3 P4 *
   71774 ** Synopsis: key=r[P3@P4]
   71775 **
   71776 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
   71777 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
   71778 ** record.
   71779 **
   71780 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
   71781 ** is not the prefix of any entry in P1 then a jump is made to P2.  If P1
   71782 ** does contain an entry whose prefix matches the P3/P4 record then control
   71783 ** falls through to the next instruction and P1 is left pointing at the
   71784 ** matching entry.
   71785 **
   71786 ** This operation leaves the cursor in a state where it cannot be
   71787 ** advanced in either direction.  In other words, the Next and Prev
   71788 ** opcodes do not work after this operation.
   71789 **
   71790 ** See also: Found, NotExists, NoConflict
   71791 */
   71792 /* Opcode: NoConflict P1 P2 P3 P4 *
   71793 ** Synopsis: key=r[P3@P4]
   71794 **
   71795 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
   71796 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
   71797 ** record.
   71798 **
   71799 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
   71800 ** contains any NULL value, jump immediately to P2.  If all terms of the
   71801 ** record are not-NULL then a check is done to determine if any row in the
   71802 ** P1 index btree has a matching key prefix.  If there are no matches, jump
   71803 ** immediately to P2.  If there is a match, fall through and leave the P1
   71804 ** cursor pointing to the matching row.
   71805 **
   71806 ** This opcode is similar to OP_NotFound with the exceptions that the
   71807 ** branch is always taken if any part of the search key input is NULL.
   71808 **
   71809 ** This operation leaves the cursor in a state where it cannot be
   71810 ** advanced in either direction.  In other words, the Next and Prev
   71811 ** opcodes do not work after this operation.
   71812 **
   71813 ** See also: NotFound, Found, NotExists
   71814 */
   71815 case OP_NoConflict:     /* jump, in3 */
   71816 case OP_NotFound:       /* jump, in3 */
   71817 case OP_Found: {        /* jump, in3 */
   71818   int alreadyExists;
   71819   int ii;
   71820   VdbeCursor *pC;
   71821   int res;
   71822   char *pFree;
   71823   UnpackedRecord *pIdxKey;
   71824   UnpackedRecord r;
   71825   char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*4 + 7];
   71826 
   71827 #ifdef SQLITE_TEST
   71828   if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
   71829 #endif
   71830 
   71831   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   71832   assert( pOp->p4type==P4_INT32 );
   71833   pC = p->apCsr[pOp->p1];
   71834   assert( pC!=0 );
   71835 #ifdef SQLITE_DEBUG
   71836   pC->seekOp = pOp->opcode;
   71837 #endif
   71838   pIn3 = &aMem[pOp->p3];
   71839   assert( pC->pCursor!=0 );
   71840   assert( pC->isTable==0 );
   71841   pFree = 0;  /* Not needed.  Only used to suppress a compiler warning. */
   71842   if( pOp->p4.i>0 ){
   71843     r.pKeyInfo = pC->pKeyInfo;
   71844     r.nField = (u16)pOp->p4.i;
   71845     r.aMem = pIn3;
   71846     for(ii=0; ii<r.nField; ii++){
   71847       assert( memIsValid(&r.aMem[ii]) );
   71848       ExpandBlob(&r.aMem[ii]);
   71849 #ifdef SQLITE_DEBUG
   71850       if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
   71851 #endif
   71852     }
   71853     pIdxKey = &r;
   71854   }else{
   71855     pIdxKey = sqlite3VdbeAllocUnpackedRecord(
   71856         pC->pKeyInfo, aTempRec, sizeof(aTempRec), &pFree
   71857     );
   71858     if( pIdxKey==0 ) goto no_mem;
   71859     assert( pIn3->flags & MEM_Blob );
   71860     assert( (pIn3->flags & MEM_Zero)==0 );  /* zeroblobs already expanded */
   71861     sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
   71862   }
   71863   pIdxKey->default_rc = 0;
   71864   if( pOp->opcode==OP_NoConflict ){
   71865     /* For the OP_NoConflict opcode, take the jump if any of the
   71866     ** input fields are NULL, since any key with a NULL will not
   71867     ** conflict */
   71868     for(ii=0; ii<r.nField; ii++){
   71869       if( r.aMem[ii].flags & MEM_Null ){
   71870         pc = pOp->p2 - 1; VdbeBranchTaken(1,2);
   71871         break;
   71872       }
   71873     }
   71874   }
   71875   rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, pIdxKey, 0, 0, &res);
   71876   if( pOp->p4.i==0 ){
   71877     sqlite3DbFree(db, pFree);
   71878   }
   71879   if( rc!=SQLITE_OK ){
   71880     break;
   71881   }
   71882   pC->seekResult = res;
   71883   alreadyExists = (res==0);
   71884   pC->nullRow = 1-alreadyExists;
   71885   pC->deferredMoveto = 0;
   71886   pC->cacheStatus = CACHE_STALE;
   71887   if( pOp->opcode==OP_Found ){
   71888     VdbeBranchTaken(alreadyExists!=0,2);
   71889     if( alreadyExists ) pc = pOp->p2 - 1;
   71890   }else{
   71891     VdbeBranchTaken(alreadyExists==0,2);
   71892     if( !alreadyExists ) pc = pOp->p2 - 1;
   71893   }
   71894   break;
   71895 }
   71896 
   71897 /* Opcode: NotExists P1 P2 P3 * *
   71898 ** Synopsis: intkey=r[P3]
   71899 **
   71900 ** P1 is the index of a cursor open on an SQL table btree (with integer
   71901 ** keys).  P3 is an integer rowid.  If P1 does not contain a record with
   71902 ** rowid P3 then jump immediately to P2.  If P1 does contain a record
   71903 ** with rowid P3 then leave the cursor pointing at that record and fall
   71904 ** through to the next instruction.
   71905 **
   71906 ** The OP_NotFound opcode performs the same operation on index btrees
   71907 ** (with arbitrary multi-value keys).
   71908 **
   71909 ** This opcode leaves the cursor in a state where it cannot be advanced
   71910 ** in either direction.  In other words, the Next and Prev opcodes will
   71911 ** not work following this opcode.
   71912 **
   71913 ** See also: Found, NotFound, NoConflict
   71914 */
   71915 case OP_NotExists: {        /* jump, in3 */
   71916   VdbeCursor *pC;
   71917   BtCursor *pCrsr;
   71918   int res;
   71919   u64 iKey;
   71920 
   71921   pIn3 = &aMem[pOp->p3];
   71922   assert( pIn3->flags & MEM_Int );
   71923   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   71924   pC = p->apCsr[pOp->p1];
   71925   assert( pC!=0 );
   71926 #ifdef SQLITE_DEBUG
   71927   pC->seekOp = 0;
   71928 #endif
   71929   assert( pC->isTable );
   71930   assert( pC->pseudoTableReg==0 );
   71931   pCrsr = pC->pCursor;
   71932   assert( pCrsr!=0 );
   71933   res = 0;
   71934   iKey = pIn3->u.i;
   71935   rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
   71936   pC->lastRowid = pIn3->u.i;
   71937   pC->rowidIsValid = res==0 ?1:0;
   71938   pC->nullRow = 0;
   71939   pC->cacheStatus = CACHE_STALE;
   71940   pC->deferredMoveto = 0;
   71941   VdbeBranchTaken(res!=0,2);
   71942   if( res!=0 ){
   71943     pc = pOp->p2 - 1;
   71944     assert( pC->rowidIsValid==0 );
   71945   }
   71946   pC->seekResult = res;
   71947   break;
   71948 }
   71949 
   71950 /* Opcode: Sequence P1 P2 * * *
   71951 ** Synopsis: r[P2]=cursor[P1].ctr++
   71952 **
   71953 ** Find the next available sequence number for cursor P1.
   71954 ** Write the sequence number into register P2.
   71955 ** The sequence number on the cursor is incremented after this
   71956 ** instruction.
   71957 */
   71958 case OP_Sequence: {           /* out2-prerelease */
   71959   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   71960   assert( p->apCsr[pOp->p1]!=0 );
   71961   pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
   71962   break;
   71963 }
   71964 
   71965 
   71966 /* Opcode: NewRowid P1 P2 P3 * *
   71967 ** Synopsis: r[P2]=rowid
   71968 **
   71969 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
   71970 ** The record number is not previously used as a key in the database
   71971 ** table that cursor P1 points to.  The new record number is written
   71972 ** written to register P2.
   71973 **
   71974 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
   71975 ** the largest previously generated record number. No new record numbers are
   71976 ** allowed to be less than this value. When this value reaches its maximum,
   71977 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
   71978 ** generated record number. This P3 mechanism is used to help implement the
   71979 ** AUTOINCREMENT feature.
   71980 */
   71981 case OP_NewRowid: {           /* out2-prerelease */
   71982   i64 v;                 /* The new rowid */
   71983   VdbeCursor *pC;        /* Cursor of table to get the new rowid */
   71984   int res;               /* Result of an sqlite3BtreeLast() */
   71985   int cnt;               /* Counter to limit the number of searches */
   71986   Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
   71987   VdbeFrame *pFrame;     /* Root frame of VDBE */
   71988 
   71989   v = 0;
   71990   res = 0;
   71991   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   71992   pC = p->apCsr[pOp->p1];
   71993   assert( pC!=0 );
   71994   if( NEVER(pC->pCursor==0) ){
   71995     /* The zero initialization above is all that is needed */
   71996   }else{
   71997     /* The next rowid or record number (different terms for the same
   71998     ** thing) is obtained in a two-step algorithm.
   71999     **
   72000     ** First we attempt to find the largest existing rowid and add one
   72001     ** to that.  But if the largest existing rowid is already the maximum
   72002     ** positive integer, we have to fall through to the second
   72003     ** probabilistic algorithm
   72004     **
   72005     ** The second algorithm is to select a rowid at random and see if
   72006     ** it already exists in the table.  If it does not exist, we have
   72007     ** succeeded.  If the random rowid does exist, we select a new one
   72008     ** and try again, up to 100 times.
   72009     */
   72010     assert( pC->isTable );
   72011 
   72012 #ifdef SQLITE_32BIT_ROWID
   72013 #   define MAX_ROWID 0x7fffffff
   72014 #else
   72015     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
   72016     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
   72017     ** to provide the constant while making all compilers happy.
   72018     */
   72019 #   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
   72020 #endif
   72021 
   72022     if( !pC->useRandomRowid ){
   72023       rc = sqlite3BtreeLast(pC->pCursor, &res);
   72024       if( rc!=SQLITE_OK ){
   72025         goto abort_due_to_error;
   72026       }
   72027       if( res ){
   72028         v = 1;   /* IMP: R-61914-48074 */
   72029       }else{
   72030         assert( sqlite3BtreeCursorIsValid(pC->pCursor) );
   72031         rc = sqlite3BtreeKeySize(pC->pCursor, &v);
   72032         assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
   72033         if( v>=MAX_ROWID ){
   72034           pC->useRandomRowid = 1;
   72035         }else{
   72036           v++;   /* IMP: R-29538-34987 */
   72037         }
   72038       }
   72039     }
   72040 
   72041 #ifndef SQLITE_OMIT_AUTOINCREMENT
   72042     if( pOp->p3 ){
   72043       /* Assert that P3 is a valid memory cell. */
   72044       assert( pOp->p3>0 );
   72045       if( p->pFrame ){
   72046         for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
   72047         /* Assert that P3 is a valid memory cell. */
   72048         assert( pOp->p3<=pFrame->nMem );
   72049         pMem = &pFrame->aMem[pOp->p3];
   72050       }else{
   72051         /* Assert that P3 is a valid memory cell. */
   72052         assert( pOp->p3<=(p->nMem-p->nCursor) );
   72053         pMem = &aMem[pOp->p3];
   72054         memAboutToChange(p, pMem);
   72055       }
   72056       assert( memIsValid(pMem) );
   72057 
   72058       REGISTER_TRACE(pOp->p3, pMem);
   72059       sqlite3VdbeMemIntegerify(pMem);
   72060       assert( (pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
   72061       if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
   72062         rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
   72063         goto abort_due_to_error;
   72064       }
   72065       if( v<pMem->u.i+1 ){
   72066         v = pMem->u.i + 1;
   72067       }
   72068       pMem->u.i = v;
   72069     }
   72070 #endif
   72071     if( pC->useRandomRowid ){
   72072       /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
   72073       ** largest possible integer (9223372036854775807) then the database
   72074       ** engine starts picking positive candidate ROWIDs at random until
   72075       ** it finds one that is not previously used. */
   72076       assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
   72077                              ** an AUTOINCREMENT table. */
   72078       /* on the first attempt, simply do one more than previous */
   72079       v = lastRowid;
   72080       v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
   72081       v++; /* ensure non-zero */
   72082       cnt = 0;
   72083       while(   ((rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)v,
   72084                                                  0, &res))==SQLITE_OK)
   72085             && (res==0)
   72086             && (++cnt<100)){
   72087         /* collision - try another random rowid */
   72088         sqlite3_randomness(sizeof(v), &v);
   72089         if( cnt<5 ){
   72090           /* try "small" random rowids for the initial attempts */
   72091           v &= 0xffffff;
   72092         }else{
   72093           v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
   72094         }
   72095         v++; /* ensure non-zero */
   72096       }
   72097       if( rc==SQLITE_OK && res==0 ){
   72098         rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
   72099         goto abort_due_to_error;
   72100       }
   72101       assert( v>0 );  /* EV: R-40812-03570 */
   72102     }
   72103     pC->rowidIsValid = 0;
   72104     pC->deferredMoveto = 0;
   72105     pC->cacheStatus = CACHE_STALE;
   72106   }
   72107   pOut->u.i = v;
   72108   break;
   72109 }
   72110 
   72111 /* Opcode: Insert P1 P2 P3 P4 P5
   72112 ** Synopsis: intkey=r[P3] data=r[P2]
   72113 **
   72114 ** Write an entry into the table of cursor P1.  A new entry is
   72115 ** created if it doesn't already exist or the data for an existing
   72116 ** entry is overwritten.  The data is the value MEM_Blob stored in register
   72117 ** number P2. The key is stored in register P3. The key must
   72118 ** be a MEM_Int.
   72119 **
   72120 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
   72121 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
   72122 ** then rowid is stored for subsequent return by the
   72123 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
   72124 **
   72125 ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
   72126 ** the last seek operation (OP_NotExists) was a success, then this
   72127 ** operation will not attempt to find the appropriate row before doing
   72128 ** the insert but will instead overwrite the row that the cursor is
   72129 ** currently pointing to.  Presumably, the prior OP_NotExists opcode
   72130 ** has already positioned the cursor correctly.  This is an optimization
   72131 ** that boosts performance by avoiding redundant seeks.
   72132 **
   72133 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
   72134 ** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
   72135 ** is part of an INSERT operation.  The difference is only important to
   72136 ** the update hook.
   72137 **
   72138 ** Parameter P4 may point to a string containing the table-name, or
   72139 ** may be NULL. If it is not NULL, then the update-hook
   72140 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
   72141 **
   72142 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
   72143 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
   72144 ** and register P2 becomes ephemeral.  If the cursor is changed, the
   72145 ** value of register P2 will then change.  Make sure this does not
   72146 ** cause any problems.)
   72147 **
   72148 ** This instruction only works on tables.  The equivalent instruction
   72149 ** for indices is OP_IdxInsert.
   72150 */
   72151 /* Opcode: InsertInt P1 P2 P3 P4 P5
   72152 ** Synopsis:  intkey=P3 data=r[P2]
   72153 **
   72154 ** This works exactly like OP_Insert except that the key is the
   72155 ** integer value P3, not the value of the integer stored in register P3.
   72156 */
   72157 case OP_Insert:
   72158 case OP_InsertInt: {
   72159   Mem *pData;       /* MEM cell holding data for the record to be inserted */
   72160   Mem *pKey;        /* MEM cell holding key  for the record */
   72161   i64 iKey;         /* The integer ROWID or key for the record to be inserted */
   72162   VdbeCursor *pC;   /* Cursor to table into which insert is written */
   72163   int nZero;        /* Number of zero-bytes to append */
   72164   int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
   72165   const char *zDb;  /* database name - used by the update hook */
   72166   const char *zTbl; /* Table name - used by the opdate hook */
   72167   int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
   72168 
   72169   pData = &aMem[pOp->p2];
   72170   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   72171   assert( memIsValid(pData) );
   72172   pC = p->apCsr[pOp->p1];
   72173   assert( pC!=0 );
   72174   assert( pC->pCursor!=0 );
   72175   assert( pC->pseudoTableReg==0 );
   72176   assert( pC->isTable );
   72177   REGISTER_TRACE(pOp->p2, pData);
   72178 
   72179   if( pOp->opcode==OP_Insert ){
   72180     pKey = &aMem[pOp->p3];
   72181     assert( pKey->flags & MEM_Int );
   72182     assert( memIsValid(pKey) );
   72183     REGISTER_TRACE(pOp->p3, pKey);
   72184     iKey = pKey->u.i;
   72185   }else{
   72186     assert( pOp->opcode==OP_InsertInt );
   72187     iKey = pOp->p3;
   72188   }
   72189 
   72190   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
   72191   if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = iKey;
   72192   if( pData->flags & MEM_Null ){
   72193     pData->z = 0;
   72194     pData->n = 0;
   72195   }else{
   72196     assert( pData->flags & (MEM_Blob|MEM_Str) );
   72197   }
   72198   seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
   72199   if( pData->flags & MEM_Zero ){
   72200     nZero = pData->u.nZero;
   72201   }else{
   72202     nZero = 0;
   72203   }
   72204   rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey,
   72205                           pData->z, pData->n, nZero,
   72206                           (pOp->p5 & OPFLAG_APPEND)!=0, seekResult
   72207   );
   72208   pC->rowidIsValid = 0;
   72209   pC->deferredMoveto = 0;
   72210   pC->cacheStatus = CACHE_STALE;
   72211 
   72212   /* Invoke the update-hook if required. */
   72213   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
   72214     zDb = db->aDb[pC->iDb].zName;
   72215     zTbl = pOp->p4.z;
   72216     op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
   72217     assert( pC->isTable );
   72218     db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
   72219     assert( pC->iDb>=0 );
   72220   }
   72221   break;
   72222 }
   72223 
   72224 /* Opcode: Delete P1 P2 * P4 *
   72225 **
   72226 ** Delete the record at which the P1 cursor is currently pointing.
   72227 **
   72228 ** The cursor will be left pointing at either the next or the previous
   72229 ** record in the table. If it is left pointing at the next record, then
   72230 ** the next Next instruction will be a no-op.  Hence it is OK to delete
   72231 ** a record from within a Next loop.
   72232 **
   72233 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
   72234 ** incremented (otherwise not).
   72235 **
   72236 ** P1 must not be pseudo-table.  It has to be a real table with
   72237 ** multiple rows.
   72238 **
   72239 ** If P4 is not NULL, then it is the name of the table that P1 is
   72240 ** pointing to.  The update hook will be invoked, if it exists.
   72241 ** If P4 is not NULL then the P1 cursor must have been positioned
   72242 ** using OP_NotFound prior to invoking this opcode.
   72243 */
   72244 case OP_Delete: {
   72245   i64 iKey;
   72246   VdbeCursor *pC;
   72247 
   72248   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   72249   pC = p->apCsr[pOp->p1];
   72250   assert( pC!=0 );
   72251   assert( pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
   72252   iKey = pC->lastRowid;      /* Only used for the update hook */
   72253 
   72254   /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
   72255   ** OP_Column on the same table without any intervening operations that
   72256   ** might move or invalidate the cursor.  Hence cursor pC is always pointing
   72257   ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
   72258   ** below is always a no-op and cannot fail.  We will run it anyhow, though,
   72259   ** to guard against future changes to the code generator.
   72260   **/
   72261   assert( pC->deferredMoveto==0 );
   72262   rc = sqlite3VdbeCursorMoveto(pC);
   72263   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
   72264 
   72265   rc = sqlite3BtreeDelete(pC->pCursor);
   72266   pC->cacheStatus = CACHE_STALE;
   72267 
   72268   /* Invoke the update-hook if required. */
   72269   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z && pC->isTable ){
   72270     db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE,
   72271                         db->aDb[pC->iDb].zName, pOp->p4.z, iKey);
   72272     assert( pC->iDb>=0 );
   72273   }
   72274   if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
   72275   break;
   72276 }
   72277 /* Opcode: ResetCount * * * * *
   72278 **
   72279 ** The value of the change counter is copied to the database handle
   72280 ** change counter (returned by subsequent calls to sqlite3_changes()).
   72281 ** Then the VMs internal change counter resets to 0.
   72282 ** This is used by trigger programs.
   72283 */
   72284 case OP_ResetCount: {
   72285   sqlite3VdbeSetChanges(db, p->nChange);
   72286   p->nChange = 0;
   72287   break;
   72288 }
   72289 
   72290 /* Opcode: SorterCompare P1 P2 P3 P4
   72291 ** Synopsis:  if key(P1)!=trim(r[P3],P4) goto P2
   72292 **
   72293 ** P1 is a sorter cursor. This instruction compares a prefix of the
   72294 ** record blob in register P3 against a prefix of the entry that
   72295 ** the sorter cursor currently points to.  Only the first P4 fields
   72296 ** of r[P3] and the sorter record are compared.
   72297 **
   72298 ** If either P3 or the sorter contains a NULL in one of their significant
   72299 ** fields (not counting the P4 fields at the end which are ignored) then
   72300 ** the comparison is assumed to be equal.
   72301 **
   72302 ** Fall through to next instruction if the two records compare equal to
   72303 ** each other.  Jump to P2 if they are different.
   72304 */
   72305 case OP_SorterCompare: {
   72306   VdbeCursor *pC;
   72307   int res;
   72308   int nKeyCol;
   72309 
   72310   pC = p->apCsr[pOp->p1];
   72311   assert( isSorter(pC) );
   72312   assert( pOp->p4type==P4_INT32 );
   72313   pIn3 = &aMem[pOp->p3];
   72314   nKeyCol = pOp->p4.i;
   72315   rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
   72316   VdbeBranchTaken(res!=0,2);
   72317   if( res ){
   72318     pc = pOp->p2-1;
   72319   }
   72320   break;
   72321 };
   72322 
   72323 /* Opcode: SorterData P1 P2 * * *
   72324 ** Synopsis: r[P2]=data
   72325 **
   72326 ** Write into register P2 the current sorter data for sorter cursor P1.
   72327 */
   72328 case OP_SorterData: {
   72329   VdbeCursor *pC;
   72330 
   72331   pOut = &aMem[pOp->p2];
   72332   pC = p->apCsr[pOp->p1];
   72333   assert( isSorter(pC) );
   72334   rc = sqlite3VdbeSorterRowkey(pC, pOut);
   72335   assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
   72336   break;
   72337 }
   72338 
   72339 /* Opcode: RowData P1 P2 * * *
   72340 ** Synopsis: r[P2]=data
   72341 **
   72342 ** Write into register P2 the complete row data for cursor P1.
   72343 ** There is no interpretation of the data.
   72344 ** It is just copied onto the P2 register exactly as
   72345 ** it is found in the database file.
   72346 **
   72347 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
   72348 ** of a real table, not a pseudo-table.
   72349 */
   72350 /* Opcode: RowKey P1 P2 * * *
   72351 ** Synopsis: r[P2]=key
   72352 **
   72353 ** Write into register P2 the complete row key for cursor P1.
   72354 ** There is no interpretation of the data.
   72355 ** The key is copied onto the P2 register exactly as
   72356 ** it is found in the database file.
   72357 **
   72358 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
   72359 ** of a real table, not a pseudo-table.
   72360 */
   72361 case OP_RowKey:
   72362 case OP_RowData: {
   72363   VdbeCursor *pC;
   72364   BtCursor *pCrsr;
   72365   u32 n;
   72366   i64 n64;
   72367 
   72368   pOut = &aMem[pOp->p2];
   72369   memAboutToChange(p, pOut);
   72370 
   72371   /* Note that RowKey and RowData are really exactly the same instruction */
   72372   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   72373   pC = p->apCsr[pOp->p1];
   72374   assert( isSorter(pC)==0 );
   72375   assert( pC->isTable || pOp->opcode!=OP_RowData );
   72376   assert( pC->isTable==0 || pOp->opcode==OP_RowData );
   72377   assert( pC!=0 );
   72378   assert( pC->nullRow==0 );
   72379   assert( pC->pseudoTableReg==0 );
   72380   assert( pC->pCursor!=0 );
   72381   pCrsr = pC->pCursor;
   72382   assert( sqlite3BtreeCursorIsValid(pCrsr) );
   72383 
   72384   /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
   72385   ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
   72386   ** the cursor.  Hence the following sqlite3VdbeCursorMoveto() call is always
   72387   ** a no-op and can never fail.  But we leave it in place as a safety.
   72388   */
   72389   assert( pC->deferredMoveto==0 );
   72390   rc = sqlite3VdbeCursorMoveto(pC);
   72391   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
   72392 
   72393   if( pC->isTable==0 ){
   72394     assert( !pC->isTable );
   72395     VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &n64);
   72396     assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */
   72397     if( n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   72398       goto too_big;
   72399     }
   72400     n = (u32)n64;
   72401   }else{
   72402     VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &n);
   72403     assert( rc==SQLITE_OK );    /* DataSize() cannot fail */
   72404     if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
   72405       goto too_big;
   72406     }
   72407   }
   72408   if( sqlite3VdbeMemGrow(pOut, n, 0) ){
   72409     goto no_mem;
   72410   }
   72411   pOut->n = n;
   72412   MemSetTypeFlag(pOut, MEM_Blob);
   72413   if( pC->isTable==0 ){
   72414     rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z);
   72415   }else{
   72416     rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z);
   72417   }
   72418   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
   72419   UPDATE_MAX_BLOBSIZE(pOut);
   72420   REGISTER_TRACE(pOp->p2, pOut);
   72421   break;
   72422 }
   72423 
   72424 /* Opcode: Rowid P1 P2 * * *
   72425 ** Synopsis: r[P2]=rowid
   72426 **
   72427 ** Store in register P2 an integer which is the key of the table entry that
   72428 ** P1 is currently point to.
   72429 **
   72430 ** P1 can be either an ordinary table or a virtual table.  There used to
   72431 ** be a separate OP_VRowid opcode for use with virtual tables, but this
   72432 ** one opcode now works for both table types.
   72433 */
   72434 case OP_Rowid: {                 /* out2-prerelease */
   72435   VdbeCursor *pC;
   72436   i64 v;
   72437   sqlite3_vtab *pVtab;
   72438   const sqlite3_module *pModule;
   72439 
   72440   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   72441   pC = p->apCsr[pOp->p1];
   72442   assert( pC!=0 );
   72443   assert( pC->pseudoTableReg==0 || pC->nullRow );
   72444   if( pC->nullRow ){
   72445     pOut->flags = MEM_Null;
   72446     break;
   72447   }else if( pC->deferredMoveto ){
   72448     v = pC->movetoTarget;
   72449 #ifndef SQLITE_OMIT_VIRTUALTABLE
   72450   }else if( pC->pVtabCursor ){
   72451     pVtab = pC->pVtabCursor->pVtab;
   72452     pModule = pVtab->pModule;
   72453     assert( pModule->xRowid );
   72454     rc = pModule->xRowid(pC->pVtabCursor, &v);
   72455     sqlite3VtabImportErrmsg(p, pVtab);
   72456 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   72457   }else{
   72458     assert( pC->pCursor!=0 );
   72459     rc = sqlite3VdbeCursorMoveto(pC);
   72460     if( rc ) goto abort_due_to_error;
   72461     if( pC->rowidIsValid ){
   72462       v = pC->lastRowid;
   72463     }else{
   72464       rc = sqlite3BtreeKeySize(pC->pCursor, &v);
   72465       assert( rc==SQLITE_OK );  /* Always so because of CursorMoveto() above */
   72466     }
   72467   }
   72468   pOut->u.i = v;
   72469   break;
   72470 }
   72471 
   72472 /* Opcode: NullRow P1 * * * *
   72473 **
   72474 ** Move the cursor P1 to a null row.  Any OP_Column operations
   72475 ** that occur while the cursor is on the null row will always
   72476 ** write a NULL.
   72477 */
   72478 case OP_NullRow: {
   72479   VdbeCursor *pC;
   72480 
   72481   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   72482   pC = p->apCsr[pOp->p1];
   72483   assert( pC!=0 );
   72484   pC->nullRow = 1;
   72485   pC->rowidIsValid = 0;
   72486   pC->cacheStatus = CACHE_STALE;
   72487   if( pC->pCursor ){
   72488     sqlite3BtreeClearCursor(pC->pCursor);
   72489   }
   72490   break;
   72491 }
   72492 
   72493 /* Opcode: Last P1 P2 * * *
   72494 **
   72495 ** The next use of the Rowid or Column or Prev instruction for P1
   72496 ** will refer to the last entry in the database table or index.
   72497 ** If the table or index is empty and P2>0, then jump immediately to P2.
   72498 ** If P2 is 0 or if the table or index is not empty, fall through
   72499 ** to the following instruction.
   72500 **
   72501 ** This opcode leaves the cursor configured to move in reverse order,
   72502 ** from the end toward the beginning.  In other words, the cursor is
   72503 ** configured to use Prev, not Next.
   72504 */
   72505 case OP_Last: {        /* jump */
   72506   VdbeCursor *pC;
   72507   BtCursor *pCrsr;
   72508   int res;
   72509 
   72510   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   72511   pC = p->apCsr[pOp->p1];
   72512   assert( pC!=0 );
   72513   pCrsr = pC->pCursor;
   72514   res = 0;
   72515   assert( pCrsr!=0 );
   72516   rc = sqlite3BtreeLast(pCrsr, &res);
   72517   pC->nullRow = (u8)res;
   72518   pC->deferredMoveto = 0;
   72519   pC->rowidIsValid = 0;
   72520   pC->cacheStatus = CACHE_STALE;
   72521 #ifdef SQLITE_DEBUG
   72522   pC->seekOp = OP_Last;
   72523 #endif
   72524   if( pOp->p2>0 ){
   72525     VdbeBranchTaken(res!=0,2);
   72526     if( res ) pc = pOp->p2 - 1;
   72527   }
   72528   break;
   72529 }
   72530 
   72531 
   72532 /* Opcode: Sort P1 P2 * * *
   72533 **
   72534 ** This opcode does exactly the same thing as OP_Rewind except that
   72535 ** it increments an undocumented global variable used for testing.
   72536 **
   72537 ** Sorting is accomplished by writing records into a sorting index,
   72538 ** then rewinding that index and playing it back from beginning to
   72539 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
   72540 ** rewinding so that the global variable will be incremented and
   72541 ** regression tests can determine whether or not the optimizer is
   72542 ** correctly optimizing out sorts.
   72543 */
   72544 case OP_SorterSort:    /* jump */
   72545 case OP_Sort: {        /* jump */
   72546 #ifdef SQLITE_TEST
   72547   sqlite3_sort_count++;
   72548   sqlite3_search_count--;
   72549 #endif
   72550   p->aCounter[SQLITE_STMTSTATUS_SORT]++;
   72551   /* Fall through into OP_Rewind */
   72552 }
   72553 /* Opcode: Rewind P1 P2 * * *
   72554 **
   72555 ** The next use of the Rowid or Column or Next instruction for P1
   72556 ** will refer to the first entry in the database table or index.
   72557 ** If the table or index is empty and P2>0, then jump immediately to P2.
   72558 ** If P2 is 0 or if the table or index is not empty, fall through
   72559 ** to the following instruction.
   72560 **
   72561 ** This opcode leaves the cursor configured to move in forward order,
   72562 ** from the beginning toward the end.  In other words, the cursor is
   72563 ** configured to use Next, not Prev.
   72564 */
   72565 case OP_Rewind: {        /* jump */
   72566   VdbeCursor *pC;
   72567   BtCursor *pCrsr;
   72568   int res;
   72569 
   72570   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   72571   pC = p->apCsr[pOp->p1];
   72572   assert( pC!=0 );
   72573   assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
   72574   res = 1;
   72575 #ifdef SQLITE_DEBUG
   72576   pC->seekOp = OP_Rewind;
   72577 #endif
   72578   if( isSorter(pC) ){
   72579     rc = sqlite3VdbeSorterRewind(db, pC, &res);
   72580   }else{
   72581     pCrsr = pC->pCursor;
   72582     assert( pCrsr );
   72583     rc = sqlite3BtreeFirst(pCrsr, &res);
   72584     pC->deferredMoveto = 0;
   72585     pC->cacheStatus = CACHE_STALE;
   72586     pC->rowidIsValid = 0;
   72587   }
   72588   pC->nullRow = (u8)res;
   72589   assert( pOp->p2>0 && pOp->p2<p->nOp );
   72590   VdbeBranchTaken(res!=0,2);
   72591   if( res ){
   72592     pc = pOp->p2 - 1;
   72593   }
   72594   break;
   72595 }
   72596 
   72597 /* Opcode: Next P1 P2 P3 P4 P5
   72598 **
   72599 ** Advance cursor P1 so that it points to the next key/data pair in its
   72600 ** table or index.  If there are no more key/value pairs then fall through
   72601 ** to the following instruction.  But if the cursor advance was successful,
   72602 ** jump immediately to P2.
   72603 **
   72604 ** The Next opcode is only valid following an SeekGT, SeekGE, or
   72605 ** OP_Rewind opcode used to position the cursor.  Next is not allowed
   72606 ** to follow SeekLT, SeekLE, or OP_Last.
   72607 **
   72608 ** The P1 cursor must be for a real table, not a pseudo-table.  P1 must have
   72609 ** been opened prior to this opcode or the program will segfault.
   72610 **
   72611 ** The P3 value is a hint to the btree implementation. If P3==1, that
   72612 ** means P1 is an SQL index and that this instruction could have been
   72613 ** omitted if that index had been unique.  P3 is usually 0.  P3 is
   72614 ** always either 0 or 1.
   72615 **
   72616 ** P4 is always of type P4_ADVANCE. The function pointer points to
   72617 ** sqlite3BtreeNext().
   72618 **
   72619 ** If P5 is positive and the jump is taken, then event counter
   72620 ** number P5-1 in the prepared statement is incremented.
   72621 **
   72622 ** See also: Prev, NextIfOpen
   72623 */
   72624 /* Opcode: NextIfOpen P1 P2 P3 P4 P5
   72625 **
   72626 ** This opcode works just like Next except that if cursor P1 is not
   72627 ** open it behaves a no-op.
   72628 */
   72629 /* Opcode: Prev P1 P2 P3 P4 P5
   72630 **
   72631 ** Back up cursor P1 so that it points to the previous key/data pair in its
   72632 ** table or index.  If there is no previous key/value pairs then fall through
   72633 ** to the following instruction.  But if the cursor backup was successful,
   72634 ** jump immediately to P2.
   72635 **
   72636 **
   72637 ** The Prev opcode is only valid following an SeekLT, SeekLE, or
   72638 ** OP_Last opcode used to position the cursor.  Prev is not allowed
   72639 ** to follow SeekGT, SeekGE, or OP_Rewind.
   72640 **
   72641 ** The P1 cursor must be for a real table, not a pseudo-table.  If P1 is
   72642 ** not open then the behavior is undefined.
   72643 **
   72644 ** The P3 value is a hint to the btree implementation. If P3==1, that
   72645 ** means P1 is an SQL index and that this instruction could have been
   72646 ** omitted if that index had been unique.  P3 is usually 0.  P3 is
   72647 ** always either 0 or 1.
   72648 **
   72649 ** P4 is always of type P4_ADVANCE. The function pointer points to
   72650 ** sqlite3BtreePrevious().
   72651 **
   72652 ** If P5 is positive and the jump is taken, then event counter
   72653 ** number P5-1 in the prepared statement is incremented.
   72654 */
   72655 /* Opcode: PrevIfOpen P1 P2 P3 P4 P5
   72656 **
   72657 ** This opcode works just like Prev except that if cursor P1 is not
   72658 ** open it behaves a no-op.
   72659 */
   72660 case OP_SorterNext: {  /* jump */
   72661   VdbeCursor *pC;
   72662   int res;
   72663 
   72664   pC = p->apCsr[pOp->p1];
   72665   assert( isSorter(pC) );
   72666   res = 0;
   72667   rc = sqlite3VdbeSorterNext(db, pC, &res);
   72668   goto next_tail;
   72669 case OP_PrevIfOpen:    /* jump */
   72670 case OP_NextIfOpen:    /* jump */
   72671   if( p->apCsr[pOp->p1]==0 ) break;
   72672   /* Fall through */
   72673 case OP_Prev:          /* jump */
   72674 case OP_Next:          /* jump */
   72675   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   72676   assert( pOp->p5<ArraySize(p->aCounter) );
   72677   pC = p->apCsr[pOp->p1];
   72678   res = pOp->p3;
   72679   assert( pC!=0 );
   72680   assert( pC->deferredMoveto==0 );
   72681   assert( pC->pCursor );
   72682   assert( res==0 || (res==1 && pC->isTable==0) );
   72683   testcase( res==1 );
   72684   assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
   72685   assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
   72686   assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext );
   72687   assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious);
   72688 
   72689   /* The Next opcode is only used after SeekGT, SeekGE, and Rewind.
   72690   ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
   72691   assert( pOp->opcode!=OP_Next || pOp->opcode!=OP_NextIfOpen
   72692        || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
   72693        || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found);
   72694   assert( pOp->opcode!=OP_Prev || pOp->opcode!=OP_PrevIfOpen
   72695        || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
   72696        || pC->seekOp==OP_Last );
   72697 
   72698   rc = pOp->p4.xAdvance(pC->pCursor, &res);
   72699 next_tail:
   72700   pC->cacheStatus = CACHE_STALE;
   72701   VdbeBranchTaken(res==0,2);
   72702   if( res==0 ){
   72703     pC->nullRow = 0;
   72704     pc = pOp->p2 - 1;
   72705     p->aCounter[pOp->p5]++;
   72706 #ifdef SQLITE_TEST
   72707     sqlite3_search_count++;
   72708 #endif
   72709   }else{
   72710     pC->nullRow = 1;
   72711   }
   72712   pC->rowidIsValid = 0;
   72713   goto check_for_interrupt;
   72714 }
   72715 
   72716 /* Opcode: IdxInsert P1 P2 P3 * P5
   72717 ** Synopsis: key=r[P2]
   72718 **
   72719 ** Register P2 holds an SQL index key made using the
   72720 ** MakeRecord instructions.  This opcode writes that key
   72721 ** into the index P1.  Data for the entry is nil.
   72722 **
   72723 ** P3 is a flag that provides a hint to the b-tree layer that this
   72724 ** insert is likely to be an append.
   72725 **
   72726 ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
   72727 ** incremented by this instruction.  If the OPFLAG_NCHANGE bit is clear,
   72728 ** then the change counter is unchanged.
   72729 **
   72730 ** If P5 has the OPFLAG_USESEEKRESULT bit set, then the cursor must have
   72731 ** just done a seek to the spot where the new entry is to be inserted.
   72732 ** This flag avoids doing an extra seek.
   72733 **
   72734 ** This instruction only works for indices.  The equivalent instruction
   72735 ** for tables is OP_Insert.
   72736 */
   72737 case OP_SorterInsert:       /* in2 */
   72738 case OP_IdxInsert: {        /* in2 */
   72739   VdbeCursor *pC;
   72740   BtCursor *pCrsr;
   72741   int nKey;
   72742   const char *zKey;
   72743 
   72744   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   72745   pC = p->apCsr[pOp->p1];
   72746   assert( pC!=0 );
   72747   assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
   72748   pIn2 = &aMem[pOp->p2];
   72749   assert( pIn2->flags & MEM_Blob );
   72750   pCrsr = pC->pCursor;
   72751   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
   72752   assert( pCrsr!=0 );
   72753   assert( pC->isTable==0 );
   72754   rc = ExpandBlob(pIn2);
   72755   if( rc==SQLITE_OK ){
   72756     if( isSorter(pC) ){
   72757       rc = sqlite3VdbeSorterWrite(db, pC, pIn2);
   72758     }else{
   72759       nKey = pIn2->n;
   72760       zKey = pIn2->z;
   72761       rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p3,
   72762           ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
   72763           );
   72764       assert( pC->deferredMoveto==0 );
   72765       pC->cacheStatus = CACHE_STALE;
   72766     }
   72767   }
   72768   break;
   72769 }
   72770 
   72771 /* Opcode: IdxDelete P1 P2 P3 * *
   72772 ** Synopsis: key=r[P2@P3]
   72773 **
   72774 ** The content of P3 registers starting at register P2 form
   72775 ** an unpacked index key. This opcode removes that entry from the
   72776 ** index opened by cursor P1.
   72777 */
   72778 case OP_IdxDelete: {
   72779   VdbeCursor *pC;
   72780   BtCursor *pCrsr;
   72781   int res;
   72782   UnpackedRecord r;
   72783 
   72784   assert( pOp->p3>0 );
   72785   assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem-p->nCursor)+1 );
   72786   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   72787   pC = p->apCsr[pOp->p1];
   72788   assert( pC!=0 );
   72789   pCrsr = pC->pCursor;
   72790   assert( pCrsr!=0 );
   72791   assert( pOp->p5==0 );
   72792   r.pKeyInfo = pC->pKeyInfo;
   72793   r.nField = (u16)pOp->p3;
   72794   r.default_rc = 0;
   72795   r.aMem = &aMem[pOp->p2];
   72796 #ifdef SQLITE_DEBUG
   72797   { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
   72798 #endif
   72799   rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
   72800   if( rc==SQLITE_OK && res==0 ){
   72801     rc = sqlite3BtreeDelete(pCrsr);
   72802   }
   72803   assert( pC->deferredMoveto==0 );
   72804   pC->cacheStatus = CACHE_STALE;
   72805   break;
   72806 }
   72807 
   72808 /* Opcode: IdxRowid P1 P2 * * *
   72809 ** Synopsis: r[P2]=rowid
   72810 **
   72811 ** Write into register P2 an integer which is the last entry in the record at
   72812 ** the end of the index key pointed to by cursor P1.  This integer should be
   72813 ** the rowid of the table entry to which this index entry points.
   72814 **
   72815 ** See also: Rowid, MakeRecord.
   72816 */
   72817 case OP_IdxRowid: {              /* out2-prerelease */
   72818   BtCursor *pCrsr;
   72819   VdbeCursor *pC;
   72820   i64 rowid;
   72821 
   72822   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   72823   pC = p->apCsr[pOp->p1];
   72824   assert( pC!=0 );
   72825   pCrsr = pC->pCursor;
   72826   assert( pCrsr!=0 );
   72827   pOut->flags = MEM_Null;
   72828   rc = sqlite3VdbeCursorMoveto(pC);
   72829   if( NEVER(rc) ) goto abort_due_to_error;
   72830   assert( pC->deferredMoveto==0 );
   72831   assert( pC->isTable==0 );
   72832   if( !pC->nullRow ){
   72833     rowid = 0;  /* Not needed.  Only used to silence a warning. */
   72834     rc = sqlite3VdbeIdxRowid(db, pCrsr, &rowid);
   72835     if( rc!=SQLITE_OK ){
   72836       goto abort_due_to_error;
   72837     }
   72838     pOut->u.i = rowid;
   72839     pOut->flags = MEM_Int;
   72840   }
   72841   break;
   72842 }
   72843 
   72844 /* Opcode: IdxGE P1 P2 P3 P4 P5
   72845 ** Synopsis: key=r[P3@P4]
   72846 **
   72847 ** The P4 register values beginning with P3 form an unpacked index
   72848 ** key that omits the PRIMARY KEY.  Compare this key value against the index
   72849 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
   72850 ** fields at the end.
   72851 **
   72852 ** If the P1 index entry is greater than or equal to the key value
   72853 ** then jump to P2.  Otherwise fall through to the next instruction.
   72854 */
   72855 /* Opcode: IdxGT P1 P2 P3 P4 P5
   72856 ** Synopsis: key=r[P3@P4]
   72857 **
   72858 ** The P4 register values beginning with P3 form an unpacked index
   72859 ** key that omits the PRIMARY KEY.  Compare this key value against the index
   72860 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
   72861 ** fields at the end.
   72862 **
   72863 ** If the P1 index entry is greater than the key value
   72864 ** then jump to P2.  Otherwise fall through to the next instruction.
   72865 */
   72866 /* Opcode: IdxLT P1 P2 P3 P4 P5
   72867 ** Synopsis: key=r[P3@P4]
   72868 **
   72869 ** The P4 register values beginning with P3 form an unpacked index
   72870 ** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
   72871 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
   72872 ** ROWID on the P1 index.
   72873 **
   72874 ** If the P1 index entry is less than the key value then jump to P2.
   72875 ** Otherwise fall through to the next instruction.
   72876 */
   72877 /* Opcode: IdxLE P1 P2 P3 P4 P5
   72878 ** Synopsis: key=r[P3@P4]
   72879 **
   72880 ** The P4 register values beginning with P3 form an unpacked index
   72881 ** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
   72882 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
   72883 ** ROWID on the P1 index.
   72884 **
   72885 ** If the P1 index entry is less than or equal to the key value then jump
   72886 ** to P2. Otherwise fall through to the next instruction.
   72887 */
   72888 case OP_IdxLE:          /* jump */
   72889 case OP_IdxGT:          /* jump */
   72890 case OP_IdxLT:          /* jump */
   72891 case OP_IdxGE:  {       /* jump */
   72892   VdbeCursor *pC;
   72893   int res;
   72894   UnpackedRecord r;
   72895 
   72896   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   72897   pC = p->apCsr[pOp->p1];
   72898   assert( pC!=0 );
   72899   assert( pC->isOrdered );
   72900   assert( pC->pCursor!=0);
   72901   assert( pC->deferredMoveto==0 );
   72902   assert( pOp->p5==0 || pOp->p5==1 );
   72903   assert( pOp->p4type==P4_INT32 );
   72904   r.pKeyInfo = pC->pKeyInfo;
   72905   r.nField = (u16)pOp->p4.i;
   72906   if( pOp->opcode<OP_IdxLT ){
   72907     assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
   72908     r.default_rc = -1;
   72909   }else{
   72910     assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
   72911     r.default_rc = 0;
   72912   }
   72913   r.aMem = &aMem[pOp->p3];
   72914 #ifdef SQLITE_DEBUG
   72915   { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
   72916 #endif
   72917   res = 0;  /* Not needed.  Only used to silence a warning. */
   72918   rc = sqlite3VdbeIdxKeyCompare(pC, &r, &res);
   72919   assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
   72920   if( (pOp->opcode&1)==(OP_IdxLT&1) ){
   72921     assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
   72922     res = -res;
   72923   }else{
   72924     assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
   72925     res++;
   72926   }
   72927   VdbeBranchTaken(res>0,2);
   72928   if( res>0 ){
   72929     pc = pOp->p2 - 1 ;
   72930   }
   72931   break;
   72932 }
   72933 
   72934 /* Opcode: Destroy P1 P2 P3 * *
   72935 **
   72936 ** Delete an entire database table or index whose root page in the database
   72937 ** file is given by P1.
   72938 **
   72939 ** The table being destroyed is in the main database file if P3==0.  If
   72940 ** P3==1 then the table to be clear is in the auxiliary database file
   72941 ** that is used to store tables create using CREATE TEMPORARY TABLE.
   72942 **
   72943 ** If AUTOVACUUM is enabled then it is possible that another root page
   72944 ** might be moved into the newly deleted root page in order to keep all
   72945 ** root pages contiguous at the beginning of the database.  The former
   72946 ** value of the root page that moved - its value before the move occurred -
   72947 ** is stored in register P2.  If no page
   72948 ** movement was required (because the table being dropped was already
   72949 ** the last one in the database) then a zero is stored in register P2.
   72950 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
   72951 **
   72952 ** See also: Clear
   72953 */
   72954 case OP_Destroy: {     /* out2-prerelease */
   72955   int iMoved;
   72956   int iCnt;
   72957   Vdbe *pVdbe;
   72958   int iDb;
   72959 
   72960   assert( p->readOnly==0 );
   72961 #ifndef SQLITE_OMIT_VIRTUALTABLE
   72962   iCnt = 0;
   72963   for(pVdbe=db->pVdbe; pVdbe; pVdbe = pVdbe->pNext){
   72964     if( pVdbe->magic==VDBE_MAGIC_RUN && pVdbe->bIsReader
   72965      && pVdbe->inVtabMethod<2 && pVdbe->pc>=0
   72966     ){
   72967       iCnt++;
   72968     }
   72969   }
   72970 #else
   72971   iCnt = db->nVdbeRead;
   72972 #endif
   72973   pOut->flags = MEM_Null;
   72974   if( iCnt>1 ){
   72975     rc = SQLITE_LOCKED;
   72976     p->errorAction = OE_Abort;
   72977   }else{
   72978     iDb = pOp->p3;
   72979     assert( iCnt==1 );
   72980     assert( DbMaskTest(p->btreeMask, iDb) );
   72981     iMoved = 0;  /* Not needed.  Only to silence a warning. */
   72982     rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
   72983     pOut->flags = MEM_Int;
   72984     pOut->u.i = iMoved;
   72985 #ifndef SQLITE_OMIT_AUTOVACUUM
   72986     if( rc==SQLITE_OK && iMoved!=0 ){
   72987       sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
   72988       /* All OP_Destroy operations occur on the same btree */
   72989       assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
   72990       resetSchemaOnFault = iDb+1;
   72991     }
   72992 #endif
   72993   }
   72994   break;
   72995 }
   72996 
   72997 /* Opcode: Clear P1 P2 P3
   72998 **
   72999 ** Delete all contents of the database table or index whose root page
   73000 ** in the database file is given by P1.  But, unlike Destroy, do not
   73001 ** remove the table or index from the database file.
   73002 **
   73003 ** The table being clear is in the main database file if P2==0.  If
   73004 ** P2==1 then the table to be clear is in the auxiliary database file
   73005 ** that is used to store tables create using CREATE TEMPORARY TABLE.
   73006 **
   73007 ** If the P3 value is non-zero, then the table referred to must be an
   73008 ** intkey table (an SQL table, not an index). In this case the row change
   73009 ** count is incremented by the number of rows in the table being cleared.
   73010 ** If P3 is greater than zero, then the value stored in register P3 is
   73011 ** also incremented by the number of rows in the table being cleared.
   73012 **
   73013 ** See also: Destroy
   73014 */
   73015 case OP_Clear: {
   73016   int nChange;
   73017 
   73018   nChange = 0;
   73019   assert( p->readOnly==0 );
   73020   assert( DbMaskTest(p->btreeMask, pOp->p2) );
   73021   rc = sqlite3BtreeClearTable(
   73022       db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
   73023   );
   73024   if( pOp->p3 ){
   73025     p->nChange += nChange;
   73026     if( pOp->p3>0 ){
   73027       assert( memIsValid(&aMem[pOp->p3]) );
   73028       memAboutToChange(p, &aMem[pOp->p3]);
   73029       aMem[pOp->p3].u.i += nChange;
   73030     }
   73031   }
   73032   break;
   73033 }
   73034 
   73035 /* Opcode: ResetSorter P1 * * * *
   73036 **
   73037 ** Delete all contents from the ephemeral table or sorter
   73038 ** that is open on cursor P1.
   73039 **
   73040 ** This opcode only works for cursors used for sorting and
   73041 ** opened with OP_OpenEphemeral or OP_SorterOpen.
   73042 */
   73043 case OP_ResetSorter: {
   73044   VdbeCursor *pC;
   73045 
   73046   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   73047   pC = p->apCsr[pOp->p1];
   73048   assert( pC!=0 );
   73049   if( pC->pSorter ){
   73050     sqlite3VdbeSorterReset(db, pC->pSorter);
   73051   }else{
   73052     assert( pC->isEphemeral );
   73053     rc = sqlite3BtreeClearTableOfCursor(pC->pCursor);
   73054   }
   73055   break;
   73056 }
   73057 
   73058 /* Opcode: CreateTable P1 P2 * * *
   73059 ** Synopsis: r[P2]=root iDb=P1
   73060 **
   73061 ** Allocate a new table in the main database file if P1==0 or in the
   73062 ** auxiliary database file if P1==1 or in an attached database if
   73063 ** P1>1.  Write the root page number of the new table into
   73064 ** register P2
   73065 **
   73066 ** The difference between a table and an index is this:  A table must
   73067 ** have a 4-byte integer key and can have arbitrary data.  An index
   73068 ** has an arbitrary key but no data.
   73069 **
   73070 ** See also: CreateIndex
   73071 */
   73072 /* Opcode: CreateIndex P1 P2 * * *
   73073 ** Synopsis: r[P2]=root iDb=P1
   73074 **
   73075 ** Allocate a new index in the main database file if P1==0 or in the
   73076 ** auxiliary database file if P1==1 or in an attached database if
   73077 ** P1>1.  Write the root page number of the new table into
   73078 ** register P2.
   73079 **
   73080 ** See documentation on OP_CreateTable for additional information.
   73081 */
   73082 case OP_CreateIndex:            /* out2-prerelease */
   73083 case OP_CreateTable: {          /* out2-prerelease */
   73084   int pgno;
   73085   int flags;
   73086   Db *pDb;
   73087 
   73088   pgno = 0;
   73089   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   73090   assert( DbMaskTest(p->btreeMask, pOp->p1) );
   73091   assert( p->readOnly==0 );
   73092   pDb = &db->aDb[pOp->p1];
   73093   assert( pDb->pBt!=0 );
   73094   if( pOp->opcode==OP_CreateTable ){
   73095     /* flags = BTREE_INTKEY; */
   73096     flags = BTREE_INTKEY;
   73097   }else{
   73098     flags = BTREE_BLOBKEY;
   73099   }
   73100   rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
   73101   pOut->u.i = pgno;
   73102   break;
   73103 }
   73104 
   73105 /* Opcode: ParseSchema P1 * * P4 *
   73106 **
   73107 ** Read and parse all entries from the SQLITE_MASTER table of database P1
   73108 ** that match the WHERE clause P4.
   73109 **
   73110 ** This opcode invokes the parser to create a new virtual machine,
   73111 ** then runs the new virtual machine.  It is thus a re-entrant opcode.
   73112 */
   73113 case OP_ParseSchema: {
   73114   int iDb;
   73115   const char *zMaster;
   73116   char *zSql;
   73117   InitData initData;
   73118 
   73119   /* Any prepared statement that invokes this opcode will hold mutexes
   73120   ** on every btree.  This is a prerequisite for invoking
   73121   ** sqlite3InitCallback().
   73122   */
   73123 #ifdef SQLITE_DEBUG
   73124   for(iDb=0; iDb<db->nDb; iDb++){
   73125     assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
   73126   }
   73127 #endif
   73128 
   73129   iDb = pOp->p1;
   73130   assert( iDb>=0 && iDb<db->nDb );
   73131   assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
   73132   /* Used to be a conditional */ {
   73133     zMaster = SCHEMA_TABLE(iDb);
   73134     initData.db = db;
   73135     initData.iDb = pOp->p1;
   73136     initData.pzErrMsg = &p->zErrMsg;
   73137     zSql = sqlite3MPrintf(db,
   73138        "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
   73139        db->aDb[iDb].zName, zMaster, pOp->p4.z);
   73140     if( zSql==0 ){
   73141       rc = SQLITE_NOMEM;
   73142     }else{
   73143       assert( db->init.busy==0 );
   73144       db->init.busy = 1;
   73145       initData.rc = SQLITE_OK;
   73146       assert( !db->mallocFailed );
   73147       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
   73148       if( rc==SQLITE_OK ) rc = initData.rc;
   73149       sqlite3DbFree(db, zSql);
   73150       db->init.busy = 0;
   73151     }
   73152   }
   73153   if( rc ) sqlite3ResetAllSchemasOfConnection(db);
   73154   if( rc==SQLITE_NOMEM ){
   73155     goto no_mem;
   73156   }
   73157   break;
   73158 }
   73159 
   73160 #if !defined(SQLITE_OMIT_ANALYZE)
   73161 /* Opcode: LoadAnalysis P1 * * * *
   73162 **
   73163 ** Read the sqlite_stat1 table for database P1 and load the content
   73164 ** of that table into the internal index hash table.  This will cause
   73165 ** the analysis to be used when preparing all subsequent queries.
   73166 */
   73167 case OP_LoadAnalysis: {
   73168   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   73169   rc = sqlite3AnalysisLoad(db, pOp->p1);
   73170   break;
   73171 }
   73172 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
   73173 
   73174 /* Opcode: DropTable P1 * * P4 *
   73175 **
   73176 ** Remove the internal (in-memory) data structures that describe
   73177 ** the table named P4 in database P1.  This is called after a table
   73178 ** is dropped from disk (using the Destroy opcode) in order to keep
   73179 ** the internal representation of the
   73180 ** schema consistent with what is on disk.
   73181 */
   73182 case OP_DropTable: {
   73183   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
   73184   break;
   73185 }
   73186 
   73187 /* Opcode: DropIndex P1 * * P4 *
   73188 **
   73189 ** Remove the internal (in-memory) data structures that describe
   73190 ** the index named P4 in database P1.  This is called after an index
   73191 ** is dropped from disk (using the Destroy opcode)
   73192 ** in order to keep the internal representation of the
   73193 ** schema consistent with what is on disk.
   73194 */
   73195 case OP_DropIndex: {
   73196   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
   73197   break;
   73198 }
   73199 
   73200 /* Opcode: DropTrigger P1 * * P4 *
   73201 **
   73202 ** Remove the internal (in-memory) data structures that describe
   73203 ** the trigger named P4 in database P1.  This is called after a trigger
   73204 ** is dropped from disk (using the Destroy opcode) in order to keep
   73205 ** the internal representation of the
   73206 ** schema consistent with what is on disk.
   73207 */
   73208 case OP_DropTrigger: {
   73209   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
   73210   break;
   73211 }
   73212 
   73213 
   73214 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
   73215 /* Opcode: IntegrityCk P1 P2 P3 * P5
   73216 **
   73217 ** Do an analysis of the currently open database.  Store in
   73218 ** register P1 the text of an error message describing any problems.
   73219 ** If no problems are found, store a NULL in register P1.
   73220 **
   73221 ** The register P3 contains the maximum number of allowed errors.
   73222 ** At most reg(P3) errors will be reported.
   73223 ** In other words, the analysis stops as soon as reg(P1) errors are
   73224 ** seen.  Reg(P1) is updated with the number of errors remaining.
   73225 **
   73226 ** The root page numbers of all tables in the database are integer
   73227 ** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
   73228 ** total.
   73229 **
   73230 ** If P5 is not zero, the check is done on the auxiliary database
   73231 ** file, not the main database file.
   73232 **
   73233 ** This opcode is used to implement the integrity_check pragma.
   73234 */
   73235 case OP_IntegrityCk: {
   73236   int nRoot;      /* Number of tables to check.  (Number of root pages.) */
   73237   int *aRoot;     /* Array of rootpage numbers for tables to be checked */
   73238   int j;          /* Loop counter */
   73239   int nErr;       /* Number of errors reported */
   73240   char *z;        /* Text of the error report */
   73241   Mem *pnErr;     /* Register keeping track of errors remaining */
   73242 
   73243   assert( p->bIsReader );
   73244   nRoot = pOp->p2;
   73245   assert( nRoot>0 );
   73246   aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(nRoot+1) );
   73247   if( aRoot==0 ) goto no_mem;
   73248   assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
   73249   pnErr = &aMem[pOp->p3];
   73250   assert( (pnErr->flags & MEM_Int)!=0 );
   73251   assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
   73252   pIn1 = &aMem[pOp->p1];
   73253   for(j=0; j<nRoot; j++){
   73254     aRoot[j] = (int)sqlite3VdbeIntValue(&pIn1[j]);
   73255   }
   73256   aRoot[j] = 0;
   73257   assert( pOp->p5<db->nDb );
   73258   assert( DbMaskTest(p->btreeMask, pOp->p5) );
   73259   z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot,
   73260                                  (int)pnErr->u.i, &nErr);
   73261   sqlite3DbFree(db, aRoot);
   73262   pnErr->u.i -= nErr;
   73263   sqlite3VdbeMemSetNull(pIn1);
   73264   if( nErr==0 ){
   73265     assert( z==0 );
   73266   }else if( z==0 ){
   73267     goto no_mem;
   73268   }else{
   73269     sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
   73270   }
   73271   UPDATE_MAX_BLOBSIZE(pIn1);
   73272   sqlite3VdbeChangeEncoding(pIn1, encoding);
   73273   break;
   73274 }
   73275 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
   73276 
   73277 /* Opcode: RowSetAdd P1 P2 * * *
   73278 ** Synopsis:  rowset(P1)=r[P2]
   73279 **
   73280 ** Insert the integer value held by register P2 into a boolean index
   73281 ** held in register P1.
   73282 **
   73283 ** An assertion fails if P2 is not an integer.
   73284 */
   73285 case OP_RowSetAdd: {       /* in1, in2 */
   73286   pIn1 = &aMem[pOp->p1];
   73287   pIn2 = &aMem[pOp->p2];
   73288   assert( (pIn2->flags & MEM_Int)!=0 );
   73289   if( (pIn1->flags & MEM_RowSet)==0 ){
   73290     sqlite3VdbeMemSetRowSet(pIn1);
   73291     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
   73292   }
   73293   sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
   73294   break;
   73295 }
   73296 
   73297 /* Opcode: RowSetRead P1 P2 P3 * *
   73298 ** Synopsis:  r[P3]=rowset(P1)
   73299 **
   73300 ** Extract the smallest value from boolean index P1 and put that value into
   73301 ** register P3.  Or, if boolean index P1 is initially empty, leave P3
   73302 ** unchanged and jump to instruction P2.
   73303 */
   73304 case OP_RowSetRead: {       /* jump, in1, out3 */
   73305   i64 val;
   73306 
   73307   pIn1 = &aMem[pOp->p1];
   73308   if( (pIn1->flags & MEM_RowSet)==0
   73309    || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
   73310   ){
   73311     /* The boolean index is empty */
   73312     sqlite3VdbeMemSetNull(pIn1);
   73313     pc = pOp->p2 - 1;
   73314     VdbeBranchTaken(1,2);
   73315   }else{
   73316     /* A value was pulled from the index */
   73317     sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
   73318     VdbeBranchTaken(0,2);
   73319   }
   73320   goto check_for_interrupt;
   73321 }
   73322 
   73323 /* Opcode: RowSetTest P1 P2 P3 P4
   73324 ** Synopsis: if r[P3] in rowset(P1) goto P2
   73325 **
   73326 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
   73327 ** contains a RowSet object and that RowSet object contains
   73328 ** the value held in P3, jump to register P2. Otherwise, insert the
   73329 ** integer in P3 into the RowSet and continue on to the
   73330 ** next opcode.
   73331 **
   73332 ** The RowSet object is optimized for the case where successive sets
   73333 ** of integers, where each set contains no duplicates. Each set
   73334 ** of values is identified by a unique P4 value. The first set
   73335 ** must have P4==0, the final set P4=-1.  P4 must be either -1 or
   73336 ** non-negative.  For non-negative values of P4 only the lower 4
   73337 ** bits are significant.
   73338 **
   73339 ** This allows optimizations: (a) when P4==0 there is no need to test
   73340 ** the rowset object for P3, as it is guaranteed not to contain it,
   73341 ** (b) when P4==-1 there is no need to insert the value, as it will
   73342 ** never be tested for, and (c) when a value that is part of set X is
   73343 ** inserted, there is no need to search to see if the same value was
   73344 ** previously inserted as part of set X (only if it was previously
   73345 ** inserted as part of some other set).
   73346 */
   73347 case OP_RowSetTest: {                     /* jump, in1, in3 */
   73348   int iSet;
   73349   int exists;
   73350 
   73351   pIn1 = &aMem[pOp->p1];
   73352   pIn3 = &aMem[pOp->p3];
   73353   iSet = pOp->p4.i;
   73354   assert( pIn3->flags&MEM_Int );
   73355 
   73356   /* If there is anything other than a rowset object in memory cell P1,
   73357   ** delete it now and initialize P1 with an empty rowset
   73358   */
   73359   if( (pIn1->flags & MEM_RowSet)==0 ){
   73360     sqlite3VdbeMemSetRowSet(pIn1);
   73361     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
   73362   }
   73363 
   73364   assert( pOp->p4type==P4_INT32 );
   73365   assert( iSet==-1 || iSet>=0 );
   73366   if( iSet ){
   73367     exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i);
   73368     VdbeBranchTaken(exists!=0,2);
   73369     if( exists ){
   73370       pc = pOp->p2 - 1;
   73371       break;
   73372     }
   73373   }
   73374   if( iSet>=0 ){
   73375     sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
   73376   }
   73377   break;
   73378 }
   73379 
   73380 
   73381 #ifndef SQLITE_OMIT_TRIGGER
   73382 
   73383 /* Opcode: Program P1 P2 P3 P4 P5
   73384 **
   73385 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
   73386 **
   73387 ** P1 contains the address of the memory cell that contains the first memory
   73388 ** cell in an array of values used as arguments to the sub-program. P2
   73389 ** contains the address to jump to if the sub-program throws an IGNORE
   73390 ** exception using the RAISE() function. Register P3 contains the address
   73391 ** of a memory cell in this (the parent) VM that is used to allocate the
   73392 ** memory required by the sub-vdbe at runtime.
   73393 **
   73394 ** P4 is a pointer to the VM containing the trigger program.
   73395 **
   73396 ** If P5 is non-zero, then recursive program invocation is enabled.
   73397 */
   73398 case OP_Program: {        /* jump */
   73399   int nMem;               /* Number of memory registers for sub-program */
   73400   int nByte;              /* Bytes of runtime space required for sub-program */
   73401   Mem *pRt;               /* Register to allocate runtime space */
   73402   Mem *pMem;              /* Used to iterate through memory cells */
   73403   Mem *pEnd;              /* Last memory cell in new array */
   73404   VdbeFrame *pFrame;      /* New vdbe frame to execute in */
   73405   SubProgram *pProgram;   /* Sub-program to execute */
   73406   void *t;                /* Token identifying trigger */
   73407 
   73408   pProgram = pOp->p4.pProgram;
   73409   pRt = &aMem[pOp->p3];
   73410   assert( pProgram->nOp>0 );
   73411 
   73412   /* If the p5 flag is clear, then recursive invocation of triggers is
   73413   ** disabled for backwards compatibility (p5 is set if this sub-program
   73414   ** is really a trigger, not a foreign key action, and the flag set
   73415   ** and cleared by the "PRAGMA recursive_triggers" command is clear).
   73416   **
   73417   ** It is recursive invocation of triggers, at the SQL level, that is
   73418   ** disabled. In some cases a single trigger may generate more than one
   73419   ** SubProgram (if the trigger may be executed with more than one different
   73420   ** ON CONFLICT algorithm). SubProgram structures associated with a
   73421   ** single trigger all have the same value for the SubProgram.token
   73422   ** variable.  */
   73423   if( pOp->p5 ){
   73424     t = pProgram->token;
   73425     for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
   73426     if( pFrame ) break;
   73427   }
   73428 
   73429   if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
   73430     rc = SQLITE_ERROR;
   73431     sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
   73432     break;
   73433   }
   73434 
   73435   /* Register pRt is used to store the memory required to save the state
   73436   ** of the current program, and the memory required at runtime to execute
   73437   ** the trigger program. If this trigger has been fired before, then pRt
   73438   ** is already allocated. Otherwise, it must be initialized.  */
   73439   if( (pRt->flags&MEM_Frame)==0 ){
   73440     /* SubProgram.nMem is set to the number of memory cells used by the
   73441     ** program stored in SubProgram.aOp. As well as these, one memory
   73442     ** cell is required for each cursor used by the program. Set local
   73443     ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
   73444     */
   73445     nMem = pProgram->nMem + pProgram->nCsr;
   73446     nByte = ROUND8(sizeof(VdbeFrame))
   73447               + nMem * sizeof(Mem)
   73448               + pProgram->nCsr * sizeof(VdbeCursor *)
   73449               + pProgram->nOnce * sizeof(u8);
   73450     pFrame = sqlite3DbMallocZero(db, nByte);
   73451     if( !pFrame ){
   73452       goto no_mem;
   73453     }
   73454     sqlite3VdbeMemRelease(pRt);
   73455     pRt->flags = MEM_Frame;
   73456     pRt->u.pFrame = pFrame;
   73457 
   73458     pFrame->v = p;
   73459     pFrame->nChildMem = nMem;
   73460     pFrame->nChildCsr = pProgram->nCsr;
   73461     pFrame->pc = pc;
   73462     pFrame->aMem = p->aMem;
   73463     pFrame->nMem = p->nMem;
   73464     pFrame->apCsr = p->apCsr;
   73465     pFrame->nCursor = p->nCursor;
   73466     pFrame->aOp = p->aOp;
   73467     pFrame->nOp = p->nOp;
   73468     pFrame->token = pProgram->token;
   73469     pFrame->aOnceFlag = p->aOnceFlag;
   73470     pFrame->nOnceFlag = p->nOnceFlag;
   73471 
   73472     pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
   73473     for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
   73474       pMem->flags = MEM_Undefined;
   73475       pMem->db = db;
   73476     }
   73477   }else{
   73478     pFrame = pRt->u.pFrame;
   73479     assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem );
   73480     assert( pProgram->nCsr==pFrame->nChildCsr );
   73481     assert( pc==pFrame->pc );
   73482   }
   73483 
   73484   p->nFrame++;
   73485   pFrame->pParent = p->pFrame;
   73486   pFrame->lastRowid = lastRowid;
   73487   pFrame->nChange = p->nChange;
   73488   p->nChange = 0;
   73489   p->pFrame = pFrame;
   73490   p->aMem = aMem = &VdbeFrameMem(pFrame)[-1];
   73491   p->nMem = pFrame->nChildMem;
   73492   p->nCursor = (u16)pFrame->nChildCsr;
   73493   p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
   73494   p->aOp = aOp = pProgram->aOp;
   73495   p->nOp = pProgram->nOp;
   73496   p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
   73497   p->nOnceFlag = pProgram->nOnce;
   73498   pc = -1;
   73499   memset(p->aOnceFlag, 0, p->nOnceFlag);
   73500 
   73501   break;
   73502 }
   73503 
   73504 /* Opcode: Param P1 P2 * * *
   73505 **
   73506 ** This opcode is only ever present in sub-programs called via the
   73507 ** OP_Program instruction. Copy a value currently stored in a memory
   73508 ** cell of the calling (parent) frame to cell P2 in the current frames
   73509 ** address space. This is used by trigger programs to access the new.*
   73510 ** and old.* values.
   73511 **
   73512 ** The address of the cell in the parent frame is determined by adding
   73513 ** the value of the P1 argument to the value of the P1 argument to the
   73514 ** calling OP_Program instruction.
   73515 */
   73516 case OP_Param: {           /* out2-prerelease */
   73517   VdbeFrame *pFrame;
   73518   Mem *pIn;
   73519   pFrame = p->pFrame;
   73520   pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
   73521   sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
   73522   break;
   73523 }
   73524 
   73525 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
   73526 
   73527 #ifndef SQLITE_OMIT_FOREIGN_KEY
   73528 /* Opcode: FkCounter P1 P2 * * *
   73529 ** Synopsis: fkctr[P1]+=P2
   73530 **
   73531 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
   73532 ** If P1 is non-zero, the database constraint counter is incremented
   73533 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
   73534 ** statement counter is incremented (immediate foreign key constraints).
   73535 */
   73536 case OP_FkCounter: {
   73537   if( db->flags & SQLITE_DeferFKs ){
   73538     db->nDeferredImmCons += pOp->p2;
   73539   }else if( pOp->p1 ){
   73540     db->nDeferredCons += pOp->p2;
   73541   }else{
   73542     p->nFkConstraint += pOp->p2;
   73543   }
   73544   break;
   73545 }
   73546 
   73547 /* Opcode: FkIfZero P1 P2 * * *
   73548 ** Synopsis: if fkctr[P1]==0 goto P2
   73549 **
   73550 ** This opcode tests if a foreign key constraint-counter is currently zero.
   73551 ** If so, jump to instruction P2. Otherwise, fall through to the next
   73552 ** instruction.
   73553 **
   73554 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
   73555 ** is zero (the one that counts deferred constraint violations). If P1 is
   73556 ** zero, the jump is taken if the statement constraint-counter is zero
   73557 ** (immediate foreign key constraint violations).
   73558 */
   73559 case OP_FkIfZero: {         /* jump */
   73560   if( pOp->p1 ){
   73561     VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
   73562     if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1;
   73563   }else{
   73564     VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
   73565     if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1;
   73566   }
   73567   break;
   73568 }
   73569 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
   73570 
   73571 #ifndef SQLITE_OMIT_AUTOINCREMENT
   73572 /* Opcode: MemMax P1 P2 * * *
   73573 ** Synopsis: r[P1]=max(r[P1],r[P2])
   73574 **
   73575 ** P1 is a register in the root frame of this VM (the root frame is
   73576 ** different from the current frame if this instruction is being executed
   73577 ** within a sub-program). Set the value of register P1 to the maximum of
   73578 ** its current value and the value in register P2.
   73579 **
   73580 ** This instruction throws an error if the memory cell is not initially
   73581 ** an integer.
   73582 */
   73583 case OP_MemMax: {        /* in2 */
   73584   VdbeFrame *pFrame;
   73585   if( p->pFrame ){
   73586     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
   73587     pIn1 = &pFrame->aMem[pOp->p1];
   73588   }else{
   73589     pIn1 = &aMem[pOp->p1];
   73590   }
   73591   assert( memIsValid(pIn1) );
   73592   sqlite3VdbeMemIntegerify(pIn1);
   73593   pIn2 = &aMem[pOp->p2];
   73594   sqlite3VdbeMemIntegerify(pIn2);
   73595   if( pIn1->u.i<pIn2->u.i){
   73596     pIn1->u.i = pIn2->u.i;
   73597   }
   73598   break;
   73599 }
   73600 #endif /* SQLITE_OMIT_AUTOINCREMENT */
   73601 
   73602 /* Opcode: IfPos P1 P2 * * *
   73603 ** Synopsis: if r[P1]>0 goto P2
   73604 **
   73605 ** If the value of register P1 is 1 or greater, jump to P2.
   73606 **
   73607 ** It is illegal to use this instruction on a register that does
   73608 ** not contain an integer.  An assertion fault will result if you try.
   73609 */
   73610 case OP_IfPos: {        /* jump, in1 */
   73611   pIn1 = &aMem[pOp->p1];
   73612   assert( pIn1->flags&MEM_Int );
   73613   VdbeBranchTaken( pIn1->u.i>0, 2);
   73614   if( pIn1->u.i>0 ){
   73615      pc = pOp->p2 - 1;
   73616   }
   73617   break;
   73618 }
   73619 
   73620 /* Opcode: IfNeg P1 P2 P3 * *
   73621 ** Synopsis: r[P1]+=P3, if r[P1]<0 goto P2
   73622 **
   73623 ** Register P1 must contain an integer.  Add literal P3 to the value in
   73624 ** register P1 then if the value of register P1 is less than zero, jump to P2.
   73625 */
   73626 case OP_IfNeg: {        /* jump, in1 */
   73627   pIn1 = &aMem[pOp->p1];
   73628   assert( pIn1->flags&MEM_Int );
   73629   pIn1->u.i += pOp->p3;
   73630   VdbeBranchTaken(pIn1->u.i<0, 2);
   73631   if( pIn1->u.i<0 ){
   73632      pc = pOp->p2 - 1;
   73633   }
   73634   break;
   73635 }
   73636 
   73637 /* Opcode: IfZero P1 P2 P3 * *
   73638 ** Synopsis: r[P1]+=P3, if r[P1]==0 goto P2
   73639 **
   73640 ** The register P1 must contain an integer.  Add literal P3 to the
   73641 ** value in register P1.  If the result is exactly 0, jump to P2.
   73642 */
   73643 case OP_IfZero: {        /* jump, in1 */
   73644   pIn1 = &aMem[pOp->p1];
   73645   assert( pIn1->flags&MEM_Int );
   73646   pIn1->u.i += pOp->p3;
   73647   VdbeBranchTaken(pIn1->u.i==0, 2);
   73648   if( pIn1->u.i==0 ){
   73649      pc = pOp->p2 - 1;
   73650   }
   73651   break;
   73652 }
   73653 
   73654 /* Opcode: AggStep * P2 P3 P4 P5
   73655 ** Synopsis: accum=r[P3] step(r[P2@P5])
   73656 **
   73657 ** Execute the step function for an aggregate.  The
   73658 ** function has P5 arguments.   P4 is a pointer to the FuncDef
   73659 ** structure that specifies the function.  Use register
   73660 ** P3 as the accumulator.
   73661 **
   73662 ** The P5 arguments are taken from register P2 and its
   73663 ** successors.
   73664 */
   73665 case OP_AggStep: {
   73666   int n;
   73667   int i;
   73668   Mem *pMem;
   73669   Mem *pRec;
   73670   sqlite3_context ctx;
   73671   sqlite3_value **apVal;
   73672 
   73673   n = pOp->p5;
   73674   assert( n>=0 );
   73675   pRec = &aMem[pOp->p2];
   73676   apVal = p->apArg;
   73677   assert( apVal || n==0 );
   73678   for(i=0; i<n; i++, pRec++){
   73679     assert( memIsValid(pRec) );
   73680     apVal[i] = pRec;
   73681     memAboutToChange(p, pRec);
   73682   }
   73683   ctx.pFunc = pOp->p4.pFunc;
   73684   assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
   73685   ctx.pMem = pMem = &aMem[pOp->p3];
   73686   pMem->n++;
   73687   ctx.s.flags = MEM_Null;
   73688   ctx.s.z = 0;
   73689   ctx.s.zMalloc = 0;
   73690   ctx.s.xDel = 0;
   73691   ctx.s.db = db;
   73692   ctx.isError = 0;
   73693   ctx.pColl = 0;
   73694   ctx.skipFlag = 0;
   73695   if( ctx.pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
   73696     assert( pOp>p->aOp );
   73697     assert( pOp[-1].p4type==P4_COLLSEQ );
   73698     assert( pOp[-1].opcode==OP_CollSeq );
   73699     ctx.pColl = pOp[-1].p4.pColl;
   73700   }
   73701   (ctx.pFunc->xStep)(&ctx, n, apVal); /* IMP: R-24505-23230 */
   73702   if( ctx.isError ){
   73703     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&ctx.s));
   73704     rc = ctx.isError;
   73705   }
   73706   if( ctx.skipFlag ){
   73707     assert( pOp[-1].opcode==OP_CollSeq );
   73708     i = pOp[-1].p1;
   73709     if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
   73710   }
   73711 
   73712   sqlite3VdbeMemRelease(&ctx.s);
   73713 
   73714   break;
   73715 }
   73716 
   73717 /* Opcode: AggFinal P1 P2 * P4 *
   73718 ** Synopsis: accum=r[P1] N=P2
   73719 **
   73720 ** Execute the finalizer function for an aggregate.  P1 is
   73721 ** the memory location that is the accumulator for the aggregate.
   73722 **
   73723 ** P2 is the number of arguments that the step function takes and
   73724 ** P4 is a pointer to the FuncDef for this function.  The P2
   73725 ** argument is not used by this opcode.  It is only there to disambiguate
   73726 ** functions that can take varying numbers of arguments.  The
   73727 ** P4 argument is only needed for the degenerate case where
   73728 ** the step function was not previously called.
   73729 */
   73730 case OP_AggFinal: {
   73731   Mem *pMem;
   73732   assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
   73733   pMem = &aMem[pOp->p1];
   73734   assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
   73735   rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
   73736   if( rc ){
   73737     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(pMem));
   73738   }
   73739   sqlite3VdbeChangeEncoding(pMem, encoding);
   73740   UPDATE_MAX_BLOBSIZE(pMem);
   73741   if( sqlite3VdbeMemTooBig(pMem) ){
   73742     goto too_big;
   73743   }
   73744   break;
   73745 }
   73746 
   73747 #ifndef SQLITE_OMIT_WAL
   73748 /* Opcode: Checkpoint P1 P2 P3 * *
   73749 **
   73750 ** Checkpoint database P1. This is a no-op if P1 is not currently in
   73751 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL
   73752 ** or RESTART.  Write 1 or 0 into mem[P3] if the checkpoint returns
   73753 ** SQLITE_BUSY or not, respectively.  Write the number of pages in the
   73754 ** WAL after the checkpoint into mem[P3+1] and the number of pages
   73755 ** in the WAL that have been checkpointed after the checkpoint
   73756 ** completes into mem[P3+2].  However on an error, mem[P3+1] and
   73757 ** mem[P3+2] are initialized to -1.
   73758 */
   73759 case OP_Checkpoint: {
   73760   int i;                          /* Loop counter */
   73761   int aRes[3];                    /* Results */
   73762   Mem *pMem;                      /* Write results here */
   73763 
   73764   assert( p->readOnly==0 );
   73765   aRes[0] = 0;
   73766   aRes[1] = aRes[2] = -1;
   73767   assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
   73768        || pOp->p2==SQLITE_CHECKPOINT_FULL
   73769        || pOp->p2==SQLITE_CHECKPOINT_RESTART
   73770   );
   73771   rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
   73772   if( rc==SQLITE_BUSY ){
   73773     rc = SQLITE_OK;
   73774     aRes[0] = 1;
   73775   }
   73776   for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
   73777     sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
   73778   }
   73779   break;
   73780 };
   73781 #endif
   73782 
   73783 #ifndef SQLITE_OMIT_PRAGMA
   73784 /* Opcode: JournalMode P1 P2 P3 * *
   73785 **
   73786 ** Change the journal mode of database P1 to P3. P3 must be one of the
   73787 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
   73788 ** modes (delete, truncate, persist, off and memory), this is a simple
   73789 ** operation. No IO is required.
   73790 **
   73791 ** If changing into or out of WAL mode the procedure is more complicated.
   73792 **
   73793 ** Write a string containing the final journal-mode to register P2.
   73794 */
   73795 case OP_JournalMode: {    /* out2-prerelease */
   73796   Btree *pBt;                     /* Btree to change journal mode of */
   73797   Pager *pPager;                  /* Pager associated with pBt */
   73798   int eNew;                       /* New journal mode */
   73799   int eOld;                       /* The old journal mode */
   73800 #ifndef SQLITE_OMIT_WAL
   73801   const char *zFilename;          /* Name of database file for pPager */
   73802 #endif
   73803 
   73804   eNew = pOp->p3;
   73805   assert( eNew==PAGER_JOURNALMODE_DELETE
   73806        || eNew==PAGER_JOURNALMODE_TRUNCATE
   73807        || eNew==PAGER_JOURNALMODE_PERSIST
   73808        || eNew==PAGER_JOURNALMODE_OFF
   73809        || eNew==PAGER_JOURNALMODE_MEMORY
   73810        || eNew==PAGER_JOURNALMODE_WAL
   73811        || eNew==PAGER_JOURNALMODE_QUERY
   73812   );
   73813   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   73814   assert( p->readOnly==0 );
   73815 
   73816   pBt = db->aDb[pOp->p1].pBt;
   73817   pPager = sqlite3BtreePager(pBt);
   73818   eOld = sqlite3PagerGetJournalMode(pPager);
   73819   if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
   73820   if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
   73821 
   73822 #ifndef SQLITE_OMIT_WAL
   73823   zFilename = sqlite3PagerFilename(pPager, 1);
   73824 
   73825   /* Do not allow a transition to journal_mode=WAL for a database
   73826   ** in temporary storage or if the VFS does not support shared memory
   73827   */
   73828   if( eNew==PAGER_JOURNALMODE_WAL
   73829    && (sqlite3Strlen30(zFilename)==0           /* Temp file */
   73830        || !sqlite3PagerWalSupported(pPager))   /* No shared-memory support */
   73831   ){
   73832     eNew = eOld;
   73833   }
   73834 
   73835   if( (eNew!=eOld)
   73836    && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
   73837   ){
   73838     if( !db->autoCommit || db->nVdbeRead>1 ){
   73839       rc = SQLITE_ERROR;
   73840       sqlite3SetString(&p->zErrMsg, db,
   73841           "cannot change %s wal mode from within a transaction",
   73842           (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
   73843       );
   73844       break;
   73845     }else{
   73846 
   73847       if( eOld==PAGER_JOURNALMODE_WAL ){
   73848         /* If leaving WAL mode, close the log file. If successful, the call
   73849         ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
   73850         ** file. An EXCLUSIVE lock may still be held on the database file
   73851         ** after a successful return.
   73852         */
   73853         rc = sqlite3PagerCloseWal(pPager);
   73854         if( rc==SQLITE_OK ){
   73855           sqlite3PagerSetJournalMode(pPager, eNew);
   73856         }
   73857       }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
   73858         /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
   73859         ** as an intermediate */
   73860         sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
   73861       }
   73862 
   73863       /* Open a transaction on the database file. Regardless of the journal
   73864       ** mode, this transaction always uses a rollback journal.
   73865       */
   73866       assert( sqlite3BtreeIsInTrans(pBt)==0 );
   73867       if( rc==SQLITE_OK ){
   73868         rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
   73869       }
   73870     }
   73871   }
   73872 #endif /* ifndef SQLITE_OMIT_WAL */
   73873 
   73874   if( rc ){
   73875     eNew = eOld;
   73876   }
   73877   eNew = sqlite3PagerSetJournalMode(pPager, eNew);
   73878 
   73879   pOut = &aMem[pOp->p2];
   73880   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
   73881   pOut->z = (char *)sqlite3JournalModename(eNew);
   73882   pOut->n = sqlite3Strlen30(pOut->z);
   73883   pOut->enc = SQLITE_UTF8;
   73884   sqlite3VdbeChangeEncoding(pOut, encoding);
   73885   break;
   73886 };
   73887 #endif /* SQLITE_OMIT_PRAGMA */
   73888 
   73889 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
   73890 /* Opcode: Vacuum * * * * *
   73891 **
   73892 ** Vacuum the entire database.  This opcode will cause other virtual
   73893 ** machines to be created and run.  It may not be called from within
   73894 ** a transaction.
   73895 */
   73896 case OP_Vacuum: {
   73897   assert( p->readOnly==0 );
   73898   rc = sqlite3RunVacuum(&p->zErrMsg, db);
   73899   break;
   73900 }
   73901 #endif
   73902 
   73903 #if !defined(SQLITE_OMIT_AUTOVACUUM)
   73904 /* Opcode: IncrVacuum P1 P2 * * *
   73905 **
   73906 ** Perform a single step of the incremental vacuum procedure on
   73907 ** the P1 database. If the vacuum has finished, jump to instruction
   73908 ** P2. Otherwise, fall through to the next instruction.
   73909 */
   73910 case OP_IncrVacuum: {        /* jump */
   73911   Btree *pBt;
   73912 
   73913   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   73914   assert( DbMaskTest(p->btreeMask, pOp->p1) );
   73915   assert( p->readOnly==0 );
   73916   pBt = db->aDb[pOp->p1].pBt;
   73917   rc = sqlite3BtreeIncrVacuum(pBt);
   73918   VdbeBranchTaken(rc==SQLITE_DONE,2);
   73919   if( rc==SQLITE_DONE ){
   73920     pc = pOp->p2 - 1;
   73921     rc = SQLITE_OK;
   73922   }
   73923   break;
   73924 }
   73925 #endif
   73926 
   73927 /* Opcode: Expire P1 * * * *
   73928 **
   73929 ** Cause precompiled statements to expire.  When an expired statement
   73930 ** is executed using sqlite3_step() it will either automatically
   73931 ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
   73932 ** or it will fail with SQLITE_SCHEMA.
   73933 **
   73934 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
   73935 ** then only the currently executing statement is expired.
   73936 */
   73937 case OP_Expire: {
   73938   if( !pOp->p1 ){
   73939     sqlite3ExpirePreparedStatements(db);
   73940   }else{
   73941     p->expired = 1;
   73942   }
   73943   break;
   73944 }
   73945 
   73946 #ifndef SQLITE_OMIT_SHARED_CACHE
   73947 /* Opcode: TableLock P1 P2 P3 P4 *
   73948 ** Synopsis: iDb=P1 root=P2 write=P3
   73949 **
   73950 ** Obtain a lock on a particular table. This instruction is only used when
   73951 ** the shared-cache feature is enabled.
   73952 **
   73953 ** P1 is the index of the database in sqlite3.aDb[] of the database
   73954 ** on which the lock is acquired.  A readlock is obtained if P3==0 or
   73955 ** a write lock if P3==1.
   73956 **
   73957 ** P2 contains the root-page of the table to lock.
   73958 **
   73959 ** P4 contains a pointer to the name of the table being locked. This is only
   73960 ** used to generate an error message if the lock cannot be obtained.
   73961 */
   73962 case OP_TableLock: {
   73963   u8 isWriteLock = (u8)pOp->p3;
   73964   if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
   73965     int p1 = pOp->p1;
   73966     assert( p1>=0 && p1<db->nDb );
   73967     assert( DbMaskTest(p->btreeMask, p1) );
   73968     assert( isWriteLock==0 || isWriteLock==1 );
   73969     rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
   73970     if( (rc&0xFF)==SQLITE_LOCKED ){
   73971       const char *z = pOp->p4.z;
   73972       sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
   73973     }
   73974   }
   73975   break;
   73976 }
   73977 #endif /* SQLITE_OMIT_SHARED_CACHE */
   73978 
   73979 #ifndef SQLITE_OMIT_VIRTUALTABLE
   73980 /* Opcode: VBegin * * * P4 *
   73981 **
   73982 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
   73983 ** xBegin method for that table.
   73984 **
   73985 ** Also, whether or not P4 is set, check that this is not being called from
   73986 ** within a callback to a virtual table xSync() method. If it is, the error
   73987 ** code will be set to SQLITE_LOCKED.
   73988 */
   73989 case OP_VBegin: {
   73990   VTable *pVTab;
   73991   pVTab = pOp->p4.pVtab;
   73992   rc = sqlite3VtabBegin(db, pVTab);
   73993   if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
   73994   break;
   73995 }
   73996 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   73997 
   73998 #ifndef SQLITE_OMIT_VIRTUALTABLE
   73999 /* Opcode: VCreate P1 * * P4 *
   74000 **
   74001 ** P4 is the name of a virtual table in database P1. Call the xCreate method
   74002 ** for that table.
   74003 */
   74004 case OP_VCreate: {
   74005   rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
   74006   break;
   74007 }
   74008 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   74009 
   74010 #ifndef SQLITE_OMIT_VIRTUALTABLE
   74011 /* Opcode: VDestroy P1 * * P4 *
   74012 **
   74013 ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
   74014 ** of that table.
   74015 */
   74016 case OP_VDestroy: {
   74017   p->inVtabMethod = 2;
   74018   rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
   74019   p->inVtabMethod = 0;
   74020   break;
   74021 }
   74022 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   74023 
   74024 #ifndef SQLITE_OMIT_VIRTUALTABLE
   74025 /* Opcode: VOpen P1 * * P4 *
   74026 **
   74027 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
   74028 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
   74029 ** table and stores that cursor in P1.
   74030 */
   74031 case OP_VOpen: {
   74032   VdbeCursor *pCur;
   74033   sqlite3_vtab_cursor *pVtabCursor;
   74034   sqlite3_vtab *pVtab;
   74035   sqlite3_module *pModule;
   74036 
   74037   assert( p->bIsReader );
   74038   pCur = 0;
   74039   pVtabCursor = 0;
   74040   pVtab = pOp->p4.pVtab->pVtab;
   74041   pModule = (sqlite3_module *)pVtab->pModule;
   74042   assert(pVtab && pModule);
   74043   rc = pModule->xOpen(pVtab, &pVtabCursor);
   74044   sqlite3VtabImportErrmsg(p, pVtab);
   74045   if( SQLITE_OK==rc ){
   74046     /* Initialize sqlite3_vtab_cursor base class */
   74047     pVtabCursor->pVtab = pVtab;
   74048 
   74049     /* Initialize vdbe cursor object */
   74050     pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
   74051     if( pCur ){
   74052       pCur->pVtabCursor = pVtabCursor;
   74053     }else{
   74054       db->mallocFailed = 1;
   74055       pModule->xClose(pVtabCursor);
   74056     }
   74057   }
   74058   break;
   74059 }
   74060 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   74061 
   74062 #ifndef SQLITE_OMIT_VIRTUALTABLE
   74063 /* Opcode: VFilter P1 P2 P3 P4 *
   74064 ** Synopsis: iplan=r[P3] zplan='P4'
   74065 **
   74066 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
   74067 ** the filtered result set is empty.
   74068 **
   74069 ** P4 is either NULL or a string that was generated by the xBestIndex
   74070 ** method of the module.  The interpretation of the P4 string is left
   74071 ** to the module implementation.
   74072 **
   74073 ** This opcode invokes the xFilter method on the virtual table specified
   74074 ** by P1.  The integer query plan parameter to xFilter is stored in register
   74075 ** P3. Register P3+1 stores the argc parameter to be passed to the
   74076 ** xFilter method. Registers P3+2..P3+1+argc are the argc
   74077 ** additional parameters which are passed to
   74078 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
   74079 **
   74080 ** A jump is made to P2 if the result set after filtering would be empty.
   74081 */
   74082 case OP_VFilter: {   /* jump */
   74083   int nArg;
   74084   int iQuery;
   74085   const sqlite3_module *pModule;
   74086   Mem *pQuery;
   74087   Mem *pArgc;
   74088   sqlite3_vtab_cursor *pVtabCursor;
   74089   sqlite3_vtab *pVtab;
   74090   VdbeCursor *pCur;
   74091   int res;
   74092   int i;
   74093   Mem **apArg;
   74094 
   74095   pQuery = &aMem[pOp->p3];
   74096   pArgc = &pQuery[1];
   74097   pCur = p->apCsr[pOp->p1];
   74098   assert( memIsValid(pQuery) );
   74099   REGISTER_TRACE(pOp->p3, pQuery);
   74100   assert( pCur->pVtabCursor );
   74101   pVtabCursor = pCur->pVtabCursor;
   74102   pVtab = pVtabCursor->pVtab;
   74103   pModule = pVtab->pModule;
   74104 
   74105   /* Grab the index number and argc parameters */
   74106   assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
   74107   nArg = (int)pArgc->u.i;
   74108   iQuery = (int)pQuery->u.i;
   74109 
   74110   /* Invoke the xFilter method */
   74111   {
   74112     res = 0;
   74113     apArg = p->apArg;
   74114     for(i = 0; i<nArg; i++){
   74115       apArg[i] = &pArgc[i+1];
   74116     }
   74117 
   74118     p->inVtabMethod = 1;
   74119     rc = pModule->xFilter(pVtabCursor, iQuery, pOp->p4.z, nArg, apArg);
   74120     p->inVtabMethod = 0;
   74121     sqlite3VtabImportErrmsg(p, pVtab);
   74122     if( rc==SQLITE_OK ){
   74123       res = pModule->xEof(pVtabCursor);
   74124     }
   74125     VdbeBranchTaken(res!=0,2);
   74126     if( res ){
   74127       pc = pOp->p2 - 1;
   74128     }
   74129   }
   74130   pCur->nullRow = 0;
   74131 
   74132   break;
   74133 }
   74134 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   74135 
   74136 #ifndef SQLITE_OMIT_VIRTUALTABLE
   74137 /* Opcode: VColumn P1 P2 P3 * *
   74138 ** Synopsis: r[P3]=vcolumn(P2)
   74139 **
   74140 ** Store the value of the P2-th column of
   74141 ** the row of the virtual-table that the
   74142 ** P1 cursor is pointing to into register P3.
   74143 */
   74144 case OP_VColumn: {
   74145   sqlite3_vtab *pVtab;
   74146   const sqlite3_module *pModule;
   74147   Mem *pDest;
   74148   sqlite3_context sContext;
   74149 
   74150   VdbeCursor *pCur = p->apCsr[pOp->p1];
   74151   assert( pCur->pVtabCursor );
   74152   assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
   74153   pDest = &aMem[pOp->p3];
   74154   memAboutToChange(p, pDest);
   74155   if( pCur->nullRow ){
   74156     sqlite3VdbeMemSetNull(pDest);
   74157     break;
   74158   }
   74159   pVtab = pCur->pVtabCursor->pVtab;
   74160   pModule = pVtab->pModule;
   74161   assert( pModule->xColumn );
   74162   memset(&sContext, 0, sizeof(sContext));
   74163 
   74164   /* The output cell may already have a buffer allocated. Move
   74165   ** the current contents to sContext.s so in case the user-function
   74166   ** can use the already allocated buffer instead of allocating a
   74167   ** new one.
   74168   */
   74169   sqlite3VdbeMemMove(&sContext.s, pDest);
   74170   MemSetTypeFlag(&sContext.s, MEM_Null);
   74171 
   74172   rc = pModule->xColumn(pCur->pVtabCursor, &sContext, pOp->p2);
   74173   sqlite3VtabImportErrmsg(p, pVtab);
   74174   if( sContext.isError ){
   74175     rc = sContext.isError;
   74176   }
   74177 
   74178   /* Copy the result of the function to the P3 register. We
   74179   ** do this regardless of whether or not an error occurred to ensure any
   74180   ** dynamic allocation in sContext.s (a Mem struct) is  released.
   74181   */
   74182   sqlite3VdbeChangeEncoding(&sContext.s, encoding);
   74183   sqlite3VdbeMemMove(pDest, &sContext.s);
   74184   REGISTER_TRACE(pOp->p3, pDest);
   74185   UPDATE_MAX_BLOBSIZE(pDest);
   74186 
   74187   if( sqlite3VdbeMemTooBig(pDest) ){
   74188     goto too_big;
   74189   }
   74190   break;
   74191 }
   74192 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   74193 
   74194 #ifndef SQLITE_OMIT_VIRTUALTABLE
   74195 /* Opcode: VNext P1 P2 * * *
   74196 **
   74197 ** Advance virtual table P1 to the next row in its result set and
   74198 ** jump to instruction P2.  Or, if the virtual table has reached
   74199 ** the end of its result set, then fall through to the next instruction.
   74200 */
   74201 case OP_VNext: {   /* jump */
   74202   sqlite3_vtab *pVtab;
   74203   const sqlite3_module *pModule;
   74204   int res;
   74205   VdbeCursor *pCur;
   74206 
   74207   res = 0;
   74208   pCur = p->apCsr[pOp->p1];
   74209   assert( pCur->pVtabCursor );
   74210   if( pCur->nullRow ){
   74211     break;
   74212   }
   74213   pVtab = pCur->pVtabCursor->pVtab;
   74214   pModule = pVtab->pModule;
   74215   assert( pModule->xNext );
   74216 
   74217   /* Invoke the xNext() method of the module. There is no way for the
   74218   ** underlying implementation to return an error if one occurs during
   74219   ** xNext(). Instead, if an error occurs, true is returned (indicating that
   74220   ** data is available) and the error code returned when xColumn or
   74221   ** some other method is next invoked on the save virtual table cursor.
   74222   */
   74223   p->inVtabMethod = 1;
   74224   rc = pModule->xNext(pCur->pVtabCursor);
   74225   p->inVtabMethod = 0;
   74226   sqlite3VtabImportErrmsg(p, pVtab);
   74227   if( rc==SQLITE_OK ){
   74228     res = pModule->xEof(pCur->pVtabCursor);
   74229   }
   74230   VdbeBranchTaken(!res,2);
   74231   if( !res ){
   74232     /* If there is data, jump to P2 */
   74233     pc = pOp->p2 - 1;
   74234   }
   74235   goto check_for_interrupt;
   74236 }
   74237 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   74238 
   74239 #ifndef SQLITE_OMIT_VIRTUALTABLE
   74240 /* Opcode: VRename P1 * * P4 *
   74241 **
   74242 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
   74243 ** This opcode invokes the corresponding xRename method. The value
   74244 ** in register P1 is passed as the zName argument to the xRename method.
   74245 */
   74246 case OP_VRename: {
   74247   sqlite3_vtab *pVtab;
   74248   Mem *pName;
   74249 
   74250   pVtab = pOp->p4.pVtab->pVtab;
   74251   pName = &aMem[pOp->p1];
   74252   assert( pVtab->pModule->xRename );
   74253   assert( memIsValid(pName) );
   74254   assert( p->readOnly==0 );
   74255   REGISTER_TRACE(pOp->p1, pName);
   74256   assert( pName->flags & MEM_Str );
   74257   testcase( pName->enc==SQLITE_UTF8 );
   74258   testcase( pName->enc==SQLITE_UTF16BE );
   74259   testcase( pName->enc==SQLITE_UTF16LE );
   74260   rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
   74261   if( rc==SQLITE_OK ){
   74262     rc = pVtab->pModule->xRename(pVtab, pName->z);
   74263     sqlite3VtabImportErrmsg(p, pVtab);
   74264     p->expired = 0;
   74265   }
   74266   break;
   74267 }
   74268 #endif
   74269 
   74270 #ifndef SQLITE_OMIT_VIRTUALTABLE
   74271 /* Opcode: VUpdate P1 P2 P3 P4 P5
   74272 ** Synopsis: data=r[P3@P2]
   74273 **
   74274 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
   74275 ** This opcode invokes the corresponding xUpdate method. P2 values
   74276 ** are contiguous memory cells starting at P3 to pass to the xUpdate
   74277 ** invocation. The value in register (P3+P2-1) corresponds to the
   74278 ** p2th element of the argv array passed to xUpdate.
   74279 **
   74280 ** The xUpdate method will do a DELETE or an INSERT or both.
   74281 ** The argv[0] element (which corresponds to memory cell P3)
   74282 ** is the rowid of a row to delete.  If argv[0] is NULL then no
   74283 ** deletion occurs.  The argv[1] element is the rowid of the new
   74284 ** row.  This can be NULL to have the virtual table select the new
   74285 ** rowid for itself.  The subsequent elements in the array are
   74286 ** the values of columns in the new row.
   74287 **
   74288 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
   74289 ** a row to delete.
   74290 **
   74291 ** P1 is a boolean flag. If it is set to true and the xUpdate call
   74292 ** is successful, then the value returned by sqlite3_last_insert_rowid()
   74293 ** is set to the value of the rowid for the row just inserted.
   74294 **
   74295 ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
   74296 ** apply in the case of a constraint failure on an insert or update.
   74297 */
   74298 case OP_VUpdate: {
   74299   sqlite3_vtab *pVtab;
   74300   sqlite3_module *pModule;
   74301   int nArg;
   74302   int i;
   74303   sqlite_int64 rowid;
   74304   Mem **apArg;
   74305   Mem *pX;
   74306 
   74307   assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback
   74308        || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
   74309   );
   74310   assert( p->readOnly==0 );
   74311   pVtab = pOp->p4.pVtab->pVtab;
   74312   pModule = (sqlite3_module *)pVtab->pModule;
   74313   nArg = pOp->p2;
   74314   assert( pOp->p4type==P4_VTAB );
   74315   if( ALWAYS(pModule->xUpdate) ){
   74316     u8 vtabOnConflict = db->vtabOnConflict;
   74317     apArg = p->apArg;
   74318     pX = &aMem[pOp->p3];
   74319     for(i=0; i<nArg; i++){
   74320       assert( memIsValid(pX) );
   74321       memAboutToChange(p, pX);
   74322       apArg[i] = pX;
   74323       pX++;
   74324     }
   74325     db->vtabOnConflict = pOp->p5;
   74326     rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
   74327     db->vtabOnConflict = vtabOnConflict;
   74328     sqlite3VtabImportErrmsg(p, pVtab);
   74329     if( rc==SQLITE_OK && pOp->p1 ){
   74330       assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
   74331       db->lastRowid = lastRowid = rowid;
   74332     }
   74333     if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
   74334       if( pOp->p5==OE_Ignore ){
   74335         rc = SQLITE_OK;
   74336       }else{
   74337         p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
   74338       }
   74339     }else{
   74340       p->nChange++;
   74341     }
   74342   }
   74343   break;
   74344 }
   74345 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   74346 
   74347 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
   74348 /* Opcode: Pagecount P1 P2 * * *
   74349 **
   74350 ** Write the current number of pages in database P1 to memory cell P2.
   74351 */
   74352 case OP_Pagecount: {            /* out2-prerelease */
   74353   pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
   74354   break;
   74355 }
   74356 #endif
   74357 
   74358 
   74359 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
   74360 /* Opcode: MaxPgcnt P1 P2 P3 * *
   74361 **
   74362 ** Try to set the maximum page count for database P1 to the value in P3.
   74363 ** Do not let the maximum page count fall below the current page count and
   74364 ** do not change the maximum page count value if P3==0.
   74365 **
   74366 ** Store the maximum page count after the change in register P2.
   74367 */
   74368 case OP_MaxPgcnt: {            /* out2-prerelease */
   74369   unsigned int newMax;
   74370   Btree *pBt;
   74371 
   74372   pBt = db->aDb[pOp->p1].pBt;
   74373   newMax = 0;
   74374   if( pOp->p3 ){
   74375     newMax = sqlite3BtreeLastPage(pBt);
   74376     if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
   74377   }
   74378   pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
   74379   break;
   74380 }
   74381 #endif
   74382 
   74383 
   74384 /* Opcode: Init * P2 * P4 *
   74385 ** Synopsis:  Start at P2
   74386 **
   74387 ** Programs contain a single instance of this opcode as the very first
   74388 ** opcode.
   74389 **
   74390 ** If tracing is enabled (by the sqlite3_trace()) interface, then
   74391 ** the UTF-8 string contained in P4 is emitted on the trace callback.
   74392 ** Or if P4 is blank, use the string returned by sqlite3_sql().
   74393 **
   74394 ** If P2 is not zero, jump to instruction P2.
   74395 */
   74396 case OP_Init: {          /* jump */
   74397   char *zTrace;
   74398   char *z;
   74399 
   74400   if( pOp->p2 ){
   74401     pc = pOp->p2 - 1;
   74402   }
   74403 #ifndef SQLITE_OMIT_TRACE
   74404   if( db->xTrace
   74405    && !p->doingRerun
   74406    && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
   74407   ){
   74408     z = sqlite3VdbeExpandSql(p, zTrace);
   74409     db->xTrace(db->pTraceArg, z);
   74410     sqlite3DbFree(db, z);
   74411   }
   74412 #ifdef SQLITE_USE_FCNTL_TRACE
   74413   zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
   74414   if( zTrace ){
   74415     int i;
   74416     for(i=0; i<db->nDb; i++){
   74417       if( DbMaskTest(p->btreeMask, i)==0 ) continue;
   74418       sqlite3_file_control(db, db->aDb[i].zName, SQLITE_FCNTL_TRACE, zTrace);
   74419     }
   74420   }
   74421 #endif /* SQLITE_USE_FCNTL_TRACE */
   74422 #ifdef SQLITE_DEBUG
   74423   if( (db->flags & SQLITE_SqlTrace)!=0
   74424    && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
   74425   ){
   74426     sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
   74427   }
   74428 #endif /* SQLITE_DEBUG */
   74429 #endif /* SQLITE_OMIT_TRACE */
   74430   break;
   74431 }
   74432 
   74433 
   74434 /* Opcode: Noop * * * * *
   74435 **
   74436 ** Do nothing.  This instruction is often useful as a jump
   74437 ** destination.
   74438 */
   74439 /*
   74440 ** The magic Explain opcode are only inserted when explain==2 (which
   74441 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
   74442 ** This opcode records information from the optimizer.  It is the
   74443 ** the same as a no-op.  This opcodesnever appears in a real VM program.
   74444 */
   74445 default: {          /* This is really OP_Noop and OP_Explain */
   74446   assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
   74447   break;
   74448 }
   74449 
   74450 /*****************************************************************************
   74451 ** The cases of the switch statement above this line should all be indented
   74452 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
   74453 ** readability.  From this point on down, the normal indentation rules are
   74454 ** restored.
   74455 *****************************************************************************/
   74456     }
   74457 
   74458 #ifdef VDBE_PROFILE
   74459     {
   74460       u64 endTime = sqlite3Hwtime();
   74461       if( endTime>start ) pOp->cycles += endTime - start;
   74462       pOp->cnt++;
   74463     }
   74464 #endif
   74465 
   74466     /* The following code adds nothing to the actual functionality
   74467     ** of the program.  It is only here for testing and debugging.
   74468     ** On the other hand, it does burn CPU cycles every time through
   74469     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
   74470     */
   74471 #ifndef NDEBUG
   74472     assert( pc>=-1 && pc<p->nOp );
   74473 
   74474 #ifdef SQLITE_DEBUG
   74475     if( db->flags & SQLITE_VdbeTrace ){
   74476       if( rc!=0 ) printf("rc=%d\n",rc);
   74477       if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
   74478         registerTrace(pOp->p2, &aMem[pOp->p2]);
   74479       }
   74480       if( pOp->opflags & OPFLG_OUT3 ){
   74481         registerTrace(pOp->p3, &aMem[pOp->p3]);
   74482       }
   74483     }
   74484 #endif  /* SQLITE_DEBUG */
   74485 #endif  /* NDEBUG */
   74486   }  /* The end of the for(;;) loop the loops through opcodes */
   74487 
   74488   /* If we reach this point, it means that execution is finished with
   74489   ** an error of some kind.
   74490   */
   74491 vdbe_error_halt:
   74492   assert( rc );
   74493   p->rc = rc;
   74494   testcase( sqlite3GlobalConfig.xLog!=0 );
   74495   sqlite3_log(rc, "statement aborts at %d: [%s] %s",
   74496                    pc, p->zSql, p->zErrMsg);
   74497   sqlite3VdbeHalt(p);
   74498   if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
   74499   rc = SQLITE_ERROR;
   74500   if( resetSchemaOnFault>0 ){
   74501     sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
   74502   }
   74503 
   74504   /* This is the only way out of this procedure.  We have to
   74505   ** release the mutexes on btrees that were acquired at the
   74506   ** top. */
   74507 vdbe_return:
   74508   db->lastRowid = lastRowid;
   74509   testcase( nVmStep>0 );
   74510   p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
   74511   sqlite3VdbeLeave(p);
   74512   return rc;
   74513 
   74514   /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
   74515   ** is encountered.
   74516   */
   74517 too_big:
   74518   sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
   74519   rc = SQLITE_TOOBIG;
   74520   goto vdbe_error_halt;
   74521 
   74522   /* Jump to here if a malloc() fails.
   74523   */
   74524 no_mem:
   74525   db->mallocFailed = 1;
   74526   sqlite3SetString(&p->zErrMsg, db, "out of memory");
   74527   rc = SQLITE_NOMEM;
   74528   goto vdbe_error_halt;
   74529 
   74530   /* Jump to here for any other kind of fatal error.  The "rc" variable
   74531   ** should hold the error number.
   74532   */
   74533 abort_due_to_error:
   74534   assert( p->zErrMsg==0 );
   74535   if( db->mallocFailed ) rc = SQLITE_NOMEM;
   74536   if( rc!=SQLITE_IOERR_NOMEM ){
   74537     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
   74538   }
   74539   goto vdbe_error_halt;
   74540 
   74541   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
   74542   ** flag.
   74543   */
   74544 abort_due_to_interrupt:
   74545   assert( db->u1.isInterrupted );
   74546   rc = SQLITE_INTERRUPT;
   74547   p->rc = rc;
   74548   sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
   74549   goto vdbe_error_halt;
   74550 }
   74551 
   74552 
   74553 /************** End of vdbe.c ************************************************/
   74554 /************** Begin file vdbeblob.c ****************************************/
   74555 /*
   74556 ** 2007 May 1
   74557 **
   74558 ** The author disclaims copyright to this source code.  In place of
   74559 ** a legal notice, here is a blessing:
   74560 **
   74561 **    May you do good and not evil.
   74562 **    May you find forgiveness for yourself and forgive others.
   74563 **    May you share freely, never taking more than you give.
   74564 **
   74565 *************************************************************************
   74566 **
   74567 ** This file contains code used to implement incremental BLOB I/O.
   74568 */
   74569 
   74570 
   74571 #ifndef SQLITE_OMIT_INCRBLOB
   74572 
   74573 /*
   74574 ** Valid sqlite3_blob* handles point to Incrblob structures.
   74575 */
   74576 typedef struct Incrblob Incrblob;
   74577 struct Incrblob {
   74578   int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
   74579   int nByte;              /* Size of open blob, in bytes */
   74580   int iOffset;            /* Byte offset of blob in cursor data */
   74581   int iCol;               /* Table column this handle is open on */
   74582   BtCursor *pCsr;         /* Cursor pointing at blob row */
   74583   sqlite3_stmt *pStmt;    /* Statement holding cursor open */
   74584   sqlite3 *db;            /* The associated database */
   74585 };
   74586 
   74587 
   74588 /*
   74589 ** This function is used by both blob_open() and blob_reopen(). It seeks
   74590 ** the b-tree cursor associated with blob handle p to point to row iRow.
   74591 ** If successful, SQLITE_OK is returned and subsequent calls to
   74592 ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
   74593 **
   74594 ** If an error occurs, or if the specified row does not exist or does not
   74595 ** contain a value of type TEXT or BLOB in the column nominated when the
   74596 ** blob handle was opened, then an error code is returned and *pzErr may
   74597 ** be set to point to a buffer containing an error message. It is the
   74598 ** responsibility of the caller to free the error message buffer using
   74599 ** sqlite3DbFree().
   74600 **
   74601 ** If an error does occur, then the b-tree cursor is closed. All subsequent
   74602 ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
   74603 ** immediately return SQLITE_ABORT.
   74604 */
   74605 static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
   74606   int rc;                         /* Error code */
   74607   char *zErr = 0;                 /* Error message */
   74608   Vdbe *v = (Vdbe *)p->pStmt;
   74609 
   74610   /* Set the value of the SQL statements only variable to integer iRow.
   74611   ** This is done directly instead of using sqlite3_bind_int64() to avoid
   74612   ** triggering asserts related to mutexes.
   74613   */
   74614   assert( v->aVar[0].flags&MEM_Int );
   74615   v->aVar[0].u.i = iRow;
   74616 
   74617   rc = sqlite3_step(p->pStmt);
   74618   if( rc==SQLITE_ROW ){
   74619     VdbeCursor *pC = v->apCsr[0];
   74620     u32 type = pC->aType[p->iCol];
   74621     if( type<12 ){
   74622       zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
   74623           type==0?"null": type==7?"real": "integer"
   74624       );
   74625       rc = SQLITE_ERROR;
   74626       sqlite3_finalize(p->pStmt);
   74627       p->pStmt = 0;
   74628     }else{
   74629       p->iOffset = pC->aType[p->iCol + pC->nField];
   74630       p->nByte = sqlite3VdbeSerialTypeLen(type);
   74631       p->pCsr =  pC->pCursor;
   74632       sqlite3BtreeIncrblobCursor(p->pCsr);
   74633     }
   74634   }
   74635 
   74636   if( rc==SQLITE_ROW ){
   74637     rc = SQLITE_OK;
   74638   }else if( p->pStmt ){
   74639     rc = sqlite3_finalize(p->pStmt);
   74640     p->pStmt = 0;
   74641     if( rc==SQLITE_OK ){
   74642       zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
   74643       rc = SQLITE_ERROR;
   74644     }else{
   74645       zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
   74646     }
   74647   }
   74648 
   74649   assert( rc!=SQLITE_OK || zErr==0 );
   74650   assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
   74651 
   74652   *pzErr = zErr;
   74653   return rc;
   74654 }
   74655 
   74656 /*
   74657 ** Open a blob handle.
   74658 */
   74659 SQLITE_API int sqlite3_blob_open(
   74660   sqlite3* db,            /* The database connection */
   74661   const char *zDb,        /* The attached database containing the blob */
   74662   const char *zTable,     /* The table containing the blob */
   74663   const char *zColumn,    /* The column containing the blob */
   74664   sqlite_int64 iRow,      /* The row containing the glob */
   74665   int flags,              /* True -> read/write access, false -> read-only */
   74666   sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
   74667 ){
   74668   int nAttempt = 0;
   74669   int iCol;               /* Index of zColumn in row-record */
   74670 
   74671   /* This VDBE program seeks a btree cursor to the identified
   74672   ** db/table/row entry. The reason for using a vdbe program instead
   74673   ** of writing code to use the b-tree layer directly is that the
   74674   ** vdbe program will take advantage of the various transaction,
   74675   ** locking and error handling infrastructure built into the vdbe.
   74676   **
   74677   ** After seeking the cursor, the vdbe executes an OP_ResultRow.
   74678   ** Code external to the Vdbe then "borrows" the b-tree cursor and
   74679   ** uses it to implement the blob_read(), blob_write() and
   74680   ** blob_bytes() functions.
   74681   **
   74682   ** The sqlite3_blob_close() function finalizes the vdbe program,
   74683   ** which closes the b-tree cursor and (possibly) commits the
   74684   ** transaction.
   74685   */
   74686   static const int iLn = VDBE_OFFSET_LINENO(4);
   74687   static const VdbeOpList openBlob[] = {
   74688     /* {OP_Transaction, 0, 0, 0},  // 0: Inserted separately */
   74689     {OP_TableLock, 0, 0, 0},       /* 1: Acquire a read or write lock */
   74690     /* One of the following two instructions is replaced by an OP_Noop. */
   74691     {OP_OpenRead, 0, 0, 0},        /* 2: Open cursor 0 for reading */
   74692     {OP_OpenWrite, 0, 0, 0},       /* 3: Open cursor 0 for read/write */
   74693     {OP_Variable, 1, 1, 1},        /* 4: Push the rowid to the stack */
   74694     {OP_NotExists, 0, 10, 1},      /* 5: Seek the cursor */
   74695     {OP_Column, 0, 0, 1},          /* 6  */
   74696     {OP_ResultRow, 1, 0, 0},       /* 7  */
   74697     {OP_Goto, 0, 4, 0},            /* 8  */
   74698     {OP_Close, 0, 0, 0},           /* 9  */
   74699     {OP_Halt, 0, 0, 0},            /* 10 */
   74700   };
   74701 
   74702   int rc = SQLITE_OK;
   74703   char *zErr = 0;
   74704   Table *pTab;
   74705   Parse *pParse = 0;
   74706   Incrblob *pBlob = 0;
   74707 
   74708   flags = !!flags;                /* flags = (flags ? 1 : 0); */
   74709   *ppBlob = 0;
   74710 
   74711   sqlite3_mutex_enter(db->mutex);
   74712 
   74713   pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
   74714   if( !pBlob ) goto blob_open_out;
   74715   pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
   74716   if( !pParse ) goto blob_open_out;
   74717 
   74718   do {
   74719     memset(pParse, 0, sizeof(Parse));
   74720     pParse->db = db;
   74721     sqlite3DbFree(db, zErr);
   74722     zErr = 0;
   74723 
   74724     sqlite3BtreeEnterAll(db);
   74725     pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
   74726     if( pTab && IsVirtual(pTab) ){
   74727       pTab = 0;
   74728       sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
   74729     }
   74730     if( pTab && !HasRowid(pTab) ){
   74731       pTab = 0;
   74732       sqlite3ErrorMsg(pParse, "cannot open table without rowid: %s", zTable);
   74733     }
   74734 #ifndef SQLITE_OMIT_VIEW
   74735     if( pTab && pTab->pSelect ){
   74736       pTab = 0;
   74737       sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
   74738     }
   74739 #endif
   74740     if( !pTab ){
   74741       if( pParse->zErrMsg ){
   74742         sqlite3DbFree(db, zErr);
   74743         zErr = pParse->zErrMsg;
   74744         pParse->zErrMsg = 0;
   74745       }
   74746       rc = SQLITE_ERROR;
   74747       sqlite3BtreeLeaveAll(db);
   74748       goto blob_open_out;
   74749     }
   74750 
   74751     /* Now search pTab for the exact column. */
   74752     for(iCol=0; iCol<pTab->nCol; iCol++) {
   74753       if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
   74754         break;
   74755       }
   74756     }
   74757     if( iCol==pTab->nCol ){
   74758       sqlite3DbFree(db, zErr);
   74759       zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
   74760       rc = SQLITE_ERROR;
   74761       sqlite3BtreeLeaveAll(db);
   74762       goto blob_open_out;
   74763     }
   74764 
   74765     /* If the value is being opened for writing, check that the
   74766     ** column is not indexed, and that it is not part of a foreign key.
   74767     ** It is against the rules to open a column to which either of these
   74768     ** descriptions applies for writing.  */
   74769     if( flags ){
   74770       const char *zFault = 0;
   74771       Index *pIdx;
   74772 #ifndef SQLITE_OMIT_FOREIGN_KEY
   74773       if( db->flags&SQLITE_ForeignKeys ){
   74774         /* Check that the column is not part of an FK child key definition. It
   74775         ** is not necessary to check if it is part of a parent key, as parent
   74776         ** key columns must be indexed. The check below will pick up this
   74777         ** case.  */
   74778         FKey *pFKey;
   74779         for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
   74780           int j;
   74781           for(j=0; j<pFKey->nCol; j++){
   74782             if( pFKey->aCol[j].iFrom==iCol ){
   74783               zFault = "foreign key";
   74784             }
   74785           }
   74786         }
   74787       }
   74788 #endif
   74789       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   74790         int j;
   74791         for(j=0; j<pIdx->nKeyCol; j++){
   74792           if( pIdx->aiColumn[j]==iCol ){
   74793             zFault = "indexed";
   74794           }
   74795         }
   74796       }
   74797       if( zFault ){
   74798         sqlite3DbFree(db, zErr);
   74799         zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
   74800         rc = SQLITE_ERROR;
   74801         sqlite3BtreeLeaveAll(db);
   74802         goto blob_open_out;
   74803       }
   74804     }
   74805 
   74806     pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(pParse);
   74807     assert( pBlob->pStmt || db->mallocFailed );
   74808     if( pBlob->pStmt ){
   74809       Vdbe *v = (Vdbe *)pBlob->pStmt;
   74810       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   74811 
   74812 
   74813       sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, flags,
   74814                            pTab->pSchema->schema_cookie,
   74815                            pTab->pSchema->iGeneration);
   74816       sqlite3VdbeChangeP5(v, 1);
   74817       sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
   74818 
   74819       /* Make sure a mutex is held on the table to be accessed */
   74820       sqlite3VdbeUsesBtree(v, iDb);
   74821 
   74822       /* Configure the OP_TableLock instruction */
   74823 #ifdef SQLITE_OMIT_SHARED_CACHE
   74824       sqlite3VdbeChangeToNoop(v, 1);
   74825 #else
   74826       sqlite3VdbeChangeP1(v, 1, iDb);
   74827       sqlite3VdbeChangeP2(v, 1, pTab->tnum);
   74828       sqlite3VdbeChangeP3(v, 1, flags);
   74829       sqlite3VdbeChangeP4(v, 1, pTab->zName, P4_TRANSIENT);
   74830 #endif
   74831 
   74832       /* Remove either the OP_OpenWrite or OpenRead. Set the P2
   74833       ** parameter of the other to pTab->tnum.  */
   74834       sqlite3VdbeChangeToNoop(v, 3 - flags);
   74835       sqlite3VdbeChangeP2(v, 2 + flags, pTab->tnum);
   74836       sqlite3VdbeChangeP3(v, 2 + flags, iDb);
   74837 
   74838       /* Configure the number of columns. Configure the cursor to
   74839       ** think that the table has one more column than it really
   74840       ** does. An OP_Column to retrieve this imaginary column will
   74841       ** always return an SQL NULL. This is useful because it means
   74842       ** we can invoke OP_Column to fill in the vdbe cursors type
   74843       ** and offset cache without causing any IO.
   74844       */
   74845       sqlite3VdbeChangeP4(v, 2+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
   74846       sqlite3VdbeChangeP2(v, 6, pTab->nCol);
   74847       if( !db->mallocFailed ){
   74848         pParse->nVar = 1;
   74849         pParse->nMem = 1;
   74850         pParse->nTab = 1;
   74851         sqlite3VdbeMakeReady(v, pParse);
   74852       }
   74853     }
   74854 
   74855     pBlob->flags = flags;
   74856     pBlob->iCol = iCol;
   74857     pBlob->db = db;
   74858     sqlite3BtreeLeaveAll(db);
   74859     if( db->mallocFailed ){
   74860       goto blob_open_out;
   74861     }
   74862     sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
   74863     rc = blobSeekToRow(pBlob, iRow, &zErr);
   74864   } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
   74865 
   74866 blob_open_out:
   74867   if( rc==SQLITE_OK && db->mallocFailed==0 ){
   74868     *ppBlob = (sqlite3_blob *)pBlob;
   74869   }else{
   74870     if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
   74871     sqlite3DbFree(db, pBlob);
   74872   }
   74873   sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
   74874   sqlite3DbFree(db, zErr);
   74875   sqlite3ParserReset(pParse);
   74876   sqlite3StackFree(db, pParse);
   74877   rc = sqlite3ApiExit(db, rc);
   74878   sqlite3_mutex_leave(db->mutex);
   74879   return rc;
   74880 }
   74881 
   74882 /*
   74883 ** Close a blob handle that was previously created using
   74884 ** sqlite3_blob_open().
   74885 */
   74886 SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
   74887   Incrblob *p = (Incrblob *)pBlob;
   74888   int rc;
   74889   sqlite3 *db;
   74890 
   74891   if( p ){
   74892     db = p->db;
   74893     sqlite3_mutex_enter(db->mutex);
   74894     rc = sqlite3_finalize(p->pStmt);
   74895     sqlite3DbFree(db, p);
   74896     sqlite3_mutex_leave(db->mutex);
   74897   }else{
   74898     rc = SQLITE_OK;
   74899   }
   74900   return rc;
   74901 }
   74902 
   74903 /*
   74904 ** Perform a read or write operation on a blob
   74905 */
   74906 static int blobReadWrite(
   74907   sqlite3_blob *pBlob,
   74908   void *z,
   74909   int n,
   74910   int iOffset,
   74911   int (*xCall)(BtCursor*, u32, u32, void*)
   74912 ){
   74913   int rc;
   74914   Incrblob *p = (Incrblob *)pBlob;
   74915   Vdbe *v;
   74916   sqlite3 *db;
   74917 
   74918   if( p==0 ) return SQLITE_MISUSE_BKPT;
   74919   db = p->db;
   74920   sqlite3_mutex_enter(db->mutex);
   74921   v = (Vdbe*)p->pStmt;
   74922 
   74923   if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
   74924     /* Request is out of range. Return a transient error. */
   74925     rc = SQLITE_ERROR;
   74926     sqlite3Error(db, SQLITE_ERROR, 0);
   74927   }else if( v==0 ){
   74928     /* If there is no statement handle, then the blob-handle has
   74929     ** already been invalidated. Return SQLITE_ABORT in this case.
   74930     */
   74931     rc = SQLITE_ABORT;
   74932   }else{
   74933     /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
   74934     ** returned, clean-up the statement handle.
   74935     */
   74936     assert( db == v->db );
   74937     sqlite3BtreeEnterCursor(p->pCsr);
   74938     rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
   74939     sqlite3BtreeLeaveCursor(p->pCsr);
   74940     if( rc==SQLITE_ABORT ){
   74941       sqlite3VdbeFinalize(v);
   74942       p->pStmt = 0;
   74943     }else{
   74944       db->errCode = rc;
   74945       v->rc = rc;
   74946     }
   74947   }
   74948   rc = sqlite3ApiExit(db, rc);
   74949   sqlite3_mutex_leave(db->mutex);
   74950   return rc;
   74951 }
   74952 
   74953 /*
   74954 ** Read data from a blob handle.
   74955 */
   74956 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
   74957   return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
   74958 }
   74959 
   74960 /*
   74961 ** Write data to a blob handle.
   74962 */
   74963 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
   74964   return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
   74965 }
   74966 
   74967 /*
   74968 ** Query a blob handle for the size of the data.
   74969 **
   74970 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
   74971 ** so no mutex is required for access.
   74972 */
   74973 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
   74974   Incrblob *p = (Incrblob *)pBlob;
   74975   return (p && p->pStmt) ? p->nByte : 0;
   74976 }
   74977 
   74978 /*
   74979 ** Move an existing blob handle to point to a different row of the same
   74980 ** database table.
   74981 **
   74982 ** If an error occurs, or if the specified row does not exist or does not
   74983 ** contain a blob or text value, then an error code is returned and the
   74984 ** database handle error code and message set. If this happens, then all
   74985 ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
   74986 ** immediately return SQLITE_ABORT.
   74987 */
   74988 SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
   74989   int rc;
   74990   Incrblob *p = (Incrblob *)pBlob;
   74991   sqlite3 *db;
   74992 
   74993   if( p==0 ) return SQLITE_MISUSE_BKPT;
   74994   db = p->db;
   74995   sqlite3_mutex_enter(db->mutex);
   74996 
   74997   if( p->pStmt==0 ){
   74998     /* If there is no statement handle, then the blob-handle has
   74999     ** already been invalidated. Return SQLITE_ABORT in this case.
   75000     */
   75001     rc = SQLITE_ABORT;
   75002   }else{
   75003     char *zErr;
   75004     rc = blobSeekToRow(p, iRow, &zErr);
   75005     if( rc!=SQLITE_OK ){
   75006       sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
   75007       sqlite3DbFree(db, zErr);
   75008     }
   75009     assert( rc!=SQLITE_SCHEMA );
   75010   }
   75011 
   75012   rc = sqlite3ApiExit(db, rc);
   75013   assert( rc==SQLITE_OK || p->pStmt==0 );
   75014   sqlite3_mutex_leave(db->mutex);
   75015   return rc;
   75016 }
   75017 
   75018 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
   75019 
   75020 /************** End of vdbeblob.c ********************************************/
   75021 /************** Begin file vdbesort.c ****************************************/
   75022 /*
   75023 ** 2011 July 9
   75024 **
   75025 ** The author disclaims copyright to this source code.  In place of
   75026 ** a legal notice, here is a blessing:
   75027 **
   75028 **    May you do good and not evil.
   75029 **    May you find forgiveness for yourself and forgive others.
   75030 **    May you share freely, never taking more than you give.
   75031 **
   75032 *************************************************************************
   75033 ** This file contains code for the VdbeSorter object, used in concert with
   75034 ** a VdbeCursor to sort large numbers of keys (as may be required, for
   75035 ** example, by CREATE INDEX statements on tables too large to fit in main
   75036 ** memory).
   75037 */
   75038 
   75039 
   75040 
   75041 typedef struct VdbeSorterIter VdbeSorterIter;
   75042 typedef struct SorterRecord SorterRecord;
   75043 typedef struct FileWriter FileWriter;
   75044 
   75045 /*
   75046 ** NOTES ON DATA STRUCTURE USED FOR N-WAY MERGES:
   75047 **
   75048 ** As keys are added to the sorter, they are written to disk in a series
   75049 ** of sorted packed-memory-arrays (PMAs). The size of each PMA is roughly
   75050 ** the same as the cache-size allowed for temporary databases. In order
   75051 ** to allow the caller to extract keys from the sorter in sorted order,
   75052 ** all PMAs currently stored on disk must be merged together. This comment
   75053 ** describes the data structure used to do so. The structure supports
   75054 ** merging any number of arrays in a single pass with no redundant comparison
   75055 ** operations.
   75056 **
   75057 ** The aIter[] array contains an iterator for each of the PMAs being merged.
   75058 ** An aIter[] iterator either points to a valid key or else is at EOF. For
   75059 ** the purposes of the paragraphs below, we assume that the array is actually
   75060 ** N elements in size, where N is the smallest power of 2 greater to or equal
   75061 ** to the number of iterators being merged. The extra aIter[] elements are
   75062 ** treated as if they are empty (always at EOF).
   75063 **
   75064 ** The aTree[] array is also N elements in size. The value of N is stored in
   75065 ** the VdbeSorter.nTree variable.
   75066 **
   75067 ** The final (N/2) elements of aTree[] contain the results of comparing
   75068 ** pairs of iterator keys together. Element i contains the result of
   75069 ** comparing aIter[2*i-N] and aIter[2*i-N+1]. Whichever key is smaller, the
   75070 ** aTree element is set to the index of it.
   75071 **
   75072 ** For the purposes of this comparison, EOF is considered greater than any
   75073 ** other key value. If the keys are equal (only possible with two EOF
   75074 ** values), it doesn't matter which index is stored.
   75075 **
   75076 ** The (N/4) elements of aTree[] that precede the final (N/2) described
   75077 ** above contains the index of the smallest of each block of 4 iterators.
   75078 ** And so on. So that aTree[1] contains the index of the iterator that
   75079 ** currently points to the smallest key value. aTree[0] is unused.
   75080 **
   75081 ** Example:
   75082 **
   75083 **     aIter[0] -> Banana
   75084 **     aIter[1] -> Feijoa
   75085 **     aIter[2] -> Elderberry
   75086 **     aIter[3] -> Currant
   75087 **     aIter[4] -> Grapefruit
   75088 **     aIter[5] -> Apple
   75089 **     aIter[6] -> Durian
   75090 **     aIter[7] -> EOF
   75091 **
   75092 **     aTree[] = { X, 5   0, 5    0, 3, 5, 6 }
   75093 **
   75094 ** The current element is "Apple" (the value of the key indicated by
   75095 ** iterator 5). When the Next() operation is invoked, iterator 5 will
   75096 ** be advanced to the next key in its segment. Say the next key is
   75097 ** "Eggplant":
   75098 **
   75099 **     aIter[5] -> Eggplant
   75100 **
   75101 ** The contents of aTree[] are updated first by comparing the new iterator
   75102 ** 5 key to the current key of iterator 4 (still "Grapefruit"). The iterator
   75103 ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
   75104 ** The value of iterator 6 - "Durian" - is now smaller than that of iterator
   75105 ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
   75106 ** so the value written into element 1 of the array is 0. As follows:
   75107 **
   75108 **     aTree[] = { X, 0   0, 6    0, 3, 5, 6 }
   75109 **
   75110 ** In other words, each time we advance to the next sorter element, log2(N)
   75111 ** key comparison operations are required, where N is the number of segments
   75112 ** being merged (rounded up to the next power of 2).
   75113 */
   75114 struct VdbeSorter {
   75115   i64 iWriteOff;                  /* Current write offset within file pTemp1 */
   75116   i64 iReadOff;                   /* Current read offset within file pTemp1 */
   75117   int nInMemory;                  /* Current size of pRecord list as PMA */
   75118   int nTree;                      /* Used size of aTree/aIter (power of 2) */
   75119   int nPMA;                       /* Number of PMAs stored in pTemp1 */
   75120   int mnPmaSize;                  /* Minimum PMA size, in bytes */
   75121   int mxPmaSize;                  /* Maximum PMA size, in bytes.  0==no limit */
   75122   VdbeSorterIter *aIter;          /* Array of iterators to merge */
   75123   int *aTree;                     /* Current state of incremental merge */
   75124   sqlite3_file *pTemp1;           /* PMA file 1 */
   75125   SorterRecord *pRecord;          /* Head of in-memory record list */
   75126   UnpackedRecord *pUnpacked;      /* Used to unpack keys */
   75127 };
   75128 
   75129 /*
   75130 ** The following type is an iterator for a PMA. It caches the current key in
   75131 ** variables nKey/aKey. If the iterator is at EOF, pFile==0.
   75132 */
   75133 struct VdbeSorterIter {
   75134   i64 iReadOff;                   /* Current read offset */
   75135   i64 iEof;                       /* 1 byte past EOF for this iterator */
   75136   int nAlloc;                     /* Bytes of space at aAlloc */
   75137   int nKey;                       /* Number of bytes in key */
   75138   sqlite3_file *pFile;            /* File iterator is reading from */
   75139   u8 *aAlloc;                     /* Allocated space */
   75140   u8 *aKey;                       /* Pointer to current key */
   75141   u8 *aBuffer;                    /* Current read buffer */
   75142   int nBuffer;                    /* Size of read buffer in bytes */
   75143 };
   75144 
   75145 /*
   75146 ** An instance of this structure is used to organize the stream of records
   75147 ** being written to files by the merge-sort code into aligned, page-sized
   75148 ** blocks.  Doing all I/O in aligned page-sized blocks helps I/O to go
   75149 ** faster on many operating systems.
   75150 */
   75151 struct FileWriter {
   75152   int eFWErr;                     /* Non-zero if in an error state */
   75153   u8 *aBuffer;                    /* Pointer to write buffer */
   75154   int nBuffer;                    /* Size of write buffer in bytes */
   75155   int iBufStart;                  /* First byte of buffer to write */
   75156   int iBufEnd;                    /* Last byte of buffer to write */
   75157   i64 iWriteOff;                  /* Offset of start of buffer in file */
   75158   sqlite3_file *pFile;            /* File to write to */
   75159 };
   75160 
   75161 /*
   75162 ** A structure to store a single record. All in-memory records are connected
   75163 ** together into a linked list headed at VdbeSorter.pRecord using the
   75164 ** SorterRecord.pNext pointer.
   75165 */
   75166 struct SorterRecord {
   75167   void *pVal;
   75168   int nVal;
   75169   SorterRecord *pNext;
   75170 };
   75171 
   75172 /* Minimum allowable value for the VdbeSorter.nWorking variable */
   75173 #define SORTER_MIN_WORKING 10
   75174 
   75175 /* Maximum number of segments to merge in a single pass. */
   75176 #define SORTER_MAX_MERGE_COUNT 16
   75177 
   75178 /*
   75179 ** Free all memory belonging to the VdbeSorterIter object passed as the second
   75180 ** argument. All structure fields are set to zero before returning.
   75181 */
   75182 static void vdbeSorterIterZero(sqlite3 *db, VdbeSorterIter *pIter){
   75183   sqlite3DbFree(db, pIter->aAlloc);
   75184   sqlite3DbFree(db, pIter->aBuffer);
   75185   memset(pIter, 0, sizeof(VdbeSorterIter));
   75186 }
   75187 
   75188 /*
   75189 ** Read nByte bytes of data from the stream of data iterated by object p.
   75190 ** If successful, set *ppOut to point to a buffer containing the data
   75191 ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
   75192 ** error code.
   75193 **
   75194 ** The buffer indicated by *ppOut may only be considered valid until the
   75195 ** next call to this function.
   75196 */
   75197 static int vdbeSorterIterRead(
   75198   sqlite3 *db,                    /* Database handle (for malloc) */
   75199   VdbeSorterIter *p,              /* Iterator */
   75200   int nByte,                      /* Bytes of data to read */
   75201   u8 **ppOut                      /* OUT: Pointer to buffer containing data */
   75202 ){
   75203   int iBuf;                       /* Offset within buffer to read from */
   75204   int nAvail;                     /* Bytes of data available in buffer */
   75205   assert( p->aBuffer );
   75206 
   75207   /* If there is no more data to be read from the buffer, read the next
   75208   ** p->nBuffer bytes of data from the file into it. Or, if there are less
   75209   ** than p->nBuffer bytes remaining in the PMA, read all remaining data.  */
   75210   iBuf = p->iReadOff % p->nBuffer;
   75211   if( iBuf==0 ){
   75212     int nRead;                    /* Bytes to read from disk */
   75213     int rc;                       /* sqlite3OsRead() return code */
   75214 
   75215     /* Determine how many bytes of data to read. */
   75216     if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
   75217       nRead = p->nBuffer;
   75218     }else{
   75219       nRead = (int)(p->iEof - p->iReadOff);
   75220     }
   75221     assert( nRead>0 );
   75222 
   75223     /* Read data from the file. Return early if an error occurs. */
   75224     rc = sqlite3OsRead(p->pFile, p->aBuffer, nRead, p->iReadOff);
   75225     assert( rc!=SQLITE_IOERR_SHORT_READ );
   75226     if( rc!=SQLITE_OK ) return rc;
   75227   }
   75228   nAvail = p->nBuffer - iBuf;
   75229 
   75230   if( nByte<=nAvail ){
   75231     /* The requested data is available in the in-memory buffer. In this
   75232     ** case there is no need to make a copy of the data, just return a
   75233     ** pointer into the buffer to the caller.  */
   75234     *ppOut = &p->aBuffer[iBuf];
   75235     p->iReadOff += nByte;
   75236   }else{
   75237     /* The requested data is not all available in the in-memory buffer.
   75238     ** In this case, allocate space at p->aAlloc[] to copy the requested
   75239     ** range into. Then return a copy of pointer p->aAlloc to the caller.  */
   75240     int nRem;                     /* Bytes remaining to copy */
   75241 
   75242     /* Extend the p->aAlloc[] allocation if required. */
   75243     if( p->nAlloc<nByte ){
   75244       int nNew = p->nAlloc*2;
   75245       while( nByte>nNew ) nNew = nNew*2;
   75246       p->aAlloc = sqlite3DbReallocOrFree(db, p->aAlloc, nNew);
   75247       if( !p->aAlloc ) return SQLITE_NOMEM;
   75248       p->nAlloc = nNew;
   75249     }
   75250 
   75251     /* Copy as much data as is available in the buffer into the start of
   75252     ** p->aAlloc[].  */
   75253     memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
   75254     p->iReadOff += nAvail;
   75255     nRem = nByte - nAvail;
   75256 
   75257     /* The following loop copies up to p->nBuffer bytes per iteration into
   75258     ** the p->aAlloc[] buffer.  */
   75259     while( nRem>0 ){
   75260       int rc;                     /* vdbeSorterIterRead() return code */
   75261       int nCopy;                  /* Number of bytes to copy */
   75262       u8 *aNext;                  /* Pointer to buffer to copy data from */
   75263 
   75264       nCopy = nRem;
   75265       if( nRem>p->nBuffer ) nCopy = p->nBuffer;
   75266       rc = vdbeSorterIterRead(db, p, nCopy, &aNext);
   75267       if( rc!=SQLITE_OK ) return rc;
   75268       assert( aNext!=p->aAlloc );
   75269       memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
   75270       nRem -= nCopy;
   75271     }
   75272 
   75273     *ppOut = p->aAlloc;
   75274   }
   75275 
   75276   return SQLITE_OK;
   75277 }
   75278 
   75279 /*
   75280 ** Read a varint from the stream of data accessed by p. Set *pnOut to
   75281 ** the value read.
   75282 */
   75283 static int vdbeSorterIterVarint(sqlite3 *db, VdbeSorterIter *p, u64 *pnOut){
   75284   int iBuf;
   75285 
   75286   iBuf = p->iReadOff % p->nBuffer;
   75287   if( iBuf && (p->nBuffer-iBuf)>=9 ){
   75288     p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
   75289   }else{
   75290     u8 aVarint[16], *a;
   75291     int i = 0, rc;
   75292     do{
   75293       rc = vdbeSorterIterRead(db, p, 1, &a);
   75294       if( rc ) return rc;
   75295       aVarint[(i++)&0xf] = a[0];
   75296     }while( (a[0]&0x80)!=0 );
   75297     sqlite3GetVarint(aVarint, pnOut);
   75298   }
   75299 
   75300   return SQLITE_OK;
   75301 }
   75302 
   75303 
   75304 /*
   75305 ** Advance iterator pIter to the next key in its PMA. Return SQLITE_OK if
   75306 ** no error occurs, or an SQLite error code if one does.
   75307 */
   75308 static int vdbeSorterIterNext(
   75309   sqlite3 *db,                    /* Database handle (for sqlite3DbMalloc() ) */
   75310   VdbeSorterIter *pIter           /* Iterator to advance */
   75311 ){
   75312   int rc;                         /* Return Code */
   75313   u64 nRec = 0;                   /* Size of record in bytes */
   75314 
   75315   if( pIter->iReadOff>=pIter->iEof ){
   75316     /* This is an EOF condition */
   75317     vdbeSorterIterZero(db, pIter);
   75318     return SQLITE_OK;
   75319   }
   75320 
   75321   rc = vdbeSorterIterVarint(db, pIter, &nRec);
   75322   if( rc==SQLITE_OK ){
   75323     pIter->nKey = (int)nRec;
   75324     rc = vdbeSorterIterRead(db, pIter, (int)nRec, &pIter->aKey);
   75325   }
   75326 
   75327   return rc;
   75328 }
   75329 
   75330 /*
   75331 ** Initialize iterator pIter to scan through the PMA stored in file pFile
   75332 ** starting at offset iStart and ending at offset iEof-1. This function
   75333 ** leaves the iterator pointing to the first key in the PMA (or EOF if the
   75334 ** PMA is empty).
   75335 */
   75336 static int vdbeSorterIterInit(
   75337   sqlite3 *db,                    /* Database handle */
   75338   const VdbeSorter *pSorter,      /* Sorter object */
   75339   i64 iStart,                     /* Start offset in pFile */
   75340   VdbeSorterIter *pIter,          /* Iterator to populate */
   75341   i64 *pnByte                     /* IN/OUT: Increment this value by PMA size */
   75342 ){
   75343   int rc = SQLITE_OK;
   75344   int nBuf;
   75345 
   75346   nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
   75347 
   75348   assert( pSorter->iWriteOff>iStart );
   75349   assert( pIter->aAlloc==0 );
   75350   assert( pIter->aBuffer==0 );
   75351   pIter->pFile = pSorter->pTemp1;
   75352   pIter->iReadOff = iStart;
   75353   pIter->nAlloc = 128;
   75354   pIter->aAlloc = (u8 *)sqlite3DbMallocRaw(db, pIter->nAlloc);
   75355   pIter->nBuffer = nBuf;
   75356   pIter->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);
   75357 
   75358   if( !pIter->aBuffer ){
   75359     rc = SQLITE_NOMEM;
   75360   }else{
   75361     int iBuf;
   75362 
   75363     iBuf = iStart % nBuf;
   75364     if( iBuf ){
   75365       int nRead = nBuf - iBuf;
   75366       if( (iStart + nRead) > pSorter->iWriteOff ){
   75367         nRead = (int)(pSorter->iWriteOff - iStart);
   75368       }
   75369       rc = sqlite3OsRead(
   75370           pSorter->pTemp1, &pIter->aBuffer[iBuf], nRead, iStart
   75371       );
   75372     }
   75373 
   75374     if( rc==SQLITE_OK ){
   75375       u64 nByte;                       /* Size of PMA in bytes */
   75376       pIter->iEof = pSorter->iWriteOff;
   75377       rc = vdbeSorterIterVarint(db, pIter, &nByte);
   75378       pIter->iEof = pIter->iReadOff + nByte;
   75379       *pnByte += nByte;
   75380     }
   75381   }
   75382 
   75383   if( rc==SQLITE_OK ){
   75384     rc = vdbeSorterIterNext(db, pIter);
   75385   }
   75386   return rc;
   75387 }
   75388 
   75389 
   75390 /*
   75391 ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
   75392 ** size nKey2 bytes).  Argument pKeyInfo supplies the collation functions
   75393 ** used by the comparison. If an error occurs, return an SQLite error code.
   75394 ** Otherwise, return SQLITE_OK and set *pRes to a negative, zero or positive
   75395 ** value, depending on whether key1 is smaller, equal to or larger than key2.
   75396 **
   75397 ** If the bOmitRowid argument is non-zero, assume both keys end in a rowid
   75398 ** field. For the purposes of the comparison, ignore it. Also, if bOmitRowid
   75399 ** is true and key1 contains even a single NULL value, it is considered to
   75400 ** be less than key2. Even if key2 also contains NULL values.
   75401 **
   75402 ** If pKey2 is passed a NULL pointer, then it is assumed that the pCsr->aSpace
   75403 ** has been allocated and contains an unpacked record that is used as key2.
   75404 */
   75405 static void vdbeSorterCompare(
   75406   const VdbeCursor *pCsr,         /* Cursor object (for pKeyInfo) */
   75407   int nKeyCol,                    /* Num of columns. 0 means "all" */
   75408   const void *pKey1, int nKey1,   /* Left side of comparison */
   75409   const void *pKey2, int nKey2,   /* Right side of comparison */
   75410   int *pRes                       /* OUT: Result of comparison */
   75411 ){
   75412   KeyInfo *pKeyInfo = pCsr->pKeyInfo;
   75413   VdbeSorter *pSorter = pCsr->pSorter;
   75414   UnpackedRecord *r2 = pSorter->pUnpacked;
   75415   int i;
   75416 
   75417   if( pKey2 ){
   75418     sqlite3VdbeRecordUnpack(pKeyInfo, nKey2, pKey2, r2);
   75419   }
   75420 
   75421   if( nKeyCol ){
   75422     r2->nField = nKeyCol;
   75423     for(i=0; i<nKeyCol; i++){
   75424       if( r2->aMem[i].flags & MEM_Null ){
   75425         *pRes = -1;
   75426         return;
   75427       }
   75428     }
   75429     assert( r2->default_rc==0 );
   75430   }
   75431 
   75432   *pRes = sqlite3VdbeRecordCompare(nKey1, pKey1, r2, 0);
   75433 }
   75434 
   75435 /*
   75436 ** This function is called to compare two iterator keys when merging
   75437 ** multiple b-tree segments. Parameter iOut is the index of the aTree[]
   75438 ** value to recalculate.
   75439 */
   75440 static int vdbeSorterDoCompare(const VdbeCursor *pCsr, int iOut){
   75441   VdbeSorter *pSorter = pCsr->pSorter;
   75442   int i1;
   75443   int i2;
   75444   int iRes;
   75445   VdbeSorterIter *p1;
   75446   VdbeSorterIter *p2;
   75447 
   75448   assert( iOut<pSorter->nTree && iOut>0 );
   75449 
   75450   if( iOut>=(pSorter->nTree/2) ){
   75451     i1 = (iOut - pSorter->nTree/2) * 2;
   75452     i2 = i1 + 1;
   75453   }else{
   75454     i1 = pSorter->aTree[iOut*2];
   75455     i2 = pSorter->aTree[iOut*2+1];
   75456   }
   75457 
   75458   p1 = &pSorter->aIter[i1];
   75459   p2 = &pSorter->aIter[i2];
   75460 
   75461   if( p1->pFile==0 ){
   75462     iRes = i2;
   75463   }else if( p2->pFile==0 ){
   75464     iRes = i1;
   75465   }else{
   75466     int res;
   75467     assert( pCsr->pSorter->pUnpacked!=0 );  /* allocated in vdbeSorterMerge() */
   75468     vdbeSorterCompare(
   75469         pCsr, 0, p1->aKey, p1->nKey, p2->aKey, p2->nKey, &res
   75470     );
   75471     if( res<=0 ){
   75472       iRes = i1;
   75473     }else{
   75474       iRes = i2;
   75475     }
   75476   }
   75477 
   75478   pSorter->aTree[iOut] = iRes;
   75479   return SQLITE_OK;
   75480 }
   75481 
   75482 /*
   75483 ** Initialize the temporary index cursor just opened as a sorter cursor.
   75484 */
   75485 SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *db, VdbeCursor *pCsr){
   75486   int pgsz;                       /* Page size of main database */
   75487   int mxCache;                    /* Cache size */
   75488   VdbeSorter *pSorter;            /* The new sorter */
   75489   char *d;                        /* Dummy */
   75490 
   75491   assert( pCsr->pKeyInfo && pCsr->pBt==0 );
   75492   pCsr->pSorter = pSorter = sqlite3DbMallocZero(db, sizeof(VdbeSorter));
   75493   if( pSorter==0 ){
   75494     return SQLITE_NOMEM;
   75495   }
   75496 
   75497   pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pCsr->pKeyInfo, 0, 0, &d);
   75498   if( pSorter->pUnpacked==0 ) return SQLITE_NOMEM;
   75499   assert( pSorter->pUnpacked==(UnpackedRecord *)d );
   75500 
   75501   if( !sqlite3TempInMemory(db) ){
   75502     pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
   75503     pSorter->mnPmaSize = SORTER_MIN_WORKING * pgsz;
   75504     mxCache = db->aDb[0].pSchema->cache_size;
   75505     if( mxCache<SORTER_MIN_WORKING ) mxCache = SORTER_MIN_WORKING;
   75506     pSorter->mxPmaSize = mxCache * pgsz;
   75507   }
   75508 
   75509   return SQLITE_OK;
   75510 }
   75511 
   75512 /*
   75513 ** Free the list of sorted records starting at pRecord.
   75514 */
   75515 static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
   75516   SorterRecord *p;
   75517   SorterRecord *pNext;
   75518   for(p=pRecord; p; p=pNext){
   75519     pNext = p->pNext;
   75520     sqlite3DbFree(db, p);
   75521   }
   75522 }
   75523 
   75524 /*
   75525 ** Reset a sorting cursor back to its original empty state.
   75526 */
   75527 SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){
   75528   if( pSorter->aIter ){
   75529     int i;
   75530     for(i=0; i<pSorter->nTree; i++){
   75531       vdbeSorterIterZero(db, &pSorter->aIter[i]);
   75532     }
   75533     sqlite3DbFree(db, pSorter->aIter);
   75534     pSorter->aIter = 0;
   75535   }
   75536   if( pSorter->pTemp1 ){
   75537     sqlite3OsCloseFree(pSorter->pTemp1);
   75538     pSorter->pTemp1 = 0;
   75539   }
   75540   vdbeSorterRecordFree(db, pSorter->pRecord);
   75541   pSorter->pRecord = 0;
   75542   pSorter->iWriteOff = 0;
   75543   pSorter->iReadOff = 0;
   75544   pSorter->nInMemory = 0;
   75545   pSorter->nTree = 0;
   75546   pSorter->nPMA = 0;
   75547   pSorter->aTree = 0;
   75548 }
   75549 
   75550 
   75551 /*
   75552 ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
   75553 */
   75554 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
   75555   VdbeSorter *pSorter = pCsr->pSorter;
   75556   if( pSorter ){
   75557     sqlite3VdbeSorterReset(db, pSorter);
   75558     sqlite3DbFree(db, pSorter->pUnpacked);
   75559     sqlite3DbFree(db, pSorter);
   75560     pCsr->pSorter = 0;
   75561   }
   75562 }
   75563 
   75564 /*
   75565 ** Allocate space for a file-handle and open a temporary file. If successful,
   75566 ** set *ppFile to point to the malloc'd file-handle and return SQLITE_OK.
   75567 ** Otherwise, set *ppFile to 0 and return an SQLite error code.
   75568 */
   75569 static int vdbeSorterOpenTempFile(sqlite3 *db, sqlite3_file **ppFile){
   75570   int dummy;
   75571   return sqlite3OsOpenMalloc(db->pVfs, 0, ppFile,
   75572       SQLITE_OPEN_TEMP_JOURNAL |
   75573       SQLITE_OPEN_READWRITE    | SQLITE_OPEN_CREATE |
   75574       SQLITE_OPEN_EXCLUSIVE    | SQLITE_OPEN_DELETEONCLOSE, &dummy
   75575   );
   75576 }
   75577 
   75578 /*
   75579 ** Merge the two sorted lists p1 and p2 into a single list.
   75580 ** Set *ppOut to the head of the new list.
   75581 */
   75582 static void vdbeSorterMerge(
   75583   const VdbeCursor *pCsr,         /* For pKeyInfo */
   75584   SorterRecord *p1,               /* First list to merge */
   75585   SorterRecord *p2,               /* Second list to merge */
   75586   SorterRecord **ppOut            /* OUT: Head of merged list */
   75587 ){
   75588   SorterRecord *pFinal = 0;
   75589   SorterRecord **pp = &pFinal;
   75590   void *pVal2 = p2 ? p2->pVal : 0;
   75591 
   75592   while( p1 && p2 ){
   75593     int res;
   75594     vdbeSorterCompare(pCsr, 0, p1->pVal, p1->nVal, pVal2, p2->nVal, &res);
   75595     if( res<=0 ){
   75596       *pp = p1;
   75597       pp = &p1->pNext;
   75598       p1 = p1->pNext;
   75599       pVal2 = 0;
   75600     }else{
   75601       *pp = p2;
   75602        pp = &p2->pNext;
   75603       p2 = p2->pNext;
   75604       if( p2==0 ) break;
   75605       pVal2 = p2->pVal;
   75606     }
   75607   }
   75608   *pp = p1 ? p1 : p2;
   75609   *ppOut = pFinal;
   75610 }
   75611 
   75612 /*
   75613 ** Sort the linked list of records headed at pCsr->pRecord. Return SQLITE_OK
   75614 ** if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if an error
   75615 ** occurs.
   75616 */
   75617 static int vdbeSorterSort(const VdbeCursor *pCsr){
   75618   int i;
   75619   SorterRecord **aSlot;
   75620   SorterRecord *p;
   75621   VdbeSorter *pSorter = pCsr->pSorter;
   75622 
   75623   aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
   75624   if( !aSlot ){
   75625     return SQLITE_NOMEM;
   75626   }
   75627 
   75628   p = pSorter->pRecord;
   75629   while( p ){
   75630     SorterRecord *pNext = p->pNext;
   75631     p->pNext = 0;
   75632     for(i=0; aSlot[i]; i++){
   75633       vdbeSorterMerge(pCsr, p, aSlot[i], &p);
   75634       aSlot[i] = 0;
   75635     }
   75636     aSlot[i] = p;
   75637     p = pNext;
   75638   }
   75639 
   75640   p = 0;
   75641   for(i=0; i<64; i++){
   75642     vdbeSorterMerge(pCsr, p, aSlot[i], &p);
   75643   }
   75644   pSorter->pRecord = p;
   75645 
   75646   sqlite3_free(aSlot);
   75647   return SQLITE_OK;
   75648 }
   75649 
   75650 /*
   75651 ** Initialize a file-writer object.
   75652 */
   75653 static void fileWriterInit(
   75654   sqlite3 *db,                    /* Database (for malloc) */
   75655   sqlite3_file *pFile,            /* File to write to */
   75656   FileWriter *p,                  /* Object to populate */
   75657   i64 iStart                      /* Offset of pFile to begin writing at */
   75658 ){
   75659   int nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
   75660 
   75661   memset(p, 0, sizeof(FileWriter));
   75662   p->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);
   75663   if( !p->aBuffer ){
   75664     p->eFWErr = SQLITE_NOMEM;
   75665   }else{
   75666     p->iBufEnd = p->iBufStart = (iStart % nBuf);
   75667     p->iWriteOff = iStart - p->iBufStart;
   75668     p->nBuffer = nBuf;
   75669     p->pFile = pFile;
   75670   }
   75671 }
   75672 
   75673 /*
   75674 ** Write nData bytes of data to the file-write object. Return SQLITE_OK
   75675 ** if successful, or an SQLite error code if an error occurs.
   75676 */
   75677 static void fileWriterWrite(FileWriter *p, u8 *pData, int nData){
   75678   int nRem = nData;
   75679   while( nRem>0 && p->eFWErr==0 ){
   75680     int nCopy = nRem;
   75681     if( nCopy>(p->nBuffer - p->iBufEnd) ){
   75682       nCopy = p->nBuffer - p->iBufEnd;
   75683     }
   75684 
   75685     memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
   75686     p->iBufEnd += nCopy;
   75687     if( p->iBufEnd==p->nBuffer ){
   75688       p->eFWErr = sqlite3OsWrite(p->pFile,
   75689           &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
   75690           p->iWriteOff + p->iBufStart
   75691       );
   75692       p->iBufStart = p->iBufEnd = 0;
   75693       p->iWriteOff += p->nBuffer;
   75694     }
   75695     assert( p->iBufEnd<p->nBuffer );
   75696 
   75697     nRem -= nCopy;
   75698   }
   75699 }
   75700 
   75701 /*
   75702 ** Flush any buffered data to disk and clean up the file-writer object.
   75703 ** The results of using the file-writer after this call are undefined.
   75704 ** Return SQLITE_OK if flushing the buffered data succeeds or is not
   75705 ** required. Otherwise, return an SQLite error code.
   75706 **
   75707 ** Before returning, set *piEof to the offset immediately following the
   75708 ** last byte written to the file.
   75709 */
   75710 static int fileWriterFinish(sqlite3 *db, FileWriter *p, i64 *piEof){
   75711   int rc;
   75712   if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
   75713     p->eFWErr = sqlite3OsWrite(p->pFile,
   75714         &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
   75715         p->iWriteOff + p->iBufStart
   75716     );
   75717   }
   75718   *piEof = (p->iWriteOff + p->iBufEnd);
   75719   sqlite3DbFree(db, p->aBuffer);
   75720   rc = p->eFWErr;
   75721   memset(p, 0, sizeof(FileWriter));
   75722   return rc;
   75723 }
   75724 
   75725 /*
   75726 ** Write value iVal encoded as a varint to the file-write object. Return
   75727 ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
   75728 */
   75729 static void fileWriterWriteVarint(FileWriter *p, u64 iVal){
   75730   int nByte;
   75731   u8 aByte[10];
   75732   nByte = sqlite3PutVarint(aByte, iVal);
   75733   fileWriterWrite(p, aByte, nByte);
   75734 }
   75735 
   75736 /*
   75737 ** Write the current contents of the in-memory linked-list to a PMA. Return
   75738 ** SQLITE_OK if successful, or an SQLite error code otherwise.
   75739 **
   75740 ** The format of a PMA is:
   75741 **
   75742 **     * A varint. This varint contains the total number of bytes of content
   75743 **       in the PMA (not including the varint itself).
   75744 **
   75745 **     * One or more records packed end-to-end in order of ascending keys.
   75746 **       Each record consists of a varint followed by a blob of data (the
   75747 **       key). The varint is the number of bytes in the blob of data.
   75748 */
   75749 static int vdbeSorterListToPMA(sqlite3 *db, const VdbeCursor *pCsr){
   75750   int rc = SQLITE_OK;             /* Return code */
   75751   VdbeSorter *pSorter = pCsr->pSorter;
   75752   FileWriter writer;
   75753 
   75754   memset(&writer, 0, sizeof(FileWriter));
   75755 
   75756   if( pSorter->nInMemory==0 ){
   75757     assert( pSorter->pRecord==0 );
   75758     return rc;
   75759   }
   75760 
   75761   rc = vdbeSorterSort(pCsr);
   75762 
   75763   /* If the first temporary PMA file has not been opened, open it now. */
   75764   if( rc==SQLITE_OK && pSorter->pTemp1==0 ){
   75765     rc = vdbeSorterOpenTempFile(db, &pSorter->pTemp1);
   75766     assert( rc!=SQLITE_OK || pSorter->pTemp1 );
   75767     assert( pSorter->iWriteOff==0 );
   75768     assert( pSorter->nPMA==0 );
   75769   }
   75770 
   75771   if( rc==SQLITE_OK ){
   75772     SorterRecord *p;
   75773     SorterRecord *pNext = 0;
   75774 
   75775     fileWriterInit(db, pSorter->pTemp1, &writer, pSorter->iWriteOff);
   75776     pSorter->nPMA++;
   75777     fileWriterWriteVarint(&writer, pSorter->nInMemory);
   75778     for(p=pSorter->pRecord; p; p=pNext){
   75779       pNext = p->pNext;
   75780       fileWriterWriteVarint(&writer, p->nVal);
   75781       fileWriterWrite(&writer, p->pVal, p->nVal);
   75782       sqlite3DbFree(db, p);
   75783     }
   75784     pSorter->pRecord = p;
   75785     rc = fileWriterFinish(db, &writer, &pSorter->iWriteOff);
   75786   }
   75787 
   75788   return rc;
   75789 }
   75790 
   75791 /*
   75792 ** Add a record to the sorter.
   75793 */
   75794 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
   75795   sqlite3 *db,                    /* Database handle */
   75796   const VdbeCursor *pCsr,               /* Sorter cursor */
   75797   Mem *pVal                       /* Memory cell containing record */
   75798 ){
   75799   VdbeSorter *pSorter = pCsr->pSorter;
   75800   int rc = SQLITE_OK;             /* Return Code */
   75801   SorterRecord *pNew;             /* New list element */
   75802 
   75803   assert( pSorter );
   75804   pSorter->nInMemory += sqlite3VarintLen(pVal->n) + pVal->n;
   75805 
   75806   pNew = (SorterRecord *)sqlite3DbMallocRaw(db, pVal->n + sizeof(SorterRecord));
   75807   if( pNew==0 ){
   75808     rc = SQLITE_NOMEM;
   75809   }else{
   75810     pNew->pVal = (void *)&pNew[1];
   75811     memcpy(pNew->pVal, pVal->z, pVal->n);
   75812     pNew->nVal = pVal->n;
   75813     pNew->pNext = pSorter->pRecord;
   75814     pSorter->pRecord = pNew;
   75815   }
   75816 
   75817   /* See if the contents of the sorter should now be written out. They
   75818   ** are written out when either of the following are true:
   75819   **
   75820   **   * The total memory allocated for the in-memory list is greater
   75821   **     than (page-size * cache-size), or
   75822   **
   75823   **   * The total memory allocated for the in-memory list is greater
   75824   **     than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
   75825   */
   75826   if( rc==SQLITE_OK && pSorter->mxPmaSize>0 && (
   75827         (pSorter->nInMemory>pSorter->mxPmaSize)
   75828      || (pSorter->nInMemory>pSorter->mnPmaSize && sqlite3HeapNearlyFull())
   75829   )){
   75830 #ifdef SQLITE_DEBUG
   75831     i64 nExpect = pSorter->iWriteOff
   75832                 + sqlite3VarintLen(pSorter->nInMemory)
   75833                 + pSorter->nInMemory;
   75834 #endif
   75835     rc = vdbeSorterListToPMA(db, pCsr);
   75836     pSorter->nInMemory = 0;
   75837     assert( rc!=SQLITE_OK || (nExpect==pSorter->iWriteOff) );
   75838   }
   75839 
   75840   return rc;
   75841 }
   75842 
   75843 /*
   75844 ** Helper function for sqlite3VdbeSorterRewind().
   75845 */
   75846 static int vdbeSorterInitMerge(
   75847   sqlite3 *db,                    /* Database handle */
   75848   const VdbeCursor *pCsr,         /* Cursor handle for this sorter */
   75849   i64 *pnByte                     /* Sum of bytes in all opened PMAs */
   75850 ){
   75851   VdbeSorter *pSorter = pCsr->pSorter;
   75852   int rc = SQLITE_OK;             /* Return code */
   75853   int i;                          /* Used to iterator through aIter[] */
   75854   i64 nByte = 0;                  /* Total bytes in all opened PMAs */
   75855 
   75856   /* Initialize the iterators. */
   75857   for(i=0; i<SORTER_MAX_MERGE_COUNT; i++){
   75858     VdbeSorterIter *pIter = &pSorter->aIter[i];
   75859     rc = vdbeSorterIterInit(db, pSorter, pSorter->iReadOff, pIter, &nByte);
   75860     pSorter->iReadOff = pIter->iEof;
   75861     assert( rc!=SQLITE_OK || pSorter->iReadOff<=pSorter->iWriteOff );
   75862     if( rc!=SQLITE_OK || pSorter->iReadOff>=pSorter->iWriteOff ) break;
   75863   }
   75864 
   75865   /* Initialize the aTree[] array. */
   75866   for(i=pSorter->nTree-1; rc==SQLITE_OK && i>0; i--){
   75867     rc = vdbeSorterDoCompare(pCsr, i);
   75868   }
   75869 
   75870   *pnByte = nByte;
   75871   return rc;
   75872 }
   75873 
   75874 /*
   75875 ** Once the sorter has been populated, this function is called to prepare
   75876 ** for iterating through its contents in sorted order.
   75877 */
   75878 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
   75879   VdbeSorter *pSorter = pCsr->pSorter;
   75880   int rc;                         /* Return code */
   75881   sqlite3_file *pTemp2 = 0;       /* Second temp file to use */
   75882   i64 iWrite2 = 0;                /* Write offset for pTemp2 */
   75883   int nIter;                      /* Number of iterators used */
   75884   int nByte;                      /* Bytes of space required for aIter/aTree */
   75885   int N = 2;                      /* Power of 2 >= nIter */
   75886 
   75887   assert( pSorter );
   75888 
   75889   /* If no data has been written to disk, then do not do so now. Instead,
   75890   ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
   75891   ** from the in-memory list.  */
   75892   if( pSorter->nPMA==0 ){
   75893     *pbEof = !pSorter->pRecord;
   75894     assert( pSorter->aTree==0 );
   75895     return vdbeSorterSort(pCsr);
   75896   }
   75897 
   75898   /* Write the current in-memory list to a PMA. */
   75899   rc = vdbeSorterListToPMA(db, pCsr);
   75900   if( rc!=SQLITE_OK ) return rc;
   75901 
   75902   /* Allocate space for aIter[] and aTree[]. */
   75903   nIter = pSorter->nPMA;
   75904   if( nIter>SORTER_MAX_MERGE_COUNT ) nIter = SORTER_MAX_MERGE_COUNT;
   75905   assert( nIter>0 );
   75906   while( N<nIter ) N += N;
   75907   nByte = N * (sizeof(int) + sizeof(VdbeSorterIter));
   75908   pSorter->aIter = (VdbeSorterIter *)sqlite3DbMallocZero(db, nByte);
   75909   if( !pSorter->aIter ) return SQLITE_NOMEM;
   75910   pSorter->aTree = (int *)&pSorter->aIter[N];
   75911   pSorter->nTree = N;
   75912 
   75913   do {
   75914     int iNew;                     /* Index of new, merged, PMA */
   75915 
   75916     for(iNew=0;
   75917         rc==SQLITE_OK && iNew*SORTER_MAX_MERGE_COUNT<pSorter->nPMA;
   75918         iNew++
   75919     ){
   75920       int rc2;                    /* Return code from fileWriterFinish() */
   75921       FileWriter writer;          /* Object used to write to disk */
   75922       i64 nWrite;                 /* Number of bytes in new PMA */
   75923 
   75924       memset(&writer, 0, sizeof(FileWriter));
   75925 
   75926       /* If there are SORTER_MAX_MERGE_COUNT or less PMAs in file pTemp1,
   75927       ** initialize an iterator for each of them and break out of the loop.
   75928       ** These iterators will be incrementally merged as the VDBE layer calls
   75929       ** sqlite3VdbeSorterNext().
   75930       **
   75931       ** Otherwise, if pTemp1 contains more than SORTER_MAX_MERGE_COUNT PMAs,
   75932       ** initialize interators for SORTER_MAX_MERGE_COUNT of them. These PMAs
   75933       ** are merged into a single PMA that is written to file pTemp2.
   75934       */
   75935       rc = vdbeSorterInitMerge(db, pCsr, &nWrite);
   75936       assert( rc!=SQLITE_OK || pSorter->aIter[ pSorter->aTree[1] ].pFile );
   75937       if( rc!=SQLITE_OK || pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
   75938         break;
   75939       }
   75940 
   75941       /* Open the second temp file, if it is not already open. */
   75942       if( pTemp2==0 ){
   75943         assert( iWrite2==0 );
   75944         rc = vdbeSorterOpenTempFile(db, &pTemp2);
   75945       }
   75946 
   75947       if( rc==SQLITE_OK ){
   75948         int bEof = 0;
   75949         fileWriterInit(db, pTemp2, &writer, iWrite2);
   75950         fileWriterWriteVarint(&writer, nWrite);
   75951         while( rc==SQLITE_OK && bEof==0 ){
   75952           VdbeSorterIter *pIter = &pSorter->aIter[ pSorter->aTree[1] ];
   75953           assert( pIter->pFile );
   75954 
   75955           fileWriterWriteVarint(&writer, pIter->nKey);
   75956           fileWriterWrite(&writer, pIter->aKey, pIter->nKey);
   75957           rc = sqlite3VdbeSorterNext(db, pCsr, &bEof);
   75958         }
   75959         rc2 = fileWriterFinish(db, &writer, &iWrite2);
   75960         if( rc==SQLITE_OK ) rc = rc2;
   75961       }
   75962     }
   75963 
   75964     if( pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
   75965       break;
   75966     }else{
   75967       sqlite3_file *pTmp = pSorter->pTemp1;
   75968       pSorter->nPMA = iNew;
   75969       pSorter->pTemp1 = pTemp2;
   75970       pTemp2 = pTmp;
   75971       pSorter->iWriteOff = iWrite2;
   75972       pSorter->iReadOff = 0;
   75973       iWrite2 = 0;
   75974     }
   75975   }while( rc==SQLITE_OK );
   75976 
   75977   if( pTemp2 ){
   75978     sqlite3OsCloseFree(pTemp2);
   75979   }
   75980   *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
   75981   return rc;
   75982 }
   75983 
   75984 /*
   75985 ** Advance to the next element in the sorter.
   75986 */
   75987 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
   75988   VdbeSorter *pSorter = pCsr->pSorter;
   75989   int rc;                         /* Return code */
   75990 
   75991   if( pSorter->aTree ){
   75992     int iPrev = pSorter->aTree[1];/* Index of iterator to advance */
   75993     rc = vdbeSorterIterNext(db, &pSorter->aIter[iPrev]);
   75994     if( rc==SQLITE_OK ){
   75995       int i;                      /* Index of aTree[] to recalculate */
   75996       VdbeSorterIter *pIter1;     /* First iterator to compare */
   75997       VdbeSorterIter *pIter2;     /* Second iterator to compare */
   75998       u8 *pKey2;                  /* To pIter2->aKey, or 0 if record cached */
   75999 
   76000       /* Find the first two iterators to compare. The one that was just
   76001       ** advanced (iPrev) and the one next to it in the array.  */
   76002       pIter1 = &pSorter->aIter[(iPrev & 0xFFFE)];
   76003       pIter2 = &pSorter->aIter[(iPrev | 0x0001)];
   76004       pKey2 = pIter2->aKey;
   76005 
   76006       for(i=(pSorter->nTree+iPrev)/2; i>0; i=i/2){
   76007         /* Compare pIter1 and pIter2. Store the result in variable iRes. */
   76008         int iRes;
   76009         if( pIter1->pFile==0 ){
   76010           iRes = +1;
   76011         }else if( pIter2->pFile==0 ){
   76012           iRes = -1;
   76013         }else{
   76014           vdbeSorterCompare(pCsr, 0,
   76015               pIter1->aKey, pIter1->nKey, pKey2, pIter2->nKey, &iRes
   76016           );
   76017         }
   76018 
   76019         /* If pIter1 contained the smaller value, set aTree[i] to its index.
   76020         ** Then set pIter2 to the next iterator to compare to pIter1. In this
   76021         ** case there is no cache of pIter2 in pSorter->pUnpacked, so set
   76022         ** pKey2 to point to the record belonging to pIter2.
   76023         **
   76024         ** Alternatively, if pIter2 contains the smaller of the two values,
   76025         ** set aTree[i] to its index and update pIter1. If vdbeSorterCompare()
   76026         ** was actually called above, then pSorter->pUnpacked now contains
   76027         ** a value equivalent to pIter2. So set pKey2 to NULL to prevent
   76028         ** vdbeSorterCompare() from decoding pIter2 again.  */
   76029         if( iRes<=0 ){
   76030           pSorter->aTree[i] = (int)(pIter1 - pSorter->aIter);
   76031           pIter2 = &pSorter->aIter[ pSorter->aTree[i ^ 0x0001] ];
   76032           pKey2 = pIter2->aKey;
   76033         }else{
   76034           if( pIter1->pFile ) pKey2 = 0;
   76035           pSorter->aTree[i] = (int)(pIter2 - pSorter->aIter);
   76036           pIter1 = &pSorter->aIter[ pSorter->aTree[i ^ 0x0001] ];
   76037         }
   76038 
   76039       }
   76040       *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
   76041     }
   76042   }else{
   76043     SorterRecord *pFree = pSorter->pRecord;
   76044     pSorter->pRecord = pFree->pNext;
   76045     pFree->pNext = 0;
   76046     vdbeSorterRecordFree(db, pFree);
   76047     *pbEof = !pSorter->pRecord;
   76048     rc = SQLITE_OK;
   76049   }
   76050   return rc;
   76051 }
   76052 
   76053 /*
   76054 ** Return a pointer to a buffer owned by the sorter that contains the
   76055 ** current key.
   76056 */
   76057 static void *vdbeSorterRowkey(
   76058   const VdbeSorter *pSorter,      /* Sorter object */
   76059   int *pnKey                      /* OUT: Size of current key in bytes */
   76060 ){
   76061   void *pKey;
   76062   if( pSorter->aTree ){
   76063     VdbeSorterIter *pIter;
   76064     pIter = &pSorter->aIter[ pSorter->aTree[1] ];
   76065     *pnKey = pIter->nKey;
   76066     pKey = pIter->aKey;
   76067   }else{
   76068     *pnKey = pSorter->pRecord->nVal;
   76069     pKey = pSorter->pRecord->pVal;
   76070   }
   76071   return pKey;
   76072 }
   76073 
   76074 /*
   76075 ** Copy the current sorter key into the memory cell pOut.
   76076 */
   76077 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
   76078   VdbeSorter *pSorter = pCsr->pSorter;
   76079   void *pKey; int nKey;           /* Sorter key to copy into pOut */
   76080 
   76081   pKey = vdbeSorterRowkey(pSorter, &nKey);
   76082   if( sqlite3VdbeMemGrow(pOut, nKey, 0) ){
   76083     return SQLITE_NOMEM;
   76084   }
   76085   pOut->n = nKey;
   76086   MemSetTypeFlag(pOut, MEM_Blob);
   76087   memcpy(pOut->z, pKey, nKey);
   76088 
   76089   return SQLITE_OK;
   76090 }
   76091 
   76092 /*
   76093 ** Compare the key in memory cell pVal with the key that the sorter cursor
   76094 ** passed as the first argument currently points to. For the purposes of
   76095 ** the comparison, ignore the rowid field at the end of each record.
   76096 **
   76097 ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
   76098 ** Otherwise, set *pRes to a negative, zero or positive value if the
   76099 ** key in pVal is smaller than, equal to or larger than the current sorter
   76100 ** key.
   76101 */
   76102 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
   76103   const VdbeCursor *pCsr,         /* Sorter cursor */
   76104   Mem *pVal,                      /* Value to compare to current sorter key */
   76105   int nKeyCol,                    /* Only compare this many fields */
   76106   int *pRes                       /* OUT: Result of comparison */
   76107 ){
   76108   VdbeSorter *pSorter = pCsr->pSorter;
   76109   void *pKey; int nKey;           /* Sorter key to compare pVal with */
   76110 
   76111   pKey = vdbeSorterRowkey(pSorter, &nKey);
   76112   vdbeSorterCompare(pCsr, nKeyCol, pVal->z, pVal->n, pKey, nKey, pRes);
   76113   return SQLITE_OK;
   76114 }
   76115 
   76116 /************** End of vdbesort.c ********************************************/
   76117 /************** Begin file journal.c *****************************************/
   76118 /*
   76119 ** 2007 August 22
   76120 **
   76121 ** The author disclaims copyright to this source code.  In place of
   76122 ** a legal notice, here is a blessing:
   76123 **
   76124 **    May you do good and not evil.
   76125 **    May you find forgiveness for yourself and forgive others.
   76126 **    May you share freely, never taking more than you give.
   76127 **
   76128 *************************************************************************
   76129 **
   76130 ** This file implements a special kind of sqlite3_file object used
   76131 ** by SQLite to create journal files if the atomic-write optimization
   76132 ** is enabled.
   76133 **
   76134 ** The distinctive characteristic of this sqlite3_file is that the
   76135 ** actual on disk file is created lazily. When the file is created,
   76136 ** the caller specifies a buffer size for an in-memory buffer to
   76137 ** be used to service read() and write() requests. The actual file
   76138 ** on disk is not created or populated until either:
   76139 **
   76140 **   1) The in-memory representation grows too large for the allocated
   76141 **      buffer, or
   76142 **   2) The sqlite3JournalCreate() function is called.
   76143 */
   76144 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
   76145 
   76146 
   76147 /*
   76148 ** A JournalFile object is a subclass of sqlite3_file used by
   76149 ** as an open file handle for journal files.
   76150 */
   76151 struct JournalFile {
   76152   sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
   76153   int nBuf;                       /* Size of zBuf[] in bytes */
   76154   char *zBuf;                     /* Space to buffer journal writes */
   76155   int iSize;                      /* Amount of zBuf[] currently used */
   76156   int flags;                      /* xOpen flags */
   76157   sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
   76158   sqlite3_file *pReal;            /* The "real" underlying file descriptor */
   76159   const char *zJournal;           /* Name of the journal file */
   76160 };
   76161 typedef struct JournalFile JournalFile;
   76162 
   76163 /*
   76164 ** If it does not already exists, create and populate the on-disk file
   76165 ** for JournalFile p.
   76166 */
   76167 static int createFile(JournalFile *p){
   76168   int rc = SQLITE_OK;
   76169   if( !p->pReal ){
   76170     sqlite3_file *pReal = (sqlite3_file *)&p[1];
   76171     rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
   76172     if( rc==SQLITE_OK ){
   76173       p->pReal = pReal;
   76174       if( p->iSize>0 ){
   76175         assert(p->iSize<=p->nBuf);
   76176         rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
   76177       }
   76178       if( rc!=SQLITE_OK ){
   76179         /* If an error occurred while writing to the file, close it before
   76180         ** returning. This way, SQLite uses the in-memory journal data to
   76181         ** roll back changes made to the internal page-cache before this
   76182         ** function was called.  */
   76183         sqlite3OsClose(pReal);
   76184         p->pReal = 0;
   76185       }
   76186     }
   76187   }
   76188   return rc;
   76189 }
   76190 
   76191 /*
   76192 ** Close the file.
   76193 */
   76194 static int jrnlClose(sqlite3_file *pJfd){
   76195   JournalFile *p = (JournalFile *)pJfd;
   76196   if( p->pReal ){
   76197     sqlite3OsClose(p->pReal);
   76198   }
   76199   sqlite3_free(p->zBuf);
   76200   return SQLITE_OK;
   76201 }
   76202 
   76203 /*
   76204 ** Read data from the file.
   76205 */
   76206 static int jrnlRead(
   76207   sqlite3_file *pJfd,    /* The journal file from which to read */
   76208   void *zBuf,            /* Put the results here */
   76209   int iAmt,              /* Number of bytes to read */
   76210   sqlite_int64 iOfst     /* Begin reading at this offset */
   76211 ){
   76212   int rc = SQLITE_OK;
   76213   JournalFile *p = (JournalFile *)pJfd;
   76214   if( p->pReal ){
   76215     rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
   76216   }else if( (iAmt+iOfst)>p->iSize ){
   76217     rc = SQLITE_IOERR_SHORT_READ;
   76218   }else{
   76219     memcpy(zBuf, &p->zBuf[iOfst], iAmt);
   76220   }
   76221   return rc;
   76222 }
   76223 
   76224 /*
   76225 ** Write data to the file.
   76226 */
   76227 static int jrnlWrite(
   76228   sqlite3_file *pJfd,    /* The journal file into which to write */
   76229   const void *zBuf,      /* Take data to be written from here */
   76230   int iAmt,              /* Number of bytes to write */
   76231   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
   76232 ){
   76233   int rc = SQLITE_OK;
   76234   JournalFile *p = (JournalFile *)pJfd;
   76235   if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
   76236     rc = createFile(p);
   76237   }
   76238   if( rc==SQLITE_OK ){
   76239     if( p->pReal ){
   76240       rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
   76241     }else{
   76242       memcpy(&p->zBuf[iOfst], zBuf, iAmt);
   76243       if( p->iSize<(iOfst+iAmt) ){
   76244         p->iSize = (iOfst+iAmt);
   76245       }
   76246     }
   76247   }
   76248   return rc;
   76249 }
   76250 
   76251 /*
   76252 ** Truncate the file.
   76253 */
   76254 static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
   76255   int rc = SQLITE_OK;
   76256   JournalFile *p = (JournalFile *)pJfd;
   76257   if( p->pReal ){
   76258     rc = sqlite3OsTruncate(p->pReal, size);
   76259   }else if( size<p->iSize ){
   76260     p->iSize = size;
   76261   }
   76262   return rc;
   76263 }
   76264 
   76265 /*
   76266 ** Sync the file.
   76267 */
   76268 static int jrnlSync(sqlite3_file *pJfd, int flags){
   76269   int rc;
   76270   JournalFile *p = (JournalFile *)pJfd;
   76271   if( p->pReal ){
   76272     rc = sqlite3OsSync(p->pReal, flags);
   76273   }else{
   76274     rc = SQLITE_OK;
   76275   }
   76276   return rc;
   76277 }
   76278 
   76279 /*
   76280 ** Query the size of the file in bytes.
   76281 */
   76282 static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
   76283   int rc = SQLITE_OK;
   76284   JournalFile *p = (JournalFile *)pJfd;
   76285   if( p->pReal ){
   76286     rc = sqlite3OsFileSize(p->pReal, pSize);
   76287   }else{
   76288     *pSize = (sqlite_int64) p->iSize;
   76289   }
   76290   return rc;
   76291 }
   76292 
   76293 /*
   76294 ** Table of methods for JournalFile sqlite3_file object.
   76295 */
   76296 static struct sqlite3_io_methods JournalFileMethods = {
   76297   1,             /* iVersion */
   76298   jrnlClose,     /* xClose */
   76299   jrnlRead,      /* xRead */
   76300   jrnlWrite,     /* xWrite */
   76301   jrnlTruncate,  /* xTruncate */
   76302   jrnlSync,      /* xSync */
   76303   jrnlFileSize,  /* xFileSize */
   76304   0,             /* xLock */
   76305   0,             /* xUnlock */
   76306   0,             /* xCheckReservedLock */
   76307   0,             /* xFileControl */
   76308   0,             /* xSectorSize */
   76309   0,             /* xDeviceCharacteristics */
   76310   0,             /* xShmMap */
   76311   0,             /* xShmLock */
   76312   0,             /* xShmBarrier */
   76313   0              /* xShmUnmap */
   76314 };
   76315 
   76316 /*
   76317 ** Open a journal file.
   76318 */
   76319 SQLITE_PRIVATE int sqlite3JournalOpen(
   76320   sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
   76321   const char *zName,         /* Name of the journal file */
   76322   sqlite3_file *pJfd,        /* Preallocated, blank file handle */
   76323   int flags,                 /* Opening flags */
   76324   int nBuf                   /* Bytes buffered before opening the file */
   76325 ){
   76326   JournalFile *p = (JournalFile *)pJfd;
   76327   memset(p, 0, sqlite3JournalSize(pVfs));
   76328   if( nBuf>0 ){
   76329     p->zBuf = sqlite3MallocZero(nBuf);
   76330     if( !p->zBuf ){
   76331       return SQLITE_NOMEM;
   76332     }
   76333   }else{
   76334     return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
   76335   }
   76336   p->pMethod = &JournalFileMethods;
   76337   p->nBuf = nBuf;
   76338   p->flags = flags;
   76339   p->zJournal = zName;
   76340   p->pVfs = pVfs;
   76341   return SQLITE_OK;
   76342 }
   76343 
   76344 /*
   76345 ** If the argument p points to a JournalFile structure, and the underlying
   76346 ** file has not yet been created, create it now.
   76347 */
   76348 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
   76349   if( p->pMethods!=&JournalFileMethods ){
   76350     return SQLITE_OK;
   76351   }
   76352   return createFile((JournalFile *)p);
   76353 }
   76354 
   76355 /*
   76356 ** The file-handle passed as the only argument is guaranteed to be an open
   76357 ** file. It may or may not be of class JournalFile. If the file is a
   76358 ** JournalFile, and the underlying file on disk has not yet been opened,
   76359 ** return 0. Otherwise, return 1.
   76360 */
   76361 SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p){
   76362   return (p->pMethods!=&JournalFileMethods || ((JournalFile *)p)->pReal!=0);
   76363 }
   76364 
   76365 /*
   76366 ** Return the number of bytes required to store a JournalFile that uses vfs
   76367 ** pVfs to create the underlying on-disk files.
   76368 */
   76369 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
   76370   return (pVfs->szOsFile+sizeof(JournalFile));
   76371 }
   76372 #endif
   76373 
   76374 /************** End of journal.c *********************************************/
   76375 /************** Begin file memjournal.c **************************************/
   76376 /*
   76377 ** 2008 October 7
   76378 **
   76379 ** The author disclaims copyright to this source code.  In place of
   76380 ** a legal notice, here is a blessing:
   76381 **
   76382 **    May you do good and not evil.
   76383 **    May you find forgiveness for yourself and forgive others.
   76384 **    May you share freely, never taking more than you give.
   76385 **
   76386 *************************************************************************
   76387 **
   76388 ** This file contains code use to implement an in-memory rollback journal.
   76389 ** The in-memory rollback journal is used to journal transactions for
   76390 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
   76391 */
   76392 
   76393 /* Forward references to internal structures */
   76394 typedef struct MemJournal MemJournal;
   76395 typedef struct FilePoint FilePoint;
   76396 typedef struct FileChunk FileChunk;
   76397 
   76398 /* Space to hold the rollback journal is allocated in increments of
   76399 ** this many bytes.
   76400 **
   76401 ** The size chosen is a little less than a power of two.  That way,
   76402 ** the FileChunk object will have a size that almost exactly fills
   76403 ** a power-of-two allocation.  This mimimizes wasted space in power-of-two
   76404 ** memory allocators.
   76405 */
   76406 #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
   76407 
   76408 /*
   76409 ** The rollback journal is composed of a linked list of these structures.
   76410 */
   76411 struct FileChunk {
   76412   FileChunk *pNext;               /* Next chunk in the journal */
   76413   u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
   76414 };
   76415 
   76416 /*
   76417 ** An instance of this object serves as a cursor into the rollback journal.
   76418 ** The cursor can be either for reading or writing.
   76419 */
   76420 struct FilePoint {
   76421   sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
   76422   FileChunk *pChunk;              /* Specific chunk into which cursor points */
   76423 };
   76424 
   76425 /*
   76426 ** This subclass is a subclass of sqlite3_file.  Each open memory-journal
   76427 ** is an instance of this class.
   76428 */
   76429 struct MemJournal {
   76430   sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
   76431   FileChunk *pFirst;              /* Head of in-memory chunk-list */
   76432   FilePoint endpoint;             /* Pointer to the end of the file */
   76433   FilePoint readpoint;            /* Pointer to the end of the last xRead() */
   76434 };
   76435 
   76436 /*
   76437 ** Read data from the in-memory journal file.  This is the implementation
   76438 ** of the sqlite3_vfs.xRead method.
   76439 */
   76440 static int memjrnlRead(
   76441   sqlite3_file *pJfd,    /* The journal file from which to read */
   76442   void *zBuf,            /* Put the results here */
   76443   int iAmt,              /* Number of bytes to read */
   76444   sqlite_int64 iOfst     /* Begin reading at this offset */
   76445 ){
   76446   MemJournal *p = (MemJournal *)pJfd;
   76447   u8 *zOut = zBuf;
   76448   int nRead = iAmt;
   76449   int iChunkOffset;
   76450   FileChunk *pChunk;
   76451 
   76452   /* SQLite never tries to read past the end of a rollback journal file */
   76453   assert( iOfst+iAmt<=p->endpoint.iOffset );
   76454 
   76455   if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
   76456     sqlite3_int64 iOff = 0;
   76457     for(pChunk=p->pFirst;
   76458         ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
   76459         pChunk=pChunk->pNext
   76460     ){
   76461       iOff += JOURNAL_CHUNKSIZE;
   76462     }
   76463   }else{
   76464     pChunk = p->readpoint.pChunk;
   76465   }
   76466 
   76467   iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
   76468   do {
   76469     int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
   76470     int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
   76471     memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
   76472     zOut += nCopy;
   76473     nRead -= iSpace;
   76474     iChunkOffset = 0;
   76475   } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
   76476   p->readpoint.iOffset = iOfst+iAmt;
   76477   p->readpoint.pChunk = pChunk;
   76478 
   76479   return SQLITE_OK;
   76480 }
   76481 
   76482 /*
   76483 ** Write data to the file.
   76484 */
   76485 static int memjrnlWrite(
   76486   sqlite3_file *pJfd,    /* The journal file into which to write */
   76487   const void *zBuf,      /* Take data to be written from here */
   76488   int iAmt,              /* Number of bytes to write */
   76489   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
   76490 ){
   76491   MemJournal *p = (MemJournal *)pJfd;
   76492   int nWrite = iAmt;
   76493   u8 *zWrite = (u8 *)zBuf;
   76494 
   76495   /* An in-memory journal file should only ever be appended to. Random
   76496   ** access writes are not required by sqlite.
   76497   */
   76498   assert( iOfst==p->endpoint.iOffset );
   76499   UNUSED_PARAMETER(iOfst);
   76500 
   76501   while( nWrite>0 ){
   76502     FileChunk *pChunk = p->endpoint.pChunk;
   76503     int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
   76504     int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
   76505 
   76506     if( iChunkOffset==0 ){
   76507       /* New chunk is required to extend the file. */
   76508       FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
   76509       if( !pNew ){
   76510         return SQLITE_IOERR_NOMEM;
   76511       }
   76512       pNew->pNext = 0;
   76513       if( pChunk ){
   76514         assert( p->pFirst );
   76515         pChunk->pNext = pNew;
   76516       }else{
   76517         assert( !p->pFirst );
   76518         p->pFirst = pNew;
   76519       }
   76520       p->endpoint.pChunk = pNew;
   76521     }
   76522 
   76523     memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
   76524     zWrite += iSpace;
   76525     nWrite -= iSpace;
   76526     p->endpoint.iOffset += iSpace;
   76527   }
   76528 
   76529   return SQLITE_OK;
   76530 }
   76531 
   76532 /*
   76533 ** Truncate the file.
   76534 */
   76535 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
   76536   MemJournal *p = (MemJournal *)pJfd;
   76537   FileChunk *pChunk;
   76538   assert(size==0);
   76539   UNUSED_PARAMETER(size);
   76540   pChunk = p->pFirst;
   76541   while( pChunk ){
   76542     FileChunk *pTmp = pChunk;
   76543     pChunk = pChunk->pNext;
   76544     sqlite3_free(pTmp);
   76545   }
   76546   sqlite3MemJournalOpen(pJfd);
   76547   return SQLITE_OK;
   76548 }
   76549 
   76550 /*
   76551 ** Close the file.
   76552 */
   76553 static int memjrnlClose(sqlite3_file *pJfd){
   76554   memjrnlTruncate(pJfd, 0);
   76555   return SQLITE_OK;
   76556 }
   76557 
   76558 
   76559 /*
   76560 ** Sync the file.
   76561 **
   76562 ** Syncing an in-memory journal is a no-op.  And, in fact, this routine
   76563 ** is never called in a working implementation.  This implementation
   76564 ** exists purely as a contingency, in case some malfunction in some other
   76565 ** part of SQLite causes Sync to be called by mistake.
   76566 */
   76567 static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
   76568   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   76569   return SQLITE_OK;
   76570 }
   76571 
   76572 /*
   76573 ** Query the size of the file in bytes.
   76574 */
   76575 static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
   76576   MemJournal *p = (MemJournal *)pJfd;
   76577   *pSize = (sqlite_int64) p->endpoint.iOffset;
   76578   return SQLITE_OK;
   76579 }
   76580 
   76581 /*
   76582 ** Table of methods for MemJournal sqlite3_file object.
   76583 */
   76584 static const struct sqlite3_io_methods MemJournalMethods = {
   76585   1,                /* iVersion */
   76586   memjrnlClose,     /* xClose */
   76587   memjrnlRead,      /* xRead */
   76588   memjrnlWrite,     /* xWrite */
   76589   memjrnlTruncate,  /* xTruncate */
   76590   memjrnlSync,      /* xSync */
   76591   memjrnlFileSize,  /* xFileSize */
   76592   0,                /* xLock */
   76593   0,                /* xUnlock */
   76594   0,                /* xCheckReservedLock */
   76595   0,                /* xFileControl */
   76596   0,                /* xSectorSize */
   76597   0,                /* xDeviceCharacteristics */
   76598   0,                /* xShmMap */
   76599   0,                /* xShmLock */
   76600   0,                /* xShmBarrier */
   76601   0,                /* xShmUnmap */
   76602   0,                /* xFetch */
   76603   0                 /* xUnfetch */
   76604 };
   76605 
   76606 /*
   76607 ** Open a journal file.
   76608 */
   76609 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
   76610   MemJournal *p = (MemJournal *)pJfd;
   76611   assert( EIGHT_BYTE_ALIGNMENT(p) );
   76612   memset(p, 0, sqlite3MemJournalSize());
   76613   p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
   76614 }
   76615 
   76616 /*
   76617 ** Return true if the file-handle passed as an argument is
   76618 ** an in-memory journal
   76619 */
   76620 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
   76621   return pJfd->pMethods==&MemJournalMethods;
   76622 }
   76623 
   76624 /*
   76625 ** Return the number of bytes required to store a MemJournal file descriptor.
   76626 */
   76627 SQLITE_PRIVATE int sqlite3MemJournalSize(void){
   76628   return sizeof(MemJournal);
   76629 }
   76630 
   76631 /************** End of memjournal.c ******************************************/
   76632 /************** Begin file walker.c ******************************************/
   76633 /*
   76634 ** 2008 August 16
   76635 **
   76636 ** The author disclaims copyright to this source code.  In place of
   76637 ** a legal notice, here is a blessing:
   76638 **
   76639 **    May you do good and not evil.
   76640 **    May you find forgiveness for yourself and forgive others.
   76641 **    May you share freely, never taking more than you give.
   76642 **
   76643 *************************************************************************
   76644 ** This file contains routines used for walking the parser tree for
   76645 ** an SQL statement.
   76646 */
   76647 /* #include <stdlib.h> */
   76648 /* #include <string.h> */
   76649 
   76650 
   76651 /*
   76652 ** Walk an expression tree.  Invoke the callback once for each node
   76653 ** of the expression, while decending.  (In other words, the callback
   76654 ** is invoked before visiting children.)
   76655 **
   76656 ** The return value from the callback should be one of the WRC_*
   76657 ** constants to specify how to proceed with the walk.
   76658 **
   76659 **    WRC_Continue      Continue descending down the tree.
   76660 **
   76661 **    WRC_Prune         Do not descend into child nodes.  But allow
   76662 **                      the walk to continue with sibling nodes.
   76663 **
   76664 **    WRC_Abort         Do no more callbacks.  Unwind the stack and
   76665 **                      return the top-level walk call.
   76666 **
   76667 ** The return value from this routine is WRC_Abort to abandon the tree walk
   76668 ** and WRC_Continue to continue.
   76669 */
   76670 SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
   76671   int rc;
   76672   if( pExpr==0 ) return WRC_Continue;
   76673   testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
   76674   testcase( ExprHasProperty(pExpr, EP_Reduced) );
   76675   rc = pWalker->xExprCallback(pWalker, pExpr);
   76676   if( rc==WRC_Continue
   76677               && !ExprHasProperty(pExpr,EP_TokenOnly) ){
   76678     if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
   76679     if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
   76680     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   76681       if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
   76682     }else{
   76683       if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
   76684     }
   76685   }
   76686   return rc & WRC_Abort;
   76687 }
   76688 
   76689 /*
   76690 ** Call sqlite3WalkExpr() for every expression in list p or until
   76691 ** an abort request is seen.
   76692 */
   76693 SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
   76694   int i;
   76695   struct ExprList_item *pItem;
   76696   if( p ){
   76697     for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
   76698       if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
   76699     }
   76700   }
   76701   return WRC_Continue;
   76702 }
   76703 
   76704 /*
   76705 ** Walk all expressions associated with SELECT statement p.  Do
   76706 ** not invoke the SELECT callback on p, but do (of course) invoke
   76707 ** any expr callbacks and SELECT callbacks that come from subqueries.
   76708 ** Return WRC_Abort or WRC_Continue.
   76709 */
   76710 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
   76711   if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
   76712   if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
   76713   if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
   76714   if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
   76715   if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
   76716   if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
   76717   if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
   76718   return WRC_Continue;
   76719 }
   76720 
   76721 /*
   76722 ** Walk the parse trees associated with all subqueries in the
   76723 ** FROM clause of SELECT statement p.  Do not invoke the select
   76724 ** callback on p, but do invoke it on each FROM clause subquery
   76725 ** and on any subqueries further down in the tree.  Return
   76726 ** WRC_Abort or WRC_Continue;
   76727 */
   76728 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
   76729   SrcList *pSrc;
   76730   int i;
   76731   struct SrcList_item *pItem;
   76732 
   76733   pSrc = p->pSrc;
   76734   if( ALWAYS(pSrc) ){
   76735     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
   76736       if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
   76737         return WRC_Abort;
   76738       }
   76739     }
   76740   }
   76741   return WRC_Continue;
   76742 }
   76743 
   76744 /*
   76745 ** Call sqlite3WalkExpr() for every expression in Select statement p.
   76746 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
   76747 ** on the compound select chain, p->pPrior.
   76748 **
   76749 ** If it is not NULL, the xSelectCallback() callback is invoked before
   76750 ** the walk of the expressions and FROM clause. The xSelectCallback2()
   76751 ** method, if it is not NULL, is invoked following the walk of the
   76752 ** expressions and FROM clause.
   76753 **
   76754 ** Return WRC_Continue under normal conditions.  Return WRC_Abort if
   76755 ** there is an abort request.
   76756 **
   76757 ** If the Walker does not have an xSelectCallback() then this routine
   76758 ** is a no-op returning WRC_Continue.
   76759 */
   76760 SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
   76761   int rc;
   76762   if( p==0 || (pWalker->xSelectCallback==0 && pWalker->xSelectCallback2==0) ){
   76763     return WRC_Continue;
   76764   }
   76765   rc = WRC_Continue;
   76766   pWalker->walkerDepth++;
   76767   while( p ){
   76768     if( pWalker->xSelectCallback ){
   76769        rc = pWalker->xSelectCallback(pWalker, p);
   76770        if( rc ) break;
   76771     }
   76772     if( sqlite3WalkSelectExpr(pWalker, p)
   76773      || sqlite3WalkSelectFrom(pWalker, p)
   76774     ){
   76775       pWalker->walkerDepth--;
   76776       return WRC_Abort;
   76777     }
   76778     if( pWalker->xSelectCallback2 ){
   76779       pWalker->xSelectCallback2(pWalker, p);
   76780     }
   76781     p = p->pPrior;
   76782   }
   76783   pWalker->walkerDepth--;
   76784   return rc & WRC_Abort;
   76785 }
   76786 
   76787 /************** End of walker.c **********************************************/
   76788 /************** Begin file resolve.c *****************************************/
   76789 /*
   76790 ** 2008 August 18
   76791 **
   76792 ** The author disclaims copyright to this source code.  In place of
   76793 ** a legal notice, here is a blessing:
   76794 **
   76795 **    May you do good and not evil.
   76796 **    May you find forgiveness for yourself and forgive others.
   76797 **    May you share freely, never taking more than you give.
   76798 **
   76799 *************************************************************************
   76800 **
   76801 ** This file contains routines used for walking the parser tree and
   76802 ** resolve all identifiers by associating them with a particular
   76803 ** table and column.
   76804 */
   76805 /* #include <stdlib.h> */
   76806 /* #include <string.h> */
   76807 
   76808 /*
   76809 ** Walk the expression tree pExpr and increase the aggregate function
   76810 ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
   76811 ** This needs to occur when copying a TK_AGG_FUNCTION node from an
   76812 ** outer query into an inner subquery.
   76813 **
   76814 ** incrAggFunctionDepth(pExpr,n) is the main routine.  incrAggDepth(..)
   76815 ** is a helper function - a callback for the tree walker.
   76816 */
   76817 static int incrAggDepth(Walker *pWalker, Expr *pExpr){
   76818   if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.i;
   76819   return WRC_Continue;
   76820 }
   76821 static void incrAggFunctionDepth(Expr *pExpr, int N){
   76822   if( N>0 ){
   76823     Walker w;
   76824     memset(&w, 0, sizeof(w));
   76825     w.xExprCallback = incrAggDepth;
   76826     w.u.i = N;
   76827     sqlite3WalkExpr(&w, pExpr);
   76828   }
   76829 }
   76830 
   76831 /*
   76832 ** Turn the pExpr expression into an alias for the iCol-th column of the
   76833 ** result set in pEList.
   76834 **
   76835 ** If the result set column is a simple column reference, then this routine
   76836 ** makes an exact copy.  But for any other kind of expression, this
   76837 ** routine make a copy of the result set column as the argument to the
   76838 ** TK_AS operator.  The TK_AS operator causes the expression to be
   76839 ** evaluated just once and then reused for each alias.
   76840 **
   76841 ** The reason for suppressing the TK_AS term when the expression is a simple
   76842 ** column reference is so that the column reference will be recognized as
   76843 ** usable by indices within the WHERE clause processing logic.
   76844 **
   76845 ** The TK_AS operator is inhibited if zType[0]=='G'.  This means
   76846 ** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
   76847 **
   76848 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
   76849 **
   76850 ** Is equivalent to:
   76851 **
   76852 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
   76853 **
   76854 ** The result of random()%5 in the GROUP BY clause is probably different
   76855 ** from the result in the result-set.  On the other hand Standard SQL does
   76856 ** not allow the GROUP BY clause to contain references to result-set columns.
   76857 ** So this should never come up in well-formed queries.
   76858 **
   76859 ** If the reference is followed by a COLLATE operator, then make sure
   76860 ** the COLLATE operator is preserved.  For example:
   76861 **
   76862 **     SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
   76863 **
   76864 ** Should be transformed into:
   76865 **
   76866 **     SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
   76867 **
   76868 ** The nSubquery parameter specifies how many levels of subquery the
   76869 ** alias is removed from the original expression.  The usually value is
   76870 ** zero but it might be more if the alias is contained within a subquery
   76871 ** of the original expression.  The Expr.op2 field of TK_AGG_FUNCTION
   76872 ** structures must be increased by the nSubquery amount.
   76873 */
   76874 static void resolveAlias(
   76875   Parse *pParse,         /* Parsing context */
   76876   ExprList *pEList,      /* A result set */
   76877   int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
   76878   Expr *pExpr,           /* Transform this into an alias to the result set */
   76879   const char *zType,     /* "GROUP" or "ORDER" or "" */
   76880   int nSubquery          /* Number of subqueries that the label is moving */
   76881 ){
   76882   Expr *pOrig;           /* The iCol-th column of the result set */
   76883   Expr *pDup;            /* Copy of pOrig */
   76884   sqlite3 *db;           /* The database connection */
   76885 
   76886   assert( iCol>=0 && iCol<pEList->nExpr );
   76887   pOrig = pEList->a[iCol].pExpr;
   76888   assert( pOrig!=0 );
   76889   assert( pOrig->flags & EP_Resolved );
   76890   db = pParse->db;
   76891   pDup = sqlite3ExprDup(db, pOrig, 0);
   76892   if( pDup==0 ) return;
   76893   if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
   76894     incrAggFunctionDepth(pDup, nSubquery);
   76895     pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
   76896     if( pDup==0 ) return;
   76897     ExprSetProperty(pDup, EP_Skip);
   76898     if( pEList->a[iCol].u.x.iAlias==0 ){
   76899       pEList->a[iCol].u.x.iAlias = (u16)(++pParse->nAlias);
   76900     }
   76901     pDup->iTable = pEList->a[iCol].u.x.iAlias;
   76902   }
   76903   if( pExpr->op==TK_COLLATE ){
   76904     pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
   76905   }
   76906 
   76907   /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
   76908   ** prevents ExprDelete() from deleting the Expr structure itself,
   76909   ** allowing it to be repopulated by the memcpy() on the following line.
   76910   ** The pExpr->u.zToken might point into memory that will be freed by the
   76911   ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
   76912   ** make a copy of the token before doing the sqlite3DbFree().
   76913   */
   76914   ExprSetProperty(pExpr, EP_Static);
   76915   sqlite3ExprDelete(db, pExpr);
   76916   memcpy(pExpr, pDup, sizeof(*pExpr));
   76917   if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
   76918     assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
   76919     pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
   76920     pExpr->flags |= EP_MemToken;
   76921   }
   76922   sqlite3DbFree(db, pDup);
   76923 }
   76924 
   76925 
   76926 /*
   76927 ** Return TRUE if the name zCol occurs anywhere in the USING clause.
   76928 **
   76929 ** Return FALSE if the USING clause is NULL or if it does not contain
   76930 ** zCol.
   76931 */
   76932 static int nameInUsingClause(IdList *pUsing, const char *zCol){
   76933   if( pUsing ){
   76934     int k;
   76935     for(k=0; k<pUsing->nId; k++){
   76936       if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
   76937     }
   76938   }
   76939   return 0;
   76940 }
   76941 
   76942 /*
   76943 ** Subqueries stores the original database, table and column names for their
   76944 ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
   76945 ** Check to see if the zSpan given to this routine matches the zDb, zTab,
   76946 ** and zCol.  If any of zDb, zTab, and zCol are NULL then those fields will
   76947 ** match anything.
   76948 */
   76949 SQLITE_PRIVATE int sqlite3MatchSpanName(
   76950   const char *zSpan,
   76951   const char *zCol,
   76952   const char *zTab,
   76953   const char *zDb
   76954 ){
   76955   int n;
   76956   for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
   76957   if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
   76958     return 0;
   76959   }
   76960   zSpan += n+1;
   76961   for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
   76962   if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
   76963     return 0;
   76964   }
   76965   zSpan += n+1;
   76966   if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
   76967     return 0;
   76968   }
   76969   return 1;
   76970 }
   76971 
   76972 /*
   76973 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
   76974 ** that name in the set of source tables in pSrcList and make the pExpr
   76975 ** expression node refer back to that source column.  The following changes
   76976 ** are made to pExpr:
   76977 **
   76978 **    pExpr->iDb           Set the index in db->aDb[] of the database X
   76979 **                         (even if X is implied).
   76980 **    pExpr->iTable        Set to the cursor number for the table obtained
   76981 **                         from pSrcList.
   76982 **    pExpr->pTab          Points to the Table structure of X.Y (even if
   76983 **                         X and/or Y are implied.)
   76984 **    pExpr->iColumn       Set to the column number within the table.
   76985 **    pExpr->op            Set to TK_COLUMN.
   76986 **    pExpr->pLeft         Any expression this points to is deleted
   76987 **    pExpr->pRight        Any expression this points to is deleted.
   76988 **
   76989 ** The zDb variable is the name of the database (the "X").  This value may be
   76990 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
   76991 ** can be used.  The zTable variable is the name of the table (the "Y").  This
   76992 ** value can be NULL if zDb is also NULL.  If zTable is NULL it
   76993 ** means that the form of the name is Z and that columns from any table
   76994 ** can be used.
   76995 **
   76996 ** If the name cannot be resolved unambiguously, leave an error message
   76997 ** in pParse and return WRC_Abort.  Return WRC_Prune on success.
   76998 */
   76999 static int lookupName(
   77000   Parse *pParse,       /* The parsing context */
   77001   const char *zDb,     /* Name of the database containing table, or NULL */
   77002   const char *zTab,    /* Name of table containing column, or NULL */
   77003   const char *zCol,    /* Name of the column. */
   77004   NameContext *pNC,    /* The name context used to resolve the name */
   77005   Expr *pExpr          /* Make this EXPR node point to the selected column */
   77006 ){
   77007   int i, j;                         /* Loop counters */
   77008   int cnt = 0;                      /* Number of matching column names */
   77009   int cntTab = 0;                   /* Number of matching table names */
   77010   int nSubquery = 0;                /* How many levels of subquery */
   77011   sqlite3 *db = pParse->db;         /* The database connection */
   77012   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
   77013   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
   77014   NameContext *pTopNC = pNC;        /* First namecontext in the list */
   77015   Schema *pSchema = 0;              /* Schema of the expression */
   77016   int isTrigger = 0;                /* True if resolved to a trigger column */
   77017   Table *pTab = 0;                  /* Table hold the row */
   77018   Column *pCol;                     /* A column of pTab */
   77019 
   77020   assert( pNC );     /* the name context cannot be NULL. */
   77021   assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
   77022   assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
   77023 
   77024   /* Initialize the node to no-match */
   77025   pExpr->iTable = -1;
   77026   pExpr->pTab = 0;
   77027   ExprSetVVAProperty(pExpr, EP_NoReduce);
   77028 
   77029   /* Translate the schema name in zDb into a pointer to the corresponding
   77030   ** schema.  If not found, pSchema will remain NULL and nothing will match
   77031   ** resulting in an appropriate error message toward the end of this routine
   77032   */
   77033   if( zDb ){
   77034     testcase( pNC->ncFlags & NC_PartIdx );
   77035     testcase( pNC->ncFlags & NC_IsCheck );
   77036     if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
   77037       /* Silently ignore database qualifiers inside CHECK constraints and partial
   77038       ** indices.  Do not raise errors because that might break legacy and
   77039       ** because it does not hurt anything to just ignore the database name. */
   77040       zDb = 0;
   77041     }else{
   77042       for(i=0; i<db->nDb; i++){
   77043         assert( db->aDb[i].zName );
   77044         if( sqlite3StrICmp(db->aDb[i].zName,zDb)==0 ){
   77045           pSchema = db->aDb[i].pSchema;
   77046           break;
   77047         }
   77048       }
   77049     }
   77050   }
   77051 
   77052   /* Start at the inner-most context and move outward until a match is found */
   77053   while( pNC && cnt==0 ){
   77054     ExprList *pEList;
   77055     SrcList *pSrcList = pNC->pSrcList;
   77056 
   77057     if( pSrcList ){
   77058       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
   77059         pTab = pItem->pTab;
   77060         assert( pTab!=0 && pTab->zName!=0 );
   77061         assert( pTab->nCol>0 );
   77062         if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
   77063           int hit = 0;
   77064           pEList = pItem->pSelect->pEList;
   77065           for(j=0; j<pEList->nExpr; j++){
   77066             if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
   77067               cnt++;
   77068               cntTab = 2;
   77069               pMatch = pItem;
   77070               pExpr->iColumn = j;
   77071               hit = 1;
   77072             }
   77073           }
   77074           if( hit || zTab==0 ) continue;
   77075         }
   77076         if( zDb && pTab->pSchema!=pSchema ){
   77077           continue;
   77078         }
   77079         if( zTab ){
   77080           const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
   77081           assert( zTabName!=0 );
   77082           if( sqlite3StrICmp(zTabName, zTab)!=0 ){
   77083             continue;
   77084           }
   77085         }
   77086         if( 0==(cntTab++) ){
   77087           pMatch = pItem;
   77088         }
   77089         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
   77090           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
   77091             /* If there has been exactly one prior match and this match
   77092             ** is for the right-hand table of a NATURAL JOIN or is in a
   77093             ** USING clause, then skip this match.
   77094             */
   77095             if( cnt==1 ){
   77096               if( pItem->jointype & JT_NATURAL ) continue;
   77097               if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
   77098             }
   77099             cnt++;
   77100             pMatch = pItem;
   77101             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
   77102             pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
   77103             break;
   77104           }
   77105         }
   77106       }
   77107       if( pMatch ){
   77108         pExpr->iTable = pMatch->iCursor;
   77109         pExpr->pTab = pMatch->pTab;
   77110         pSchema = pExpr->pTab->pSchema;
   77111       }
   77112     } /* if( pSrcList ) */
   77113 
   77114 #ifndef SQLITE_OMIT_TRIGGER
   77115     /* If we have not already resolved the name, then maybe
   77116     ** it is a new.* or old.* trigger argument reference
   77117     */
   77118     if( zDb==0 && zTab!=0 && cntTab==0 && pParse->pTriggerTab!=0 ){
   77119       int op = pParse->eTriggerOp;
   77120       assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
   77121       if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
   77122         pExpr->iTable = 1;
   77123         pTab = pParse->pTriggerTab;
   77124       }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
   77125         pExpr->iTable = 0;
   77126         pTab = pParse->pTriggerTab;
   77127       }else{
   77128         pTab = 0;
   77129       }
   77130 
   77131       if( pTab ){
   77132         int iCol;
   77133         pSchema = pTab->pSchema;
   77134         cntTab++;
   77135         for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
   77136           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
   77137             if( iCol==pTab->iPKey ){
   77138               iCol = -1;
   77139             }
   77140             break;
   77141           }
   77142         }
   77143         if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && HasRowid(pTab) ){
   77144           /* IMP: R-51414-32910 */
   77145           /* IMP: R-44911-55124 */
   77146           iCol = -1;
   77147         }
   77148         if( iCol<pTab->nCol ){
   77149           cnt++;
   77150           if( iCol<0 ){
   77151             pExpr->affinity = SQLITE_AFF_INTEGER;
   77152           }else if( pExpr->iTable==0 ){
   77153             testcase( iCol==31 );
   77154             testcase( iCol==32 );
   77155             pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
   77156           }else{
   77157             testcase( iCol==31 );
   77158             testcase( iCol==32 );
   77159             pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
   77160           }
   77161           pExpr->iColumn = (i16)iCol;
   77162           pExpr->pTab = pTab;
   77163           isTrigger = 1;
   77164         }
   77165       }
   77166     }
   77167 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
   77168 
   77169     /*
   77170     ** Perhaps the name is a reference to the ROWID
   77171     */
   77172     if( cnt==0 && cntTab==1 && pMatch && sqlite3IsRowid(zCol)
   77173      && HasRowid(pMatch->pTab) ){
   77174       cnt = 1;
   77175       pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
   77176       pExpr->affinity = SQLITE_AFF_INTEGER;
   77177     }
   77178 
   77179     /*
   77180     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
   77181     ** might refer to an result-set alias.  This happens, for example, when
   77182     ** we are resolving names in the WHERE clause of the following command:
   77183     **
   77184     **     SELECT a+b AS x FROM table WHERE x<10;
   77185     **
   77186     ** In cases like this, replace pExpr with a copy of the expression that
   77187     ** forms the result set entry ("a+b" in the example) and return immediately.
   77188     ** Note that the expression in the result set should have already been
   77189     ** resolved by the time the WHERE clause is resolved.
   77190     **
   77191     ** The ability to use an output result-set column in the WHERE, GROUP BY,
   77192     ** or HAVING clauses, or as part of a larger expression in the ORDRE BY
   77193     ** clause is not standard SQL.  This is a (goofy) SQLite extension, that
   77194     ** is supported for backwards compatibility only.  TO DO: Issue a warning
   77195     ** on sqlite3_log() whenever the capability is used.
   77196     */
   77197     if( (pEList = pNC->pEList)!=0
   77198      && zTab==0
   77199      && cnt==0
   77200     ){
   77201       for(j=0; j<pEList->nExpr; j++){
   77202         char *zAs = pEList->a[j].zName;
   77203         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
   77204           Expr *pOrig;
   77205           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
   77206           assert( pExpr->x.pList==0 );
   77207           assert( pExpr->x.pSelect==0 );
   77208           pOrig = pEList->a[j].pExpr;
   77209           if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
   77210             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
   77211             return WRC_Abort;
   77212           }
   77213           resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
   77214           cnt = 1;
   77215           pMatch = 0;
   77216           assert( zTab==0 && zDb==0 );
   77217           goto lookupname_end;
   77218         }
   77219       }
   77220     }
   77221 
   77222     /* Advance to the next name context.  The loop will exit when either
   77223     ** we have a match (cnt>0) or when we run out of name contexts.
   77224     */
   77225     if( cnt==0 ){
   77226       pNC = pNC->pNext;
   77227       nSubquery++;
   77228     }
   77229   }
   77230 
   77231   /*
   77232   ** If X and Y are NULL (in other words if only the column name Z is
   77233   ** supplied) and the value of Z is enclosed in double-quotes, then
   77234   ** Z is a string literal if it doesn't match any column names.  In that
   77235   ** case, we need to return right away and not make any changes to
   77236   ** pExpr.
   77237   **
   77238   ** Because no reference was made to outer contexts, the pNC->nRef
   77239   ** fields are not changed in any context.
   77240   */
   77241   if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
   77242     pExpr->op = TK_STRING;
   77243     pExpr->pTab = 0;
   77244     return WRC_Prune;
   77245   }
   77246 
   77247   /*
   77248   ** cnt==0 means there was not match.  cnt>1 means there were two or
   77249   ** more matches.  Either way, we have an error.
   77250   */
   77251   if( cnt!=1 ){
   77252     const char *zErr;
   77253     zErr = cnt==0 ? "no such column" : "ambiguous column name";
   77254     if( zDb ){
   77255       sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
   77256     }else if( zTab ){
   77257       sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
   77258     }else{
   77259       sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
   77260     }
   77261     pParse->checkSchema = 1;
   77262     pTopNC->nErr++;
   77263   }
   77264 
   77265   /* If a column from a table in pSrcList is referenced, then record
   77266   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
   77267   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
   77268   ** column number is greater than the number of bits in the bitmask
   77269   ** then set the high-order bit of the bitmask.
   77270   */
   77271   if( pExpr->iColumn>=0 && pMatch!=0 ){
   77272     int n = pExpr->iColumn;
   77273     testcase( n==BMS-1 );
   77274     if( n>=BMS ){
   77275       n = BMS-1;
   77276     }
   77277     assert( pMatch->iCursor==pExpr->iTable );
   77278     pMatch->colUsed |= ((Bitmask)1)<<n;
   77279   }
   77280 
   77281   /* Clean up and return
   77282   */
   77283   sqlite3ExprDelete(db, pExpr->pLeft);
   77284   pExpr->pLeft = 0;
   77285   sqlite3ExprDelete(db, pExpr->pRight);
   77286   pExpr->pRight = 0;
   77287   pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
   77288 lookupname_end:
   77289   if( cnt==1 ){
   77290     assert( pNC!=0 );
   77291     if( pExpr->op!=TK_AS ){
   77292       sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
   77293     }
   77294     /* Increment the nRef value on all name contexts from TopNC up to
   77295     ** the point where the name matched. */
   77296     for(;;){
   77297       assert( pTopNC!=0 );
   77298       pTopNC->nRef++;
   77299       if( pTopNC==pNC ) break;
   77300       pTopNC = pTopNC->pNext;
   77301     }
   77302     return WRC_Prune;
   77303   } else {
   77304     return WRC_Abort;
   77305   }
   77306 }
   77307 
   77308 /*
   77309 ** Allocate and return a pointer to an expression to load the column iCol
   77310 ** from datasource iSrc in SrcList pSrc.
   77311 */
   77312 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
   77313   Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
   77314   if( p ){
   77315     struct SrcList_item *pItem = &pSrc->a[iSrc];
   77316     p->pTab = pItem->pTab;
   77317     p->iTable = pItem->iCursor;
   77318     if( p->pTab->iPKey==iCol ){
   77319       p->iColumn = -1;
   77320     }else{
   77321       p->iColumn = (ynVar)iCol;
   77322       testcase( iCol==BMS );
   77323       testcase( iCol==BMS-1 );
   77324       pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
   77325     }
   77326     ExprSetProperty(p, EP_Resolved);
   77327   }
   77328   return p;
   77329 }
   77330 
   77331 /*
   77332 ** Report an error that an expression is not valid for a partial index WHERE
   77333 ** clause.
   77334 */
   77335 static void notValidPartIdxWhere(
   77336   Parse *pParse,       /* Leave error message here */
   77337   NameContext *pNC,    /* The name context */
   77338   const char *zMsg     /* Type of error */
   77339 ){
   77340   if( (pNC->ncFlags & NC_PartIdx)!=0 ){
   77341     sqlite3ErrorMsg(pParse, "%s prohibited in partial index WHERE clauses",
   77342                     zMsg);
   77343   }
   77344 }
   77345 
   77346 #ifndef SQLITE_OMIT_CHECK
   77347 /*
   77348 ** Report an error that an expression is not valid for a CHECK constraint.
   77349 */
   77350 static void notValidCheckConstraint(
   77351   Parse *pParse,       /* Leave error message here */
   77352   NameContext *pNC,    /* The name context */
   77353   const char *zMsg     /* Type of error */
   77354 ){
   77355   if( (pNC->ncFlags & NC_IsCheck)!=0 ){
   77356     sqlite3ErrorMsg(pParse,"%s prohibited in CHECK constraints", zMsg);
   77357   }
   77358 }
   77359 #else
   77360 # define notValidCheckConstraint(P,N,M)
   77361 #endif
   77362 
   77363 /*
   77364 ** Expression p should encode a floating point value between 1.0 and 0.0.
   77365 ** Return 1024 times this value.  Or return -1 if p is not a floating point
   77366 ** value between 1.0 and 0.0.
   77367 */
   77368 static int exprProbability(Expr *p){
   77369   double r = -1.0;
   77370   if( p->op!=TK_FLOAT ) return -1;
   77371   sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
   77372   assert( r>=0.0 );
   77373   if( r>1.0 ) return -1;
   77374   return (int)(r*1000.0);
   77375 }
   77376 
   77377 /*
   77378 ** This routine is callback for sqlite3WalkExpr().
   77379 **
   77380 ** Resolve symbolic names into TK_COLUMN operators for the current
   77381 ** node in the expression tree.  Return 0 to continue the search down
   77382 ** the tree or 2 to abort the tree walk.
   77383 **
   77384 ** This routine also does error checking and name resolution for
   77385 ** function names.  The operator for aggregate functions is changed
   77386 ** to TK_AGG_FUNCTION.
   77387 */
   77388 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
   77389   NameContext *pNC;
   77390   Parse *pParse;
   77391 
   77392   pNC = pWalker->u.pNC;
   77393   assert( pNC!=0 );
   77394   pParse = pNC->pParse;
   77395   assert( pParse==pWalker->pParse );
   77396 
   77397   if( ExprHasProperty(pExpr, EP_Resolved) ) return WRC_Prune;
   77398   ExprSetProperty(pExpr, EP_Resolved);
   77399 #ifndef NDEBUG
   77400   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
   77401     SrcList *pSrcList = pNC->pSrcList;
   77402     int i;
   77403     for(i=0; i<pNC->pSrcList->nSrc; i++){
   77404       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
   77405     }
   77406   }
   77407 #endif
   77408   switch( pExpr->op ){
   77409 
   77410 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
   77411     /* The special operator TK_ROW means use the rowid for the first
   77412     ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
   77413     ** clause processing on UPDATE and DELETE statements.
   77414     */
   77415     case TK_ROW: {
   77416       SrcList *pSrcList = pNC->pSrcList;
   77417       struct SrcList_item *pItem;
   77418       assert( pSrcList && pSrcList->nSrc==1 );
   77419       pItem = pSrcList->a;
   77420       pExpr->op = TK_COLUMN;
   77421       pExpr->pTab = pItem->pTab;
   77422       pExpr->iTable = pItem->iCursor;
   77423       pExpr->iColumn = -1;
   77424       pExpr->affinity = SQLITE_AFF_INTEGER;
   77425       break;
   77426     }
   77427 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
   77428 
   77429     /* A lone identifier is the name of a column.
   77430     */
   77431     case TK_ID: {
   77432       return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
   77433     }
   77434 
   77435     /* A table name and column name:     ID.ID
   77436     ** Or a database, table and column:  ID.ID.ID
   77437     */
   77438     case TK_DOT: {
   77439       const char *zColumn;
   77440       const char *zTable;
   77441       const char *zDb;
   77442       Expr *pRight;
   77443 
   77444       /* if( pSrcList==0 ) break; */
   77445       pRight = pExpr->pRight;
   77446       if( pRight->op==TK_ID ){
   77447         zDb = 0;
   77448         zTable = pExpr->pLeft->u.zToken;
   77449         zColumn = pRight->u.zToken;
   77450       }else{
   77451         assert( pRight->op==TK_DOT );
   77452         zDb = pExpr->pLeft->u.zToken;
   77453         zTable = pRight->pLeft->u.zToken;
   77454         zColumn = pRight->pRight->u.zToken;
   77455       }
   77456       return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
   77457     }
   77458 
   77459     /* Resolve function names
   77460     */
   77461     case TK_FUNCTION: {
   77462       ExprList *pList = pExpr->x.pList;    /* The argument list */
   77463       int n = pList ? pList->nExpr : 0;    /* Number of arguments */
   77464       int no_such_func = 0;       /* True if no such function exists */
   77465       int wrong_num_args = 0;     /* True if wrong number of arguments */
   77466       int is_agg = 0;             /* True if is an aggregate function */
   77467       int auth;                   /* Authorization to use the function */
   77468       int nId;                    /* Number of characters in function name */
   77469       const char *zId;            /* The function name. */
   77470       FuncDef *pDef;              /* Information about the function */
   77471       u8 enc = ENC(pParse->db);   /* The database encoding */
   77472 
   77473       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   77474       notValidPartIdxWhere(pParse, pNC, "functions");
   77475       zId = pExpr->u.zToken;
   77476       nId = sqlite3Strlen30(zId);
   77477       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
   77478       if( pDef==0 ){
   77479         pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
   77480         if( pDef==0 ){
   77481           no_such_func = 1;
   77482         }else{
   77483           wrong_num_args = 1;
   77484         }
   77485       }else{
   77486         is_agg = pDef->xFunc==0;
   77487         if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
   77488           ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
   77489           if( n==2 ){
   77490             pExpr->iTable = exprProbability(pList->a[1].pExpr);
   77491             if( pExpr->iTable<0 ){
   77492               sqlite3ErrorMsg(pParse, "second argument to likelihood() must be a "
   77493                                       "constant between 0.0 and 1.0");
   77494               pNC->nErr++;
   77495             }
   77496           }else{
   77497             /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is equivalent to
   77498             ** likelihood(X, 0.0625).
   77499             ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is short-hand for
   77500             ** likelihood(X,0.0625).
   77501             ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand for
   77502             ** likelihood(X,0.9375).
   77503             ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent to
   77504             ** likelihood(X,0.9375). */
   77505             /* TUNING: unlikely() probability is 0.0625.  likely() is 0.9375 */
   77506             pExpr->iTable = pDef->zName[0]=='u' ? 62 : 938;
   77507           }
   77508         }
   77509       }
   77510 #ifndef SQLITE_OMIT_AUTHORIZATION
   77511       if( pDef ){
   77512         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
   77513         if( auth!=SQLITE_OK ){
   77514           if( auth==SQLITE_DENY ){
   77515             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
   77516                                     pDef->zName);
   77517             pNC->nErr++;
   77518           }
   77519           pExpr->op = TK_NULL;
   77520           return WRC_Prune;
   77521         }
   77522         if( pDef->funcFlags & SQLITE_FUNC_CONSTANT ) ExprSetProperty(pExpr,EP_Constant);
   77523       }
   77524 #endif
   77525       if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
   77526         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
   77527         pNC->nErr++;
   77528         is_agg = 0;
   77529       }else if( no_such_func && pParse->db->init.busy==0 ){
   77530         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
   77531         pNC->nErr++;
   77532       }else if( wrong_num_args ){
   77533         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
   77534              nId, zId);
   77535         pNC->nErr++;
   77536       }
   77537       if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
   77538       sqlite3WalkExprList(pWalker, pList);
   77539       if( is_agg ){
   77540         NameContext *pNC2 = pNC;
   77541         pExpr->op = TK_AGG_FUNCTION;
   77542         pExpr->op2 = 0;
   77543         while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
   77544           pExpr->op2++;
   77545           pNC2 = pNC2->pNext;
   77546         }
   77547         if( pNC2 ) pNC2->ncFlags |= NC_HasAgg;
   77548         pNC->ncFlags |= NC_AllowAgg;
   77549       }
   77550       /* FIX ME:  Compute pExpr->affinity based on the expected return
   77551       ** type of the function
   77552       */
   77553       return WRC_Prune;
   77554     }
   77555 #ifndef SQLITE_OMIT_SUBQUERY
   77556     case TK_SELECT:
   77557     case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
   77558 #endif
   77559     case TK_IN: {
   77560       testcase( pExpr->op==TK_IN );
   77561       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   77562         int nRef = pNC->nRef;
   77563         notValidCheckConstraint(pParse, pNC, "subqueries");
   77564         notValidPartIdxWhere(pParse, pNC, "subqueries");
   77565         sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
   77566         assert( pNC->nRef>=nRef );
   77567         if( nRef!=pNC->nRef ){
   77568           ExprSetProperty(pExpr, EP_VarSelect);
   77569         }
   77570       }
   77571       break;
   77572     }
   77573     case TK_VARIABLE: {
   77574       notValidCheckConstraint(pParse, pNC, "parameters");
   77575       notValidPartIdxWhere(pParse, pNC, "parameters");
   77576       break;
   77577     }
   77578   }
   77579   return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
   77580 }
   77581 
   77582 /*
   77583 ** pEList is a list of expressions which are really the result set of the
   77584 ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
   77585 ** This routine checks to see if pE is a simple identifier which corresponds
   77586 ** to the AS-name of one of the terms of the expression list.  If it is,
   77587 ** this routine return an integer between 1 and N where N is the number of
   77588 ** elements in pEList, corresponding to the matching entry.  If there is
   77589 ** no match, or if pE is not a simple identifier, then this routine
   77590 ** return 0.
   77591 **
   77592 ** pEList has been resolved.  pE has not.
   77593 */
   77594 static int resolveAsName(
   77595   Parse *pParse,     /* Parsing context for error messages */
   77596   ExprList *pEList,  /* List of expressions to scan */
   77597   Expr *pE           /* Expression we are trying to match */
   77598 ){
   77599   int i;             /* Loop counter */
   77600 
   77601   UNUSED_PARAMETER(pParse);
   77602 
   77603   if( pE->op==TK_ID ){
   77604     char *zCol = pE->u.zToken;
   77605     for(i=0; i<pEList->nExpr; i++){
   77606       char *zAs = pEList->a[i].zName;
   77607       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
   77608         return i+1;
   77609       }
   77610     }
   77611   }
   77612   return 0;
   77613 }
   77614 
   77615 /*
   77616 ** pE is a pointer to an expression which is a single term in the
   77617 ** ORDER BY of a compound SELECT.  The expression has not been
   77618 ** name resolved.
   77619 **
   77620 ** At the point this routine is called, we already know that the
   77621 ** ORDER BY term is not an integer index into the result set.  That
   77622 ** case is handled by the calling routine.
   77623 **
   77624 ** Attempt to match pE against result set columns in the left-most
   77625 ** SELECT statement.  Return the index i of the matching column,
   77626 ** as an indication to the caller that it should sort by the i-th column.
   77627 ** The left-most column is 1.  In other words, the value returned is the
   77628 ** same integer value that would be used in the SQL statement to indicate
   77629 ** the column.
   77630 **
   77631 ** If there is no match, return 0.  Return -1 if an error occurs.
   77632 */
   77633 static int resolveOrderByTermToExprList(
   77634   Parse *pParse,     /* Parsing context for error messages */
   77635   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
   77636   Expr *pE           /* The specific ORDER BY term */
   77637 ){
   77638   int i;             /* Loop counter */
   77639   ExprList *pEList;  /* The columns of the result set */
   77640   NameContext nc;    /* Name context for resolving pE */
   77641   sqlite3 *db;       /* Database connection */
   77642   int rc;            /* Return code from subprocedures */
   77643   u8 savedSuppErr;   /* Saved value of db->suppressErr */
   77644 
   77645   assert( sqlite3ExprIsInteger(pE, &i)==0 );
   77646   pEList = pSelect->pEList;
   77647 
   77648   /* Resolve all names in the ORDER BY term expression
   77649   */
   77650   memset(&nc, 0, sizeof(nc));
   77651   nc.pParse = pParse;
   77652   nc.pSrcList = pSelect->pSrc;
   77653   nc.pEList = pEList;
   77654   nc.ncFlags = NC_AllowAgg;
   77655   nc.nErr = 0;
   77656   db = pParse->db;
   77657   savedSuppErr = db->suppressErr;
   77658   db->suppressErr = 1;
   77659   rc = sqlite3ResolveExprNames(&nc, pE);
   77660   db->suppressErr = savedSuppErr;
   77661   if( rc ) return 0;
   77662 
   77663   /* Try to match the ORDER BY expression against an expression
   77664   ** in the result set.  Return an 1-based index of the matching
   77665   ** result-set entry.
   77666   */
   77667   for(i=0; i<pEList->nExpr; i++){
   77668     if( sqlite3ExprCompare(pEList->a[i].pExpr, pE, -1)<2 ){
   77669       return i+1;
   77670     }
   77671   }
   77672 
   77673   /* If no match, return 0. */
   77674   return 0;
   77675 }
   77676 
   77677 /*
   77678 ** Generate an ORDER BY or GROUP BY term out-of-range error.
   77679 */
   77680 static void resolveOutOfRangeError(
   77681   Parse *pParse,         /* The error context into which to write the error */
   77682   const char *zType,     /* "ORDER" or "GROUP" */
   77683   int i,                 /* The index (1-based) of the term out of range */
   77684   int mx                 /* Largest permissible value of i */
   77685 ){
   77686   sqlite3ErrorMsg(pParse,
   77687     "%r %s BY term out of range - should be "
   77688     "between 1 and %d", i, zType, mx);
   77689 }
   77690 
   77691 /*
   77692 ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
   77693 ** each term of the ORDER BY clause is a constant integer between 1
   77694 ** and N where N is the number of columns in the compound SELECT.
   77695 **
   77696 ** ORDER BY terms that are already an integer between 1 and N are
   77697 ** unmodified.  ORDER BY terms that are integers outside the range of
   77698 ** 1 through N generate an error.  ORDER BY terms that are expressions
   77699 ** are matched against result set expressions of compound SELECT
   77700 ** beginning with the left-most SELECT and working toward the right.
   77701 ** At the first match, the ORDER BY expression is transformed into
   77702 ** the integer column number.
   77703 **
   77704 ** Return the number of errors seen.
   77705 */
   77706 static int resolveCompoundOrderBy(
   77707   Parse *pParse,        /* Parsing context.  Leave error messages here */
   77708   Select *pSelect       /* The SELECT statement containing the ORDER BY */
   77709 ){
   77710   int i;
   77711   ExprList *pOrderBy;
   77712   ExprList *pEList;
   77713   sqlite3 *db;
   77714   int moreToDo = 1;
   77715 
   77716   pOrderBy = pSelect->pOrderBy;
   77717   if( pOrderBy==0 ) return 0;
   77718   db = pParse->db;
   77719 #if SQLITE_MAX_COLUMN
   77720   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
   77721     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
   77722     return 1;
   77723   }
   77724 #endif
   77725   for(i=0; i<pOrderBy->nExpr; i++){
   77726     pOrderBy->a[i].done = 0;
   77727   }
   77728   pSelect->pNext = 0;
   77729   while( pSelect->pPrior ){
   77730     pSelect->pPrior->pNext = pSelect;
   77731     pSelect = pSelect->pPrior;
   77732   }
   77733   while( pSelect && moreToDo ){
   77734     struct ExprList_item *pItem;
   77735     moreToDo = 0;
   77736     pEList = pSelect->pEList;
   77737     assert( pEList!=0 );
   77738     for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
   77739       int iCol = -1;
   77740       Expr *pE, *pDup;
   77741       if( pItem->done ) continue;
   77742       pE = sqlite3ExprSkipCollate(pItem->pExpr);
   77743       if( sqlite3ExprIsInteger(pE, &iCol) ){
   77744         if( iCol<=0 || iCol>pEList->nExpr ){
   77745           resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
   77746           return 1;
   77747         }
   77748       }else{
   77749         iCol = resolveAsName(pParse, pEList, pE);
   77750         if( iCol==0 ){
   77751           pDup = sqlite3ExprDup(db, pE, 0);
   77752           if( !db->mallocFailed ){
   77753             assert(pDup);
   77754             iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
   77755           }
   77756           sqlite3ExprDelete(db, pDup);
   77757         }
   77758       }
   77759       if( iCol>0 ){
   77760         /* Convert the ORDER BY term into an integer column number iCol,
   77761         ** taking care to preserve the COLLATE clause if it exists */
   77762         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
   77763         if( pNew==0 ) return 1;
   77764         pNew->flags |= EP_IntValue;
   77765         pNew->u.iValue = iCol;
   77766         if( pItem->pExpr==pE ){
   77767           pItem->pExpr = pNew;
   77768         }else{
   77769           assert( pItem->pExpr->op==TK_COLLATE );
   77770           assert( pItem->pExpr->pLeft==pE );
   77771           pItem->pExpr->pLeft = pNew;
   77772         }
   77773         sqlite3ExprDelete(db, pE);
   77774         pItem->u.x.iOrderByCol = (u16)iCol;
   77775         pItem->done = 1;
   77776       }else{
   77777         moreToDo = 1;
   77778       }
   77779     }
   77780     pSelect = pSelect->pNext;
   77781   }
   77782   for(i=0; i<pOrderBy->nExpr; i++){
   77783     if( pOrderBy->a[i].done==0 ){
   77784       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
   77785             "column in the result set", i+1);
   77786       return 1;
   77787     }
   77788   }
   77789   return 0;
   77790 }
   77791 
   77792 /*
   77793 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
   77794 ** the SELECT statement pSelect.  If any term is reference to a
   77795 ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
   77796 ** field) then convert that term into a copy of the corresponding result set
   77797 ** column.
   77798 **
   77799 ** If any errors are detected, add an error message to pParse and
   77800 ** return non-zero.  Return zero if no errors are seen.
   77801 */
   77802 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
   77803   Parse *pParse,        /* Parsing context.  Leave error messages here */
   77804   Select *pSelect,      /* The SELECT statement containing the clause */
   77805   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
   77806   const char *zType     /* "ORDER" or "GROUP" */
   77807 ){
   77808   int i;
   77809   sqlite3 *db = pParse->db;
   77810   ExprList *pEList;
   77811   struct ExprList_item *pItem;
   77812 
   77813   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
   77814 #if SQLITE_MAX_COLUMN
   77815   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
   77816     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
   77817     return 1;
   77818   }
   77819 #endif
   77820   pEList = pSelect->pEList;
   77821   assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
   77822   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
   77823     if( pItem->u.x.iOrderByCol ){
   77824       if( pItem->u.x.iOrderByCol>pEList->nExpr ){
   77825         resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
   77826         return 1;
   77827       }
   77828       resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr, zType,0);
   77829     }
   77830   }
   77831   return 0;
   77832 }
   77833 
   77834 /*
   77835 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
   77836 ** The Name context of the SELECT statement is pNC.  zType is either
   77837 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
   77838 **
   77839 ** This routine resolves each term of the clause into an expression.
   77840 ** If the order-by term is an integer I between 1 and N (where N is the
   77841 ** number of columns in the result set of the SELECT) then the expression
   77842 ** in the resolution is a copy of the I-th result-set expression.  If
   77843 ** the order-by term is an identifier that corresponds to the AS-name of
   77844 ** a result-set expression, then the term resolves to a copy of the
   77845 ** result-set expression.  Otherwise, the expression is resolved in
   77846 ** the usual way - using sqlite3ResolveExprNames().
   77847 **
   77848 ** This routine returns the number of errors.  If errors occur, then
   77849 ** an appropriate error message might be left in pParse.  (OOM errors
   77850 ** excepted.)
   77851 */
   77852 static int resolveOrderGroupBy(
   77853   NameContext *pNC,     /* The name context of the SELECT statement */
   77854   Select *pSelect,      /* The SELECT statement holding pOrderBy */
   77855   ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
   77856   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
   77857 ){
   77858   int i, j;                      /* Loop counters */
   77859   int iCol;                      /* Column number */
   77860   struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
   77861   Parse *pParse;                 /* Parsing context */
   77862   int nResult;                   /* Number of terms in the result set */
   77863 
   77864   if( pOrderBy==0 ) return 0;
   77865   nResult = pSelect->pEList->nExpr;
   77866   pParse = pNC->pParse;
   77867   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
   77868     Expr *pE = pItem->pExpr;
   77869     Expr *pE2 = sqlite3ExprSkipCollate(pE);
   77870     if( zType[0]!='G' ){
   77871       iCol = resolveAsName(pParse, pSelect->pEList, pE2);
   77872       if( iCol>0 ){
   77873         /* If an AS-name match is found, mark this ORDER BY column as being
   77874         ** a copy of the iCol-th result-set column.  The subsequent call to
   77875         ** sqlite3ResolveOrderGroupBy() will convert the expression to a
   77876         ** copy of the iCol-th result-set expression. */
   77877         pItem->u.x.iOrderByCol = (u16)iCol;
   77878         continue;
   77879       }
   77880     }
   77881     if( sqlite3ExprIsInteger(pE2, &iCol) ){
   77882       /* The ORDER BY term is an integer constant.  Again, set the column
   77883       ** number so that sqlite3ResolveOrderGroupBy() will convert the
   77884       ** order-by term to a copy of the result-set expression */
   77885       if( iCol<1 || iCol>0xffff ){
   77886         resolveOutOfRangeError(pParse, zType, i+1, nResult);
   77887         return 1;
   77888       }
   77889       pItem->u.x.iOrderByCol = (u16)iCol;
   77890       continue;
   77891     }
   77892 
   77893     /* Otherwise, treat the ORDER BY term as an ordinary expression */
   77894     pItem->u.x.iOrderByCol = 0;
   77895     if( sqlite3ResolveExprNames(pNC, pE) ){
   77896       return 1;
   77897     }
   77898     for(j=0; j<pSelect->pEList->nExpr; j++){
   77899       if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
   77900         pItem->u.x.iOrderByCol = j+1;
   77901       }
   77902     }
   77903   }
   77904   return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
   77905 }
   77906 
   77907 /*
   77908 ** Resolve names in the SELECT statement p and all of its descendents.
   77909 */
   77910 static int resolveSelectStep(Walker *pWalker, Select *p){
   77911   NameContext *pOuterNC;  /* Context that contains this SELECT */
   77912   NameContext sNC;        /* Name context of this SELECT */
   77913   int isCompound;         /* True if p is a compound select */
   77914   int nCompound;          /* Number of compound terms processed so far */
   77915   Parse *pParse;          /* Parsing context */
   77916   ExprList *pEList;       /* Result set expression list */
   77917   int i;                  /* Loop counter */
   77918   ExprList *pGroupBy;     /* The GROUP BY clause */
   77919   Select *pLeftmost;      /* Left-most of SELECT of a compound */
   77920   sqlite3 *db;            /* Database connection */
   77921 
   77922 
   77923   assert( p!=0 );
   77924   if( p->selFlags & SF_Resolved ){
   77925     return WRC_Prune;
   77926   }
   77927   pOuterNC = pWalker->u.pNC;
   77928   pParse = pWalker->pParse;
   77929   db = pParse->db;
   77930 
   77931   /* Normally sqlite3SelectExpand() will be called first and will have
   77932   ** already expanded this SELECT.  However, if this is a subquery within
   77933   ** an expression, sqlite3ResolveExprNames() will be called without a
   77934   ** prior call to sqlite3SelectExpand().  When that happens, let
   77935   ** sqlite3SelectPrep() do all of the processing for this SELECT.
   77936   ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
   77937   ** this routine in the correct order.
   77938   */
   77939   if( (p->selFlags & SF_Expanded)==0 ){
   77940     sqlite3SelectPrep(pParse, p, pOuterNC);
   77941     return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
   77942   }
   77943 
   77944   isCompound = p->pPrior!=0;
   77945   nCompound = 0;
   77946   pLeftmost = p;
   77947   while( p ){
   77948     assert( (p->selFlags & SF_Expanded)!=0 );
   77949     assert( (p->selFlags & SF_Resolved)==0 );
   77950     p->selFlags |= SF_Resolved;
   77951 
   77952     /* Resolve the expressions in the LIMIT and OFFSET clauses. These
   77953     ** are not allowed to refer to any names, so pass an empty NameContext.
   77954     */
   77955     memset(&sNC, 0, sizeof(sNC));
   77956     sNC.pParse = pParse;
   77957     if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
   77958         sqlite3ResolveExprNames(&sNC, p->pOffset) ){
   77959       return WRC_Abort;
   77960     }
   77961 
   77962     /* Recursively resolve names in all subqueries
   77963     */
   77964     for(i=0; i<p->pSrc->nSrc; i++){
   77965       struct SrcList_item *pItem = &p->pSrc->a[i];
   77966       if( pItem->pSelect ){
   77967         NameContext *pNC;         /* Used to iterate name contexts */
   77968         int nRef = 0;             /* Refcount for pOuterNC and outer contexts */
   77969         const char *zSavedContext = pParse->zAuthContext;
   77970 
   77971         /* Count the total number of references to pOuterNC and all of its
   77972         ** parent contexts. After resolving references to expressions in
   77973         ** pItem->pSelect, check if this value has changed. If so, then
   77974         ** SELECT statement pItem->pSelect must be correlated. Set the
   77975         ** pItem->isCorrelated flag if this is the case. */
   77976         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
   77977 
   77978         if( pItem->zName ) pParse->zAuthContext = pItem->zName;
   77979         sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
   77980         pParse->zAuthContext = zSavedContext;
   77981         if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
   77982 
   77983         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
   77984         assert( pItem->isCorrelated==0 && nRef<=0 );
   77985         pItem->isCorrelated = (nRef!=0);
   77986       }
   77987     }
   77988 
   77989     /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
   77990     ** resolve the result-set expression list.
   77991     */
   77992     sNC.ncFlags = NC_AllowAgg;
   77993     sNC.pSrcList = p->pSrc;
   77994     sNC.pNext = pOuterNC;
   77995 
   77996     /* Resolve names in the result set. */
   77997     pEList = p->pEList;
   77998     assert( pEList!=0 );
   77999     for(i=0; i<pEList->nExpr; i++){
   78000       Expr *pX = pEList->a[i].pExpr;
   78001       if( sqlite3ResolveExprNames(&sNC, pX) ){
   78002         return WRC_Abort;
   78003       }
   78004     }
   78005 
   78006     /* If there are no aggregate functions in the result-set, and no GROUP BY
   78007     ** expression, do not allow aggregates in any of the other expressions.
   78008     */
   78009     assert( (p->selFlags & SF_Aggregate)==0 );
   78010     pGroupBy = p->pGroupBy;
   78011     if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
   78012       p->selFlags |= SF_Aggregate;
   78013     }else{
   78014       sNC.ncFlags &= ~NC_AllowAgg;
   78015     }
   78016 
   78017     /* If a HAVING clause is present, then there must be a GROUP BY clause.
   78018     */
   78019     if( p->pHaving && !pGroupBy ){
   78020       sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
   78021       return WRC_Abort;
   78022     }
   78023 
   78024     /* Add the output column list to the name-context before parsing the
   78025     ** other expressions in the SELECT statement. This is so that
   78026     ** expressions in the WHERE clause (etc.) can refer to expressions by
   78027     ** aliases in the result set.
   78028     **
   78029     ** Minor point: If this is the case, then the expression will be
   78030     ** re-evaluated for each reference to it.
   78031     */
   78032     sNC.pEList = p->pEList;
   78033     if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
   78034     if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
   78035 
   78036     /* The ORDER BY and GROUP BY clauses may not refer to terms in
   78037     ** outer queries
   78038     */
   78039     sNC.pNext = 0;
   78040     sNC.ncFlags |= NC_AllowAgg;
   78041 
   78042     /* Process the ORDER BY clause for singleton SELECT statements.
   78043     ** The ORDER BY clause for compounds SELECT statements is handled
   78044     ** below, after all of the result-sets for all of the elements of
   78045     ** the compound have been resolved.
   78046     */
   78047     if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
   78048       return WRC_Abort;
   78049     }
   78050     if( db->mallocFailed ){
   78051       return WRC_Abort;
   78052     }
   78053 
   78054     /* Resolve the GROUP BY clause.  At the same time, make sure
   78055     ** the GROUP BY clause does not contain aggregate functions.
   78056     */
   78057     if( pGroupBy ){
   78058       struct ExprList_item *pItem;
   78059 
   78060       if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
   78061         return WRC_Abort;
   78062       }
   78063       for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
   78064         if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
   78065           sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
   78066               "the GROUP BY clause");
   78067           return WRC_Abort;
   78068         }
   78069       }
   78070     }
   78071 
   78072     /* Advance to the next term of the compound
   78073     */
   78074     p = p->pPrior;
   78075     nCompound++;
   78076   }
   78077 
   78078   /* Resolve the ORDER BY on a compound SELECT after all terms of
   78079   ** the compound have been resolved.
   78080   */
   78081   if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
   78082     return WRC_Abort;
   78083   }
   78084 
   78085   return WRC_Prune;
   78086 }
   78087 
   78088 /*
   78089 ** This routine walks an expression tree and resolves references to
   78090 ** table columns and result-set columns.  At the same time, do error
   78091 ** checking on function usage and set a flag if any aggregate functions
   78092 ** are seen.
   78093 **
   78094 ** To resolve table columns references we look for nodes (or subtrees) of the
   78095 ** form X.Y.Z or Y.Z or just Z where
   78096 **
   78097 **      X:   The name of a database.  Ex:  "main" or "temp" or
   78098 **           the symbolic name assigned to an ATTACH-ed database.
   78099 **
   78100 **      Y:   The name of a table in a FROM clause.  Or in a trigger
   78101 **           one of the special names "old" or "new".
   78102 **
   78103 **      Z:   The name of a column in table Y.
   78104 **
   78105 ** The node at the root of the subtree is modified as follows:
   78106 **
   78107 **    Expr.op        Changed to TK_COLUMN
   78108 **    Expr.pTab      Points to the Table object for X.Y
   78109 **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
   78110 **    Expr.iTable    The VDBE cursor number for X.Y
   78111 **
   78112 **
   78113 ** To resolve result-set references, look for expression nodes of the
   78114 ** form Z (with no X and Y prefix) where the Z matches the right-hand
   78115 ** size of an AS clause in the result-set of a SELECT.  The Z expression
   78116 ** is replaced by a copy of the left-hand side of the result-set expression.
   78117 ** Table-name and function resolution occurs on the substituted expression
   78118 ** tree.  For example, in:
   78119 **
   78120 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
   78121 **
   78122 ** The "x" term of the order by is replaced by "a+b" to render:
   78123 **
   78124 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
   78125 **
   78126 ** Function calls are checked to make sure that the function is
   78127 ** defined and that the correct number of arguments are specified.
   78128 ** If the function is an aggregate function, then the NC_HasAgg flag is
   78129 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
   78130 ** If an expression contains aggregate functions then the EP_Agg
   78131 ** property on the expression is set.
   78132 **
   78133 ** An error message is left in pParse if anything is amiss.  The number
   78134 ** if errors is returned.
   78135 */
   78136 SQLITE_PRIVATE int sqlite3ResolveExprNames(
   78137   NameContext *pNC,       /* Namespace to resolve expressions in. */
   78138   Expr *pExpr             /* The expression to be analyzed. */
   78139 ){
   78140   u8 savedHasAgg;
   78141   Walker w;
   78142 
   78143   if( pExpr==0 ) return 0;
   78144 #if SQLITE_MAX_EXPR_DEPTH>0
   78145   {
   78146     Parse *pParse = pNC->pParse;
   78147     if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
   78148       return 1;
   78149     }
   78150     pParse->nHeight += pExpr->nHeight;
   78151   }
   78152 #endif
   78153   savedHasAgg = pNC->ncFlags & NC_HasAgg;
   78154   pNC->ncFlags &= ~NC_HasAgg;
   78155   memset(&w, 0, sizeof(w));
   78156   w.xExprCallback = resolveExprStep;
   78157   w.xSelectCallback = resolveSelectStep;
   78158   w.pParse = pNC->pParse;
   78159   w.u.pNC = pNC;
   78160   sqlite3WalkExpr(&w, pExpr);
   78161 #if SQLITE_MAX_EXPR_DEPTH>0
   78162   pNC->pParse->nHeight -= pExpr->nHeight;
   78163 #endif
   78164   if( pNC->nErr>0 || w.pParse->nErr>0 ){
   78165     ExprSetProperty(pExpr, EP_Error);
   78166   }
   78167   if( pNC->ncFlags & NC_HasAgg ){
   78168     ExprSetProperty(pExpr, EP_Agg);
   78169   }else if( savedHasAgg ){
   78170     pNC->ncFlags |= NC_HasAgg;
   78171   }
   78172   return ExprHasProperty(pExpr, EP_Error);
   78173 }
   78174 
   78175 
   78176 /*
   78177 ** Resolve all names in all expressions of a SELECT and in all
   78178 ** decendents of the SELECT, including compounds off of p->pPrior,
   78179 ** subqueries in expressions, and subqueries used as FROM clause
   78180 ** terms.
   78181 **
   78182 ** See sqlite3ResolveExprNames() for a description of the kinds of
   78183 ** transformations that occur.
   78184 **
   78185 ** All SELECT statements should have been expanded using
   78186 ** sqlite3SelectExpand() prior to invoking this routine.
   78187 */
   78188 SQLITE_PRIVATE void sqlite3ResolveSelectNames(
   78189   Parse *pParse,         /* The parser context */
   78190   Select *p,             /* The SELECT statement being coded. */
   78191   NameContext *pOuterNC  /* Name context for parent SELECT statement */
   78192 ){
   78193   Walker w;
   78194 
   78195   assert( p!=0 );
   78196   memset(&w, 0, sizeof(w));
   78197   w.xExprCallback = resolveExprStep;
   78198   w.xSelectCallback = resolveSelectStep;
   78199   w.pParse = pParse;
   78200   w.u.pNC = pOuterNC;
   78201   sqlite3WalkSelect(&w, p);
   78202 }
   78203 
   78204 /*
   78205 ** Resolve names in expressions that can only reference a single table:
   78206 **
   78207 **    *   CHECK constraints
   78208 **    *   WHERE clauses on partial indices
   78209 **
   78210 ** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
   78211 ** is set to -1 and the Expr.iColumn value is set to the column number.
   78212 **
   78213 ** Any errors cause an error message to be set in pParse.
   78214 */
   78215 SQLITE_PRIVATE void sqlite3ResolveSelfReference(
   78216   Parse *pParse,      /* Parsing context */
   78217   Table *pTab,        /* The table being referenced */
   78218   int type,           /* NC_IsCheck or NC_PartIdx */
   78219   Expr *pExpr,        /* Expression to resolve.  May be NULL. */
   78220   ExprList *pList     /* Expression list to resolve.  May be NUL. */
   78221 ){
   78222   SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
   78223   NameContext sNC;                /* Name context for pParse->pNewTable */
   78224   int i;                          /* Loop counter */
   78225 
   78226   assert( type==NC_IsCheck || type==NC_PartIdx );
   78227   memset(&sNC, 0, sizeof(sNC));
   78228   memset(&sSrc, 0, sizeof(sSrc));
   78229   sSrc.nSrc = 1;
   78230   sSrc.a[0].zName = pTab->zName;
   78231   sSrc.a[0].pTab = pTab;
   78232   sSrc.a[0].iCursor = -1;
   78233   sNC.pParse = pParse;
   78234   sNC.pSrcList = &sSrc;
   78235   sNC.ncFlags = type;
   78236   if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
   78237   if( pList ){
   78238     for(i=0; i<pList->nExpr; i++){
   78239       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
   78240         return;
   78241       }
   78242     }
   78243   }
   78244 }
   78245 
   78246 /************** End of resolve.c *********************************************/
   78247 /************** Begin file expr.c ********************************************/
   78248 /*
   78249 ** 2001 September 15
   78250 **
   78251 ** The author disclaims copyright to this source code.  In place of
   78252 ** a legal notice, here is a blessing:
   78253 **
   78254 **    May you do good and not evil.
   78255 **    May you find forgiveness for yourself and forgive others.
   78256 **    May you share freely, never taking more than you give.
   78257 **
   78258 *************************************************************************
   78259 ** This file contains routines used for analyzing expressions and
   78260 ** for generating VDBE code that evaluates expressions in SQLite.
   78261 */
   78262 
   78263 /*
   78264 ** Return the 'affinity' of the expression pExpr if any.
   78265 **
   78266 ** If pExpr is a column, a reference to a column via an 'AS' alias,
   78267 ** or a sub-select with a column as the return value, then the
   78268 ** affinity of that column is returned. Otherwise, 0x00 is returned,
   78269 ** indicating no affinity for the expression.
   78270 **
   78271 ** i.e. the WHERE clause expresssions in the following statements all
   78272 ** have an affinity:
   78273 **
   78274 ** CREATE TABLE t1(a);
   78275 ** SELECT * FROM t1 WHERE a;
   78276 ** SELECT a AS b FROM t1 WHERE b;
   78277 ** SELECT * FROM t1 WHERE (select a from t1);
   78278 */
   78279 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
   78280   int op;
   78281   pExpr = sqlite3ExprSkipCollate(pExpr);
   78282   if( pExpr->flags & EP_Generic ) return 0;
   78283   op = pExpr->op;
   78284   if( op==TK_SELECT ){
   78285     assert( pExpr->flags&EP_xIsSelect );
   78286     return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
   78287   }
   78288 #ifndef SQLITE_OMIT_CAST
   78289   if( op==TK_CAST ){
   78290     assert( !ExprHasProperty(pExpr, EP_IntValue) );
   78291     return sqlite3AffinityType(pExpr->u.zToken, 0);
   78292   }
   78293 #endif
   78294   if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
   78295    && pExpr->pTab!=0
   78296   ){
   78297     /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
   78298     ** a TK_COLUMN but was previously evaluated and cached in a register */
   78299     int j = pExpr->iColumn;
   78300     if( j<0 ) return SQLITE_AFF_INTEGER;
   78301     assert( pExpr->pTab && j<pExpr->pTab->nCol );
   78302     return pExpr->pTab->aCol[j].affinity;
   78303   }
   78304   return pExpr->affinity;
   78305 }
   78306 
   78307 /*
   78308 ** Set the collating sequence for expression pExpr to be the collating
   78309 ** sequence named by pToken.   Return a pointer to a new Expr node that
   78310 ** implements the COLLATE operator.
   78311 **
   78312 ** If a memory allocation error occurs, that fact is recorded in pParse->db
   78313 ** and the pExpr parameter is returned unchanged.
   78314 */
   78315 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(
   78316   Parse *pParse,           /* Parsing context */
   78317   Expr *pExpr,             /* Add the "COLLATE" clause to this expression */
   78318   const Token *pCollName   /* Name of collating sequence */
   78319 ){
   78320   if( pCollName->n>0 ){
   78321     Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, 1);
   78322     if( pNew ){
   78323       pNew->pLeft = pExpr;
   78324       pNew->flags |= EP_Collate|EP_Skip;
   78325       pExpr = pNew;
   78326     }
   78327   }
   78328   return pExpr;
   78329 }
   78330 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
   78331   Token s;
   78332   assert( zC!=0 );
   78333   s.z = zC;
   78334   s.n = sqlite3Strlen30(s.z);
   78335   return sqlite3ExprAddCollateToken(pParse, pExpr, &s);
   78336 }
   78337 
   78338 /*
   78339 ** Skip over any TK_COLLATE or TK_AS operators and any unlikely()
   78340 ** or likelihood() function at the root of an expression.
   78341 */
   78342 SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
   78343   while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
   78344     if( ExprHasProperty(pExpr, EP_Unlikely) ){
   78345       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   78346       assert( pExpr->x.pList->nExpr>0 );
   78347       assert( pExpr->op==TK_FUNCTION );
   78348       pExpr = pExpr->x.pList->a[0].pExpr;
   78349     }else{
   78350       assert( pExpr->op==TK_COLLATE || pExpr->op==TK_AS );
   78351       pExpr = pExpr->pLeft;
   78352     }
   78353   }
   78354   return pExpr;
   78355 }
   78356 
   78357 /*
   78358 ** Return the collation sequence for the expression pExpr. If
   78359 ** there is no defined collating sequence, return NULL.
   78360 **
   78361 ** The collating sequence might be determined by a COLLATE operator
   78362 ** or by the presence of a column with a defined collating sequence.
   78363 ** COLLATE operators take first precedence.  Left operands take
   78364 ** precedence over right operands.
   78365 */
   78366 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
   78367   sqlite3 *db = pParse->db;
   78368   CollSeq *pColl = 0;
   78369   Expr *p = pExpr;
   78370   while( p ){
   78371     int op = p->op;
   78372     if( p->flags & EP_Generic ) break;
   78373     if( op==TK_CAST || op==TK_UPLUS ){
   78374       p = p->pLeft;
   78375       continue;
   78376     }
   78377     if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
   78378       pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
   78379       break;
   78380     }
   78381     if( p->pTab!=0
   78382      && (op==TK_AGG_COLUMN || op==TK_COLUMN
   78383           || op==TK_REGISTER || op==TK_TRIGGER)
   78384     ){
   78385       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
   78386       ** a TK_COLUMN but was previously evaluated and cached in a register */
   78387       int j = p->iColumn;
   78388       if( j>=0 ){
   78389         const char *zColl = p->pTab->aCol[j].zColl;
   78390         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
   78391       }
   78392       break;
   78393     }
   78394     if( p->flags & EP_Collate ){
   78395       if( ALWAYS(p->pLeft) && (p->pLeft->flags & EP_Collate)!=0 ){
   78396         p = p->pLeft;
   78397       }else{
   78398         p = p->pRight;
   78399       }
   78400     }else{
   78401       break;
   78402     }
   78403   }
   78404   if( sqlite3CheckCollSeq(pParse, pColl) ){
   78405     pColl = 0;
   78406   }
   78407   return pColl;
   78408 }
   78409 
   78410 /*
   78411 ** pExpr is an operand of a comparison operator.  aff2 is the
   78412 ** type affinity of the other operand.  This routine returns the
   78413 ** type affinity that should be used for the comparison operator.
   78414 */
   78415 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
   78416   char aff1 = sqlite3ExprAffinity(pExpr);
   78417   if( aff1 && aff2 ){
   78418     /* Both sides of the comparison are columns. If one has numeric
   78419     ** affinity, use that. Otherwise use no affinity.
   78420     */
   78421     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
   78422       return SQLITE_AFF_NUMERIC;
   78423     }else{
   78424       return SQLITE_AFF_NONE;
   78425     }
   78426   }else if( !aff1 && !aff2 ){
   78427     /* Neither side of the comparison is a column.  Compare the
   78428     ** results directly.
   78429     */
   78430     return SQLITE_AFF_NONE;
   78431   }else{
   78432     /* One side is a column, the other is not. Use the columns affinity. */
   78433     assert( aff1==0 || aff2==0 );
   78434     return (aff1 + aff2);
   78435   }
   78436 }
   78437 
   78438 /*
   78439 ** pExpr is a comparison operator.  Return the type affinity that should
   78440 ** be applied to both operands prior to doing the comparison.
   78441 */
   78442 static char comparisonAffinity(Expr *pExpr){
   78443   char aff;
   78444   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
   78445           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
   78446           pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
   78447   assert( pExpr->pLeft );
   78448   aff = sqlite3ExprAffinity(pExpr->pLeft);
   78449   if( pExpr->pRight ){
   78450     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
   78451   }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   78452     aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
   78453   }else if( !aff ){
   78454     aff = SQLITE_AFF_NONE;
   78455   }
   78456   return aff;
   78457 }
   78458 
   78459 /*
   78460 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
   78461 ** idx_affinity is the affinity of an indexed column. Return true
   78462 ** if the index with affinity idx_affinity may be used to implement
   78463 ** the comparison in pExpr.
   78464 */
   78465 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
   78466   char aff = comparisonAffinity(pExpr);
   78467   switch( aff ){
   78468     case SQLITE_AFF_NONE:
   78469       return 1;
   78470     case SQLITE_AFF_TEXT:
   78471       return idx_affinity==SQLITE_AFF_TEXT;
   78472     default:
   78473       return sqlite3IsNumericAffinity(idx_affinity);
   78474   }
   78475 }
   78476 
   78477 /*
   78478 ** Return the P5 value that should be used for a binary comparison
   78479 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
   78480 */
   78481 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
   78482   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
   78483   aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
   78484   return aff;
   78485 }
   78486 
   78487 /*
   78488 ** Return a pointer to the collation sequence that should be used by
   78489 ** a binary comparison operator comparing pLeft and pRight.
   78490 **
   78491 ** If the left hand expression has a collating sequence type, then it is
   78492 ** used. Otherwise the collation sequence for the right hand expression
   78493 ** is used, or the default (BINARY) if neither expression has a collating
   78494 ** type.
   78495 **
   78496 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
   78497 ** it is not considered.
   78498 */
   78499 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
   78500   Parse *pParse,
   78501   Expr *pLeft,
   78502   Expr *pRight
   78503 ){
   78504   CollSeq *pColl;
   78505   assert( pLeft );
   78506   if( pLeft->flags & EP_Collate ){
   78507     pColl = sqlite3ExprCollSeq(pParse, pLeft);
   78508   }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
   78509     pColl = sqlite3ExprCollSeq(pParse, pRight);
   78510   }else{
   78511     pColl = sqlite3ExprCollSeq(pParse, pLeft);
   78512     if( !pColl ){
   78513       pColl = sqlite3ExprCollSeq(pParse, pRight);
   78514     }
   78515   }
   78516   return pColl;
   78517 }
   78518 
   78519 /*
   78520 ** Generate code for a comparison operator.
   78521 */
   78522 static int codeCompare(
   78523   Parse *pParse,    /* The parsing (and code generating) context */
   78524   Expr *pLeft,      /* The left operand */
   78525   Expr *pRight,     /* The right operand */
   78526   int opcode,       /* The comparison opcode */
   78527   int in1, int in2, /* Register holding operands */
   78528   int dest,         /* Jump here if true.  */
   78529   int jumpIfNull    /* If true, jump if either operand is NULL */
   78530 ){
   78531   int p5;
   78532   int addr;
   78533   CollSeq *p4;
   78534 
   78535   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
   78536   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
   78537   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
   78538                            (void*)p4, P4_COLLSEQ);
   78539   sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
   78540   return addr;
   78541 }
   78542 
   78543 #if SQLITE_MAX_EXPR_DEPTH>0
   78544 /*
   78545 ** Check that argument nHeight is less than or equal to the maximum
   78546 ** expression depth allowed. If it is not, leave an error message in
   78547 ** pParse.
   78548 */
   78549 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
   78550   int rc = SQLITE_OK;
   78551   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
   78552   if( nHeight>mxHeight ){
   78553     sqlite3ErrorMsg(pParse,
   78554        "Expression tree is too large (maximum depth %d)", mxHeight
   78555     );
   78556     rc = SQLITE_ERROR;
   78557   }
   78558   return rc;
   78559 }
   78560 
   78561 /* The following three functions, heightOfExpr(), heightOfExprList()
   78562 ** and heightOfSelect(), are used to determine the maximum height
   78563 ** of any expression tree referenced by the structure passed as the
   78564 ** first argument.
   78565 **
   78566 ** If this maximum height is greater than the current value pointed
   78567 ** to by pnHeight, the second parameter, then set *pnHeight to that
   78568 ** value.
   78569 */
   78570 static void heightOfExpr(Expr *p, int *pnHeight){
   78571   if( p ){
   78572     if( p->nHeight>*pnHeight ){
   78573       *pnHeight = p->nHeight;
   78574     }
   78575   }
   78576 }
   78577 static void heightOfExprList(ExprList *p, int *pnHeight){
   78578   if( p ){
   78579     int i;
   78580     for(i=0; i<p->nExpr; i++){
   78581       heightOfExpr(p->a[i].pExpr, pnHeight);
   78582     }
   78583   }
   78584 }
   78585 static void heightOfSelect(Select *p, int *pnHeight){
   78586   if( p ){
   78587     heightOfExpr(p->pWhere, pnHeight);
   78588     heightOfExpr(p->pHaving, pnHeight);
   78589     heightOfExpr(p->pLimit, pnHeight);
   78590     heightOfExpr(p->pOffset, pnHeight);
   78591     heightOfExprList(p->pEList, pnHeight);
   78592     heightOfExprList(p->pGroupBy, pnHeight);
   78593     heightOfExprList(p->pOrderBy, pnHeight);
   78594     heightOfSelect(p->pPrior, pnHeight);
   78595   }
   78596 }
   78597 
   78598 /*
   78599 ** Set the Expr.nHeight variable in the structure passed as an
   78600 ** argument. An expression with no children, Expr.pList or
   78601 ** Expr.pSelect member has a height of 1. Any other expression
   78602 ** has a height equal to the maximum height of any other
   78603 ** referenced Expr plus one.
   78604 */
   78605 static void exprSetHeight(Expr *p){
   78606   int nHeight = 0;
   78607   heightOfExpr(p->pLeft, &nHeight);
   78608   heightOfExpr(p->pRight, &nHeight);
   78609   if( ExprHasProperty(p, EP_xIsSelect) ){
   78610     heightOfSelect(p->x.pSelect, &nHeight);
   78611   }else{
   78612     heightOfExprList(p->x.pList, &nHeight);
   78613   }
   78614   p->nHeight = nHeight + 1;
   78615 }
   78616 
   78617 /*
   78618 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
   78619 ** the height is greater than the maximum allowed expression depth,
   78620 ** leave an error in pParse.
   78621 */
   78622 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
   78623   exprSetHeight(p);
   78624   sqlite3ExprCheckHeight(pParse, p->nHeight);
   78625 }
   78626 
   78627 /*
   78628 ** Return the maximum height of any expression tree referenced
   78629 ** by the select statement passed as an argument.
   78630 */
   78631 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
   78632   int nHeight = 0;
   78633   heightOfSelect(p, &nHeight);
   78634   return nHeight;
   78635 }
   78636 #else
   78637   #define exprSetHeight(y)
   78638 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
   78639 
   78640 /*
   78641 ** This routine is the core allocator for Expr nodes.
   78642 **
   78643 ** Construct a new expression node and return a pointer to it.  Memory
   78644 ** for this node and for the pToken argument is a single allocation
   78645 ** obtained from sqlite3DbMalloc().  The calling function
   78646 ** is responsible for making sure the node eventually gets freed.
   78647 **
   78648 ** If dequote is true, then the token (if it exists) is dequoted.
   78649 ** If dequote is false, no dequoting is performance.  The deQuote
   78650 ** parameter is ignored if pToken is NULL or if the token does not
   78651 ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
   78652 ** then the EP_DblQuoted flag is set on the expression node.
   78653 **
   78654 ** Special case:  If op==TK_INTEGER and pToken points to a string that
   78655 ** can be translated into a 32-bit integer, then the token is not
   78656 ** stored in u.zToken.  Instead, the integer values is written
   78657 ** into u.iValue and the EP_IntValue flag is set.  No extra storage
   78658 ** is allocated to hold the integer text and the dequote flag is ignored.
   78659 */
   78660 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
   78661   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
   78662   int op,                 /* Expression opcode */
   78663   const Token *pToken,    /* Token argument.  Might be NULL */
   78664   int dequote             /* True to dequote */
   78665 ){
   78666   Expr *pNew;
   78667   int nExtra = 0;
   78668   int iValue = 0;
   78669 
   78670   if( pToken ){
   78671     if( op!=TK_INTEGER || pToken->z==0
   78672           || sqlite3GetInt32(pToken->z, &iValue)==0 ){
   78673       nExtra = pToken->n+1;
   78674       assert( iValue>=0 );
   78675     }
   78676   }
   78677   pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
   78678   if( pNew ){
   78679     pNew->op = (u8)op;
   78680     pNew->iAgg = -1;
   78681     if( pToken ){
   78682       if( nExtra==0 ){
   78683         pNew->flags |= EP_IntValue;
   78684         pNew->u.iValue = iValue;
   78685       }else{
   78686         int c;
   78687         pNew->u.zToken = (char*)&pNew[1];
   78688         assert( pToken->z!=0 || pToken->n==0 );
   78689         if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
   78690         pNew->u.zToken[pToken->n] = 0;
   78691         if( dequote && nExtra>=3
   78692              && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
   78693           sqlite3Dequote(pNew->u.zToken);
   78694           if( c=='"' ) pNew->flags |= EP_DblQuoted;
   78695         }
   78696       }
   78697     }
   78698 #if SQLITE_MAX_EXPR_DEPTH>0
   78699     pNew->nHeight = 1;
   78700 #endif
   78701   }
   78702   return pNew;
   78703 }
   78704 
   78705 /*
   78706 ** Allocate a new expression node from a zero-terminated token that has
   78707 ** already been dequoted.
   78708 */
   78709 SQLITE_PRIVATE Expr *sqlite3Expr(
   78710   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
   78711   int op,                 /* Expression opcode */
   78712   const char *zToken      /* Token argument.  Might be NULL */
   78713 ){
   78714   Token x;
   78715   x.z = zToken;
   78716   x.n = zToken ? sqlite3Strlen30(zToken) : 0;
   78717   return sqlite3ExprAlloc(db, op, &x, 0);
   78718 }
   78719 
   78720 /*
   78721 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
   78722 **
   78723 ** If pRoot==NULL that means that a memory allocation error has occurred.
   78724 ** In that case, delete the subtrees pLeft and pRight.
   78725 */
   78726 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
   78727   sqlite3 *db,
   78728   Expr *pRoot,
   78729   Expr *pLeft,
   78730   Expr *pRight
   78731 ){
   78732   if( pRoot==0 ){
   78733     assert( db->mallocFailed );
   78734     sqlite3ExprDelete(db, pLeft);
   78735     sqlite3ExprDelete(db, pRight);
   78736   }else{
   78737     if( pRight ){
   78738       pRoot->pRight = pRight;
   78739       pRoot->flags |= EP_Collate & pRight->flags;
   78740     }
   78741     if( pLeft ){
   78742       pRoot->pLeft = pLeft;
   78743       pRoot->flags |= EP_Collate & pLeft->flags;
   78744     }
   78745     exprSetHeight(pRoot);
   78746   }
   78747 }
   78748 
   78749 /*
   78750 ** Allocate a Expr node which joins as many as two subtrees.
   78751 **
   78752 ** One or both of the subtrees can be NULL.  Return a pointer to the new
   78753 ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
   78754 ** free the subtrees and return NULL.
   78755 */
   78756 SQLITE_PRIVATE Expr *sqlite3PExpr(
   78757   Parse *pParse,          /* Parsing context */
   78758   int op,                 /* Expression opcode */
   78759   Expr *pLeft,            /* Left operand */
   78760   Expr *pRight,           /* Right operand */
   78761   const Token *pToken     /* Argument token */
   78762 ){
   78763   Expr *p;
   78764   if( op==TK_AND && pLeft && pRight ){
   78765     /* Take advantage of short-circuit false optimization for AND */
   78766     p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
   78767   }else{
   78768     p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
   78769     sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
   78770   }
   78771   if( p ) {
   78772     sqlite3ExprCheckHeight(pParse, p->nHeight);
   78773   }
   78774   return p;
   78775 }
   78776 
   78777 /*
   78778 ** If the expression is always either TRUE or FALSE (respectively),
   78779 ** then return 1.  If one cannot determine the truth value of the
   78780 ** expression at compile-time return 0.
   78781 **
   78782 ** This is an optimization.  If is OK to return 0 here even if
   78783 ** the expression really is always false or false (a false negative).
   78784 ** But it is a bug to return 1 if the expression might have different
   78785 ** boolean values in different circumstances (a false positive.)
   78786 **
   78787 ** Note that if the expression is part of conditional for a
   78788 ** LEFT JOIN, then we cannot determine at compile-time whether or not
   78789 ** is it true or false, so always return 0.
   78790 */
   78791 static int exprAlwaysTrue(Expr *p){
   78792   int v = 0;
   78793   if( ExprHasProperty(p, EP_FromJoin) ) return 0;
   78794   if( !sqlite3ExprIsInteger(p, &v) ) return 0;
   78795   return v!=0;
   78796 }
   78797 static int exprAlwaysFalse(Expr *p){
   78798   int v = 0;
   78799   if( ExprHasProperty(p, EP_FromJoin) ) return 0;
   78800   if( !sqlite3ExprIsInteger(p, &v) ) return 0;
   78801   return v==0;
   78802 }
   78803 
   78804 /*
   78805 ** Join two expressions using an AND operator.  If either expression is
   78806 ** NULL, then just return the other expression.
   78807 **
   78808 ** If one side or the other of the AND is known to be false, then instead
   78809 ** of returning an AND expression, just return a constant expression with
   78810 ** a value of false.
   78811 */
   78812 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
   78813   if( pLeft==0 ){
   78814     return pRight;
   78815   }else if( pRight==0 ){
   78816     return pLeft;
   78817   }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
   78818     sqlite3ExprDelete(db, pLeft);
   78819     sqlite3ExprDelete(db, pRight);
   78820     return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
   78821   }else{
   78822     Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
   78823     sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
   78824     return pNew;
   78825   }
   78826 }
   78827 
   78828 /*
   78829 ** Construct a new expression node for a function with multiple
   78830 ** arguments.
   78831 */
   78832 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
   78833   Expr *pNew;
   78834   sqlite3 *db = pParse->db;
   78835   assert( pToken );
   78836   pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
   78837   if( pNew==0 ){
   78838     sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
   78839     return 0;
   78840   }
   78841   pNew->x.pList = pList;
   78842   assert( !ExprHasProperty(pNew, EP_xIsSelect) );
   78843   sqlite3ExprSetHeight(pParse, pNew);
   78844   return pNew;
   78845 }
   78846 
   78847 /*
   78848 ** Assign a variable number to an expression that encodes a wildcard
   78849 ** in the original SQL statement.
   78850 **
   78851 ** Wildcards consisting of a single "?" are assigned the next sequential
   78852 ** variable number.
   78853 **
   78854 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
   78855 ** sure "nnn" is not too be to avoid a denial of service attack when
   78856 ** the SQL statement comes from an external source.
   78857 **
   78858 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
   78859 ** as the previous instance of the same wildcard.  Or if this is the first
   78860 ** instance of the wildcard, the next sequenial variable number is
   78861 ** assigned.
   78862 */
   78863 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
   78864   sqlite3 *db = pParse->db;
   78865   const char *z;
   78866 
   78867   if( pExpr==0 ) return;
   78868   assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
   78869   z = pExpr->u.zToken;
   78870   assert( z!=0 );
   78871   assert( z[0]!=0 );
   78872   if( z[1]==0 ){
   78873     /* Wildcard of the form "?".  Assign the next variable number */
   78874     assert( z[0]=='?' );
   78875     pExpr->iColumn = (ynVar)(++pParse->nVar);
   78876   }else{
   78877     ynVar x = 0;
   78878     u32 n = sqlite3Strlen30(z);
   78879     if( z[0]=='?' ){
   78880       /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
   78881       ** use it as the variable number */
   78882       i64 i;
   78883       int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
   78884       pExpr->iColumn = x = (ynVar)i;
   78885       testcase( i==0 );
   78886       testcase( i==1 );
   78887       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
   78888       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
   78889       if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
   78890         sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
   78891             db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
   78892         x = 0;
   78893       }
   78894       if( i>pParse->nVar ){
   78895         pParse->nVar = (int)i;
   78896       }
   78897     }else{
   78898       /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
   78899       ** number as the prior appearance of the same name, or if the name
   78900       ** has never appeared before, reuse the same variable number
   78901       */
   78902       ynVar i;
   78903       for(i=0; i<pParse->nzVar; i++){
   78904         if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
   78905           pExpr->iColumn = x = (ynVar)i+1;
   78906           break;
   78907         }
   78908       }
   78909       if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
   78910     }
   78911     if( x>0 ){
   78912       if( x>pParse->nzVar ){
   78913         char **a;
   78914         a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
   78915         if( a==0 ) return;  /* Error reported through db->mallocFailed */
   78916         pParse->azVar = a;
   78917         memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
   78918         pParse->nzVar = x;
   78919       }
   78920       if( z[0]!='?' || pParse->azVar[x-1]==0 ){
   78921         sqlite3DbFree(db, pParse->azVar[x-1]);
   78922         pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
   78923       }
   78924     }
   78925   }
   78926   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
   78927     sqlite3ErrorMsg(pParse, "too many SQL variables");
   78928   }
   78929 }
   78930 
   78931 /*
   78932 ** Recursively delete an expression tree.
   78933 */
   78934 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
   78935   if( p==0 ) return;
   78936   /* Sanity check: Assert that the IntValue is non-negative if it exists */
   78937   assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
   78938   if( !ExprHasProperty(p, EP_TokenOnly) ){
   78939     /* The Expr.x union is never used at the same time as Expr.pRight */
   78940     assert( p->x.pList==0 || p->pRight==0 );
   78941     sqlite3ExprDelete(db, p->pLeft);
   78942     sqlite3ExprDelete(db, p->pRight);
   78943     if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
   78944     if( ExprHasProperty(p, EP_xIsSelect) ){
   78945       sqlite3SelectDelete(db, p->x.pSelect);
   78946     }else{
   78947       sqlite3ExprListDelete(db, p->x.pList);
   78948     }
   78949   }
   78950   if( !ExprHasProperty(p, EP_Static) ){
   78951     sqlite3DbFree(db, p);
   78952   }
   78953 }
   78954 
   78955 /*
   78956 ** Return the number of bytes allocated for the expression structure
   78957 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
   78958 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
   78959 */
   78960 static int exprStructSize(Expr *p){
   78961   if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
   78962   if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
   78963   return EXPR_FULLSIZE;
   78964 }
   78965 
   78966 /*
   78967 ** The dupedExpr*Size() routines each return the number of bytes required
   78968 ** to store a copy of an expression or expression tree.  They differ in
   78969 ** how much of the tree is measured.
   78970 **
   78971 **     dupedExprStructSize()     Size of only the Expr structure
   78972 **     dupedExprNodeSize()       Size of Expr + space for token
   78973 **     dupedExprSize()           Expr + token + subtree components
   78974 **
   78975 ***************************************************************************
   78976 **
   78977 ** The dupedExprStructSize() function returns two values OR-ed together:
   78978 ** (1) the space required for a copy of the Expr structure only and
   78979 ** (2) the EP_xxx flags that indicate what the structure size should be.
   78980 ** The return values is always one of:
   78981 **
   78982 **      EXPR_FULLSIZE
   78983 **      EXPR_REDUCEDSIZE   | EP_Reduced
   78984 **      EXPR_TOKENONLYSIZE | EP_TokenOnly
   78985 **
   78986 ** The size of the structure can be found by masking the return value
   78987 ** of this routine with 0xfff.  The flags can be found by masking the
   78988 ** return value with EP_Reduced|EP_TokenOnly.
   78989 **
   78990 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
   78991 ** (unreduced) Expr objects as they or originally constructed by the parser.
   78992 ** During expression analysis, extra information is computed and moved into
   78993 ** later parts of teh Expr object and that extra information might get chopped
   78994 ** off if the expression is reduced.  Note also that it does not work to
   78995 ** make a EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
   78996 ** to reduce a pristine expression tree from the parser.  The implementation
   78997 ** of dupedExprStructSize() contain multiple assert() statements that attempt
   78998 ** to enforce this constraint.
   78999 */
   79000 static int dupedExprStructSize(Expr *p, int flags){
   79001   int nSize;
   79002   assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
   79003   assert( EXPR_FULLSIZE<=0xfff );
   79004   assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
   79005   if( 0==(flags&EXPRDUP_REDUCE) ){
   79006     nSize = EXPR_FULLSIZE;
   79007   }else{
   79008     assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
   79009     assert( !ExprHasProperty(p, EP_FromJoin) );
   79010     assert( !ExprHasProperty(p, EP_MemToken) );
   79011     assert( !ExprHasProperty(p, EP_NoReduce) );
   79012     if( p->pLeft || p->x.pList ){
   79013       nSize = EXPR_REDUCEDSIZE | EP_Reduced;
   79014     }else{
   79015       assert( p->pRight==0 );
   79016       nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
   79017     }
   79018   }
   79019   return nSize;
   79020 }
   79021 
   79022 /*
   79023 ** This function returns the space in bytes required to store the copy
   79024 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
   79025 ** string is defined.)
   79026 */
   79027 static int dupedExprNodeSize(Expr *p, int flags){
   79028   int nByte = dupedExprStructSize(p, flags) & 0xfff;
   79029   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
   79030     nByte += sqlite3Strlen30(p->u.zToken)+1;
   79031   }
   79032   return ROUND8(nByte);
   79033 }
   79034 
   79035 /*
   79036 ** Return the number of bytes required to create a duplicate of the
   79037 ** expression passed as the first argument. The second argument is a
   79038 ** mask containing EXPRDUP_XXX flags.
   79039 **
   79040 ** The value returned includes space to create a copy of the Expr struct
   79041 ** itself and the buffer referred to by Expr.u.zToken, if any.
   79042 **
   79043 ** If the EXPRDUP_REDUCE flag is set, then the return value includes
   79044 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
   79045 ** and Expr.pRight variables (but not for any structures pointed to or
   79046 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
   79047 */
   79048 static int dupedExprSize(Expr *p, int flags){
   79049   int nByte = 0;
   79050   if( p ){
   79051     nByte = dupedExprNodeSize(p, flags);
   79052     if( flags&EXPRDUP_REDUCE ){
   79053       nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
   79054     }
   79055   }
   79056   return nByte;
   79057 }
   79058 
   79059 /*
   79060 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
   79061 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
   79062 ** to store the copy of expression p, the copies of p->u.zToken
   79063 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
   79064 ** if any. Before returning, *pzBuffer is set to the first byte passed the
   79065 ** portion of the buffer copied into by this function.
   79066 */
   79067 static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
   79068   Expr *pNew = 0;                      /* Value to return */
   79069   if( p ){
   79070     const int isReduced = (flags&EXPRDUP_REDUCE);
   79071     u8 *zAlloc;
   79072     u32 staticFlag = 0;
   79073 
   79074     assert( pzBuffer==0 || isReduced );
   79075 
   79076     /* Figure out where to write the new Expr structure. */
   79077     if( pzBuffer ){
   79078       zAlloc = *pzBuffer;
   79079       staticFlag = EP_Static;
   79080     }else{
   79081       zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
   79082     }
   79083     pNew = (Expr *)zAlloc;
   79084 
   79085     if( pNew ){
   79086       /* Set nNewSize to the size allocated for the structure pointed to
   79087       ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
   79088       ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
   79089       ** by the copy of the p->u.zToken string (if any).
   79090       */
   79091       const unsigned nStructSize = dupedExprStructSize(p, flags);
   79092       const int nNewSize = nStructSize & 0xfff;
   79093       int nToken;
   79094       if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
   79095         nToken = sqlite3Strlen30(p->u.zToken) + 1;
   79096       }else{
   79097         nToken = 0;
   79098       }
   79099       if( isReduced ){
   79100         assert( ExprHasProperty(p, EP_Reduced)==0 );
   79101         memcpy(zAlloc, p, nNewSize);
   79102       }else{
   79103         int nSize = exprStructSize(p);
   79104         memcpy(zAlloc, p, nSize);
   79105         memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
   79106       }
   79107 
   79108       /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
   79109       pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
   79110       pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
   79111       pNew->flags |= staticFlag;
   79112 
   79113       /* Copy the p->u.zToken string, if any. */
   79114       if( nToken ){
   79115         char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
   79116         memcpy(zToken, p->u.zToken, nToken);
   79117       }
   79118 
   79119       if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
   79120         /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
   79121         if( ExprHasProperty(p, EP_xIsSelect) ){
   79122           pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
   79123         }else{
   79124           pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
   79125         }
   79126       }
   79127 
   79128       /* Fill in pNew->pLeft and pNew->pRight. */
   79129       if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
   79130         zAlloc += dupedExprNodeSize(p, flags);
   79131         if( ExprHasProperty(pNew, EP_Reduced) ){
   79132           pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
   79133           pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
   79134         }
   79135         if( pzBuffer ){
   79136           *pzBuffer = zAlloc;
   79137         }
   79138       }else{
   79139         if( !ExprHasProperty(p, EP_TokenOnly) ){
   79140           pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
   79141           pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
   79142         }
   79143       }
   79144 
   79145     }
   79146   }
   79147   return pNew;
   79148 }
   79149 
   79150 /*
   79151 ** Create and return a deep copy of the object passed as the second
   79152 ** argument. If an OOM condition is encountered, NULL is returned
   79153 ** and the db->mallocFailed flag set.
   79154 */
   79155 #ifndef SQLITE_OMIT_CTE
   79156 static With *withDup(sqlite3 *db, With *p){
   79157   With *pRet = 0;
   79158   if( p ){
   79159     int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
   79160     pRet = sqlite3DbMallocZero(db, nByte);
   79161     if( pRet ){
   79162       int i;
   79163       pRet->nCte = p->nCte;
   79164       for(i=0; i<p->nCte; i++){
   79165         pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
   79166         pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
   79167         pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
   79168       }
   79169     }
   79170   }
   79171   return pRet;
   79172 }
   79173 #else
   79174 # define withDup(x,y) 0
   79175 #endif
   79176 
   79177 /*
   79178 ** The following group of routines make deep copies of expressions,
   79179 ** expression lists, ID lists, and select statements.  The copies can
   79180 ** be deleted (by being passed to their respective ...Delete() routines)
   79181 ** without effecting the originals.
   79182 **
   79183 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
   79184 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
   79185 ** by subsequent calls to sqlite*ListAppend() routines.
   79186 **
   79187 ** Any tables that the SrcList might point to are not duplicated.
   79188 **
   79189 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
   79190 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
   79191 ** truncated version of the usual Expr structure that will be stored as
   79192 ** part of the in-memory representation of the database schema.
   79193 */
   79194 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
   79195   return exprDup(db, p, flags, 0);
   79196 }
   79197 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
   79198   ExprList *pNew;
   79199   struct ExprList_item *pItem, *pOldItem;
   79200   int i;
   79201   if( p==0 ) return 0;
   79202   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
   79203   if( pNew==0 ) return 0;
   79204   pNew->nExpr = i = p->nExpr;
   79205   if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
   79206   pNew->a = pItem = sqlite3DbMallocRaw(db,  i*sizeof(p->a[0]) );
   79207   if( pItem==0 ){
   79208     sqlite3DbFree(db, pNew);
   79209     return 0;
   79210   }
   79211   pOldItem = p->a;
   79212   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
   79213     Expr *pOldExpr = pOldItem->pExpr;
   79214     pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
   79215     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
   79216     pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
   79217     pItem->sortOrder = pOldItem->sortOrder;
   79218     pItem->done = 0;
   79219     pItem->bSpanIsTab = pOldItem->bSpanIsTab;
   79220     pItem->u = pOldItem->u;
   79221   }
   79222   return pNew;
   79223 }
   79224 
   79225 /*
   79226 ** If cursors, triggers, views and subqueries are all omitted from
   79227 ** the build, then none of the following routines, except for
   79228 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
   79229 ** called with a NULL argument.
   79230 */
   79231 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
   79232  || !defined(SQLITE_OMIT_SUBQUERY)
   79233 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
   79234   SrcList *pNew;
   79235   int i;
   79236   int nByte;
   79237   if( p==0 ) return 0;
   79238   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
   79239   pNew = sqlite3DbMallocRaw(db, nByte );
   79240   if( pNew==0 ) return 0;
   79241   pNew->nSrc = pNew->nAlloc = p->nSrc;
   79242   for(i=0; i<p->nSrc; i++){
   79243     struct SrcList_item *pNewItem = &pNew->a[i];
   79244     struct SrcList_item *pOldItem = &p->a[i];
   79245     Table *pTab;
   79246     pNewItem->pSchema = pOldItem->pSchema;
   79247     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
   79248     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
   79249     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
   79250     pNewItem->jointype = pOldItem->jointype;
   79251     pNewItem->iCursor = pOldItem->iCursor;
   79252     pNewItem->addrFillSub = pOldItem->addrFillSub;
   79253     pNewItem->regReturn = pOldItem->regReturn;
   79254     pNewItem->isCorrelated = pOldItem->isCorrelated;
   79255     pNewItem->viaCoroutine = pOldItem->viaCoroutine;
   79256     pNewItem->isRecursive = pOldItem->isRecursive;
   79257     pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
   79258     pNewItem->notIndexed = pOldItem->notIndexed;
   79259     pNewItem->pIndex = pOldItem->pIndex;
   79260     pTab = pNewItem->pTab = pOldItem->pTab;
   79261     if( pTab ){
   79262       pTab->nRef++;
   79263     }
   79264     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
   79265     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
   79266     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
   79267     pNewItem->colUsed = pOldItem->colUsed;
   79268   }
   79269   return pNew;
   79270 }
   79271 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
   79272   IdList *pNew;
   79273   int i;
   79274   if( p==0 ) return 0;
   79275   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
   79276   if( pNew==0 ) return 0;
   79277   pNew->nId = p->nId;
   79278   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
   79279   if( pNew->a==0 ){
   79280     sqlite3DbFree(db, pNew);
   79281     return 0;
   79282   }
   79283   /* Note that because the size of the allocation for p->a[] is not
   79284   ** necessarily a power of two, sqlite3IdListAppend() may not be called
   79285   ** on the duplicate created by this function. */
   79286   for(i=0; i<p->nId; i++){
   79287     struct IdList_item *pNewItem = &pNew->a[i];
   79288     struct IdList_item *pOldItem = &p->a[i];
   79289     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
   79290     pNewItem->idx = pOldItem->idx;
   79291   }
   79292   return pNew;
   79293 }
   79294 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
   79295   Select *pNew, *pPrior;
   79296   if( p==0 ) return 0;
   79297   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
   79298   if( pNew==0 ) return 0;
   79299   pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
   79300   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
   79301   pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
   79302   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
   79303   pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
   79304   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
   79305   pNew->op = p->op;
   79306   pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
   79307   if( pPrior ) pPrior->pNext = pNew;
   79308   pNew->pNext = 0;
   79309   pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
   79310   pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
   79311   pNew->iLimit = 0;
   79312   pNew->iOffset = 0;
   79313   pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
   79314   pNew->addrOpenEphm[0] = -1;
   79315   pNew->addrOpenEphm[1] = -1;
   79316   pNew->nSelectRow = p->nSelectRow;
   79317   pNew->pWith = withDup(db, p->pWith);
   79318   return pNew;
   79319 }
   79320 #else
   79321 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
   79322   assert( p==0 );
   79323   return 0;
   79324 }
   79325 #endif
   79326 
   79327 
   79328 /*
   79329 ** Add a new element to the end of an expression list.  If pList is
   79330 ** initially NULL, then create a new expression list.
   79331 **
   79332 ** If a memory allocation error occurs, the entire list is freed and
   79333 ** NULL is returned.  If non-NULL is returned, then it is guaranteed
   79334 ** that the new entry was successfully appended.
   79335 */
   79336 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
   79337   Parse *pParse,          /* Parsing context */
   79338   ExprList *pList,        /* List to which to append. Might be NULL */
   79339   Expr *pExpr             /* Expression to be appended. Might be NULL */
   79340 ){
   79341   sqlite3 *db = pParse->db;
   79342   if( pList==0 ){
   79343     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
   79344     if( pList==0 ){
   79345       goto no_mem;
   79346     }
   79347     pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));
   79348     if( pList->a==0 ) goto no_mem;
   79349   }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
   79350     struct ExprList_item *a;
   79351     assert( pList->nExpr>0 );
   79352     a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
   79353     if( a==0 ){
   79354       goto no_mem;
   79355     }
   79356     pList->a = a;
   79357   }
   79358   assert( pList->a!=0 );
   79359   if( 1 ){
   79360     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
   79361     memset(pItem, 0, sizeof(*pItem));
   79362     pItem->pExpr = pExpr;
   79363   }
   79364   return pList;
   79365 
   79366 no_mem:
   79367   /* Avoid leaking memory if malloc has failed. */
   79368   sqlite3ExprDelete(db, pExpr);
   79369   sqlite3ExprListDelete(db, pList);
   79370   return 0;
   79371 }
   79372 
   79373 /*
   79374 ** Set the ExprList.a[].zName element of the most recently added item
   79375 ** on the expression list.
   79376 **
   79377 ** pList might be NULL following an OOM error.  But pName should never be
   79378 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
   79379 ** is set.
   79380 */
   79381 SQLITE_PRIVATE void sqlite3ExprListSetName(
   79382   Parse *pParse,          /* Parsing context */
   79383   ExprList *pList,        /* List to which to add the span. */
   79384   Token *pName,           /* Name to be added */
   79385   int dequote             /* True to cause the name to be dequoted */
   79386 ){
   79387   assert( pList!=0 || pParse->db->mallocFailed!=0 );
   79388   if( pList ){
   79389     struct ExprList_item *pItem;
   79390     assert( pList->nExpr>0 );
   79391     pItem = &pList->a[pList->nExpr-1];
   79392     assert( pItem->zName==0 );
   79393     pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
   79394     if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
   79395   }
   79396 }
   79397 
   79398 /*
   79399 ** Set the ExprList.a[].zSpan element of the most recently added item
   79400 ** on the expression list.
   79401 **
   79402 ** pList might be NULL following an OOM error.  But pSpan should never be
   79403 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
   79404 ** is set.
   79405 */
   79406 SQLITE_PRIVATE void sqlite3ExprListSetSpan(
   79407   Parse *pParse,          /* Parsing context */
   79408   ExprList *pList,        /* List to which to add the span. */
   79409   ExprSpan *pSpan         /* The span to be added */
   79410 ){
   79411   sqlite3 *db = pParse->db;
   79412   assert( pList!=0 || db->mallocFailed!=0 );
   79413   if( pList ){
   79414     struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
   79415     assert( pList->nExpr>0 );
   79416     assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
   79417     sqlite3DbFree(db, pItem->zSpan);
   79418     pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
   79419                                     (int)(pSpan->zEnd - pSpan->zStart));
   79420   }
   79421 }
   79422 
   79423 /*
   79424 ** If the expression list pEList contains more than iLimit elements,
   79425 ** leave an error message in pParse.
   79426 */
   79427 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
   79428   Parse *pParse,
   79429   ExprList *pEList,
   79430   const char *zObject
   79431 ){
   79432   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
   79433   testcase( pEList && pEList->nExpr==mx );
   79434   testcase( pEList && pEList->nExpr==mx+1 );
   79435   if( pEList && pEList->nExpr>mx ){
   79436     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
   79437   }
   79438 }
   79439 
   79440 /*
   79441 ** Delete an entire expression list.
   79442 */
   79443 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
   79444   int i;
   79445   struct ExprList_item *pItem;
   79446   if( pList==0 ) return;
   79447   assert( pList->a!=0 || pList->nExpr==0 );
   79448   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
   79449     sqlite3ExprDelete(db, pItem->pExpr);
   79450     sqlite3DbFree(db, pItem->zName);
   79451     sqlite3DbFree(db, pItem->zSpan);
   79452   }
   79453   sqlite3DbFree(db, pList->a);
   79454   sqlite3DbFree(db, pList);
   79455 }
   79456 
   79457 /*
   79458 ** These routines are Walker callbacks.  Walker.u.pi is a pointer
   79459 ** to an integer.  These routines are checking an expression to see
   79460 ** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
   79461 ** not constant.
   79462 **
   79463 ** These callback routines are used to implement the following:
   79464 **
   79465 **     sqlite3ExprIsConstant()
   79466 **     sqlite3ExprIsConstantNotJoin()
   79467 **     sqlite3ExprIsConstantOrFunction()
   79468 **
   79469 */
   79470 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
   79471 
   79472   /* If pWalker->u.i is 3 then any term of the expression that comes from
   79473   ** the ON or USING clauses of a join disqualifies the expression
   79474   ** from being considered constant. */
   79475   if( pWalker->u.i==3 && ExprHasProperty(pExpr, EP_FromJoin) ){
   79476     pWalker->u.i = 0;
   79477     return WRC_Abort;
   79478   }
   79479 
   79480   switch( pExpr->op ){
   79481     /* Consider functions to be constant if all their arguments are constant
   79482     ** and either pWalker->u.i==2 or the function as the SQLITE_FUNC_CONST
   79483     ** flag. */
   79484     case TK_FUNCTION:
   79485       if( pWalker->u.i==2 || ExprHasProperty(pExpr,EP_Constant) ){
   79486         return WRC_Continue;
   79487       }
   79488       /* Fall through */
   79489     case TK_ID:
   79490     case TK_COLUMN:
   79491     case TK_AGG_FUNCTION:
   79492     case TK_AGG_COLUMN:
   79493       testcase( pExpr->op==TK_ID );
   79494       testcase( pExpr->op==TK_COLUMN );
   79495       testcase( pExpr->op==TK_AGG_FUNCTION );
   79496       testcase( pExpr->op==TK_AGG_COLUMN );
   79497       pWalker->u.i = 0;
   79498       return WRC_Abort;
   79499     default:
   79500       testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
   79501       testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
   79502       return WRC_Continue;
   79503   }
   79504 }
   79505 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
   79506   UNUSED_PARAMETER(NotUsed);
   79507   pWalker->u.i = 0;
   79508   return WRC_Abort;
   79509 }
   79510 static int exprIsConst(Expr *p, int initFlag){
   79511   Walker w;
   79512   memset(&w, 0, sizeof(w));
   79513   w.u.i = initFlag;
   79514   w.xExprCallback = exprNodeIsConstant;
   79515   w.xSelectCallback = selectNodeIsConstant;
   79516   sqlite3WalkExpr(&w, p);
   79517   return w.u.i;
   79518 }
   79519 
   79520 /*
   79521 ** Walk an expression tree.  Return 1 if the expression is constant
   79522 ** and 0 if it involves variables or function calls.
   79523 **
   79524 ** For the purposes of this function, a double-quoted string (ex: "abc")
   79525 ** is considered a variable but a single-quoted string (ex: 'abc') is
   79526 ** a constant.
   79527 */
   79528 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
   79529   return exprIsConst(p, 1);
   79530 }
   79531 
   79532 /*
   79533 ** Walk an expression tree.  Return 1 if the expression is constant
   79534 ** that does no originate from the ON or USING clauses of a join.
   79535 ** Return 0 if it involves variables or function calls or terms from
   79536 ** an ON or USING clause.
   79537 */
   79538 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
   79539   return exprIsConst(p, 3);
   79540 }
   79541 
   79542 /*
   79543 ** Walk an expression tree.  Return 1 if the expression is constant
   79544 ** or a function call with constant arguments.  Return and 0 if there
   79545 ** are any variables.
   79546 **
   79547 ** For the purposes of this function, a double-quoted string (ex: "abc")
   79548 ** is considered a variable but a single-quoted string (ex: 'abc') is
   79549 ** a constant.
   79550 */
   79551 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
   79552   return exprIsConst(p, 2);
   79553 }
   79554 
   79555 /*
   79556 ** If the expression p codes a constant integer that is small enough
   79557 ** to fit in a 32-bit integer, return 1 and put the value of the integer
   79558 ** in *pValue.  If the expression is not an integer or if it is too big
   79559 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
   79560 */
   79561 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
   79562   int rc = 0;
   79563 
   79564   /* If an expression is an integer literal that fits in a signed 32-bit
   79565   ** integer, then the EP_IntValue flag will have already been set */
   79566   assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
   79567            || sqlite3GetInt32(p->u.zToken, &rc)==0 );
   79568 
   79569   if( p->flags & EP_IntValue ){
   79570     *pValue = p->u.iValue;
   79571     return 1;
   79572   }
   79573   switch( p->op ){
   79574     case TK_UPLUS: {
   79575       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
   79576       break;
   79577     }
   79578     case TK_UMINUS: {
   79579       int v;
   79580       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
   79581         assert( v!=(-2147483647-1) );
   79582         *pValue = -v;
   79583         rc = 1;
   79584       }
   79585       break;
   79586     }
   79587     default: break;
   79588   }
   79589   return rc;
   79590 }
   79591 
   79592 /*
   79593 ** Return FALSE if there is no chance that the expression can be NULL.
   79594 **
   79595 ** If the expression might be NULL or if the expression is too complex
   79596 ** to tell return TRUE.
   79597 **
   79598 ** This routine is used as an optimization, to skip OP_IsNull opcodes
   79599 ** when we know that a value cannot be NULL.  Hence, a false positive
   79600 ** (returning TRUE when in fact the expression can never be NULL) might
   79601 ** be a small performance hit but is otherwise harmless.  On the other
   79602 ** hand, a false negative (returning FALSE when the result could be NULL)
   79603 ** will likely result in an incorrect answer.  So when in doubt, return
   79604 ** TRUE.
   79605 */
   79606 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
   79607   u8 op;
   79608   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
   79609   op = p->op;
   79610   if( op==TK_REGISTER ) op = p->op2;
   79611   switch( op ){
   79612     case TK_INTEGER:
   79613     case TK_STRING:
   79614     case TK_FLOAT:
   79615     case TK_BLOB:
   79616       return 0;
   79617     case TK_COLUMN:
   79618       assert( p->pTab!=0 );
   79619       return p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0;
   79620     default:
   79621       return 1;
   79622   }
   79623 }
   79624 
   79625 /*
   79626 ** Return TRUE if the given expression is a constant which would be
   79627 ** unchanged by OP_Affinity with the affinity given in the second
   79628 ** argument.
   79629 **
   79630 ** This routine is used to determine if the OP_Affinity operation
   79631 ** can be omitted.  When in doubt return FALSE.  A false negative
   79632 ** is harmless.  A false positive, however, can result in the wrong
   79633 ** answer.
   79634 */
   79635 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
   79636   u8 op;
   79637   if( aff==SQLITE_AFF_NONE ) return 1;
   79638   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
   79639   op = p->op;
   79640   if( op==TK_REGISTER ) op = p->op2;
   79641   switch( op ){
   79642     case TK_INTEGER: {
   79643       return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
   79644     }
   79645     case TK_FLOAT: {
   79646       return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
   79647     }
   79648     case TK_STRING: {
   79649       return aff==SQLITE_AFF_TEXT;
   79650     }
   79651     case TK_BLOB: {
   79652       return 1;
   79653     }
   79654     case TK_COLUMN: {
   79655       assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
   79656       return p->iColumn<0
   79657           && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
   79658     }
   79659     default: {
   79660       return 0;
   79661     }
   79662   }
   79663 }
   79664 
   79665 /*
   79666 ** Return TRUE if the given string is a row-id column name.
   79667 */
   79668 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
   79669   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
   79670   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
   79671   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
   79672   return 0;
   79673 }
   79674 
   79675 /*
   79676 ** Return true if we are able to the IN operator optimization on a
   79677 ** query of the form
   79678 **
   79679 **       x IN (SELECT ...)
   79680 **
   79681 ** Where the SELECT... clause is as specified by the parameter to this
   79682 ** routine.
   79683 **
   79684 ** The Select object passed in has already been preprocessed and no
   79685 ** errors have been found.
   79686 */
   79687 #ifndef SQLITE_OMIT_SUBQUERY
   79688 static int isCandidateForInOpt(Select *p){
   79689   SrcList *pSrc;
   79690   ExprList *pEList;
   79691   Table *pTab;
   79692   if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
   79693   if( p->pPrior ) return 0;              /* Not a compound SELECT */
   79694   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
   79695     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
   79696     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
   79697     return 0; /* No DISTINCT keyword and no aggregate functions */
   79698   }
   79699   assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
   79700   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
   79701   assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
   79702   if( p->pWhere ) return 0;              /* Has no WHERE clause */
   79703   pSrc = p->pSrc;
   79704   assert( pSrc!=0 );
   79705   if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
   79706   if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
   79707   pTab = pSrc->a[0].pTab;
   79708   if( NEVER(pTab==0) ) return 0;
   79709   assert( pTab->pSelect==0 );            /* FROM clause is not a view */
   79710   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
   79711   pEList = p->pEList;
   79712   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
   79713   if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
   79714   return 1;
   79715 }
   79716 #endif /* SQLITE_OMIT_SUBQUERY */
   79717 
   79718 /*
   79719 ** Code an OP_Once instruction and allocate space for its flag. Return the
   79720 ** address of the new instruction.
   79721 */
   79722 SQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){
   79723   Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
   79724   return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
   79725 }
   79726 
   79727 /*
   79728 ** Generate code that checks the left-most column of index table iCur to see if
   79729 ** it contains any NULL entries.  Cause the register at regHasNull to be set
   79730 ** to a non-NULL value if iCur contains no NULLs.  Cause register regHasNull
   79731 ** to be set to NULL if iCur contains one or more NULL values.
   79732 */
   79733 static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
   79734   int j1;
   79735   sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
   79736   j1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
   79737   sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
   79738   sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
   79739   VdbeComment((v, "first_entry_in(%d)", iCur));
   79740   sqlite3VdbeJumpHere(v, j1);
   79741 }
   79742 
   79743 
   79744 #ifndef SQLITE_OMIT_SUBQUERY
   79745 /*
   79746 ** The argument is an IN operator with a list (not a subquery) on the
   79747 ** right-hand side.  Return TRUE if that list is constant.
   79748 */
   79749 static int sqlite3InRhsIsConstant(Expr *pIn){
   79750   Expr *pLHS;
   79751   int res;
   79752   assert( !ExprHasProperty(pIn, EP_xIsSelect) );
   79753   pLHS = pIn->pLeft;
   79754   pIn->pLeft = 0;
   79755   res = sqlite3ExprIsConstant(pIn);
   79756   pIn->pLeft = pLHS;
   79757   return res;
   79758 }
   79759 #endif
   79760 
   79761 /*
   79762 ** This function is used by the implementation of the IN (...) operator.
   79763 ** The pX parameter is the expression on the RHS of the IN operator, which
   79764 ** might be either a list of expressions or a subquery.
   79765 **
   79766 ** The job of this routine is to find or create a b-tree object that can
   79767 ** be used either to test for membership in the RHS set or to iterate through
   79768 ** all members of the RHS set, skipping duplicates.
   79769 **
   79770 ** A cursor is opened on the b-tree object that is the RHS of the IN operator
   79771 ** and pX->iTable is set to the index of that cursor.
   79772 **
   79773 ** The returned value of this function indicates the b-tree type, as follows:
   79774 **
   79775 **   IN_INDEX_ROWID      - The cursor was opened on a database table.
   79776 **   IN_INDEX_INDEX_ASC  - The cursor was opened on an ascending index.
   79777 **   IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
   79778 **   IN_INDEX_EPH        - The cursor was opened on a specially created and
   79779 **                         populated epheremal table.
   79780 **   IN_INDEX_NOOP       - No cursor was allocated.  The IN operator must be
   79781 **                         implemented as a sequence of comparisons.
   79782 **
   79783 ** An existing b-tree might be used if the RHS expression pX is a simple
   79784 ** subquery such as:
   79785 **
   79786 **     SELECT <column> FROM <table>
   79787 **
   79788 ** If the RHS of the IN operator is a list or a more complex subquery, then
   79789 ** an ephemeral table might need to be generated from the RHS and then
   79790 ** pX->iTable made to point to the ephermeral table instead of an
   79791 ** existing table.
   79792 **
   79793 ** The inFlags parameter must contain exactly one of the bits
   79794 ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP.  If inFlags contains
   79795 ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a
   79796 ** fast membership test.  When the IN_INDEX_LOOP bit is set, the
   79797 ** IN index will be used to loop over all values of the RHS of the
   79798 ** IN operator.
   79799 **
   79800 ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
   79801 ** through the set members) then the b-tree must not contain duplicates.
   79802 ** An epheremal table must be used unless the selected <column> is guaranteed
   79803 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
   79804 ** has a UNIQUE constraint or UNIQUE index.
   79805 **
   79806 ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
   79807 ** for fast set membership tests) then an epheremal table must
   79808 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
   79809 ** be found with <column> as its left-most column.
   79810 **
   79811 ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
   79812 ** if the RHS of the IN operator is a list (not a subquery) then this
   79813 ** routine might decide that creating an ephemeral b-tree for membership
   79814 ** testing is too expensive and return IN_INDEX_NOOP.  In that case, the
   79815 ** calling routine should implement the IN operator using a sequence
   79816 ** of Eq or Ne comparison operations.
   79817 **
   79818 ** When the b-tree is being used for membership tests, the calling function
   79819 ** might need to know whether or not the RHS side of the IN operator
   79820 ** contains a NULL.  If prRhsHasNull is not a NULL pointer and
   79821 ** if there is any chance that the (...) might contain a NULL value at
   79822 ** runtime, then a register is allocated and the register number written
   79823 ** to *prRhsHasNull. If there is no chance that the (...) contains a
   79824 ** NULL value, then *prRhsHasNull is left unchanged.
   79825 **
   79826 ** If a register is allocated and its location stored in *prRhsHasNull, then
   79827 ** the value in that register will be NULL if the b-tree contains one or more
   79828 ** NULL values, and it will be some non-NULL value if the b-tree contains no
   79829 ** NULL values.
   79830 */
   79831 #ifndef SQLITE_OMIT_SUBQUERY
   79832 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, u32 inFlags, int *prRhsHasNull){
   79833   Select *p;                            /* SELECT to the right of IN operator */
   79834   int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
   79835   int iTab = pParse->nTab++;            /* Cursor of the RHS table */
   79836   int mustBeUnique;                     /* True if RHS must be unique */
   79837   Vdbe *v = sqlite3GetVdbe(pParse);     /* Virtual machine being coded */
   79838 
   79839   assert( pX->op==TK_IN );
   79840   mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
   79841 
   79842   /* Check to see if an existing table or index can be used to
   79843   ** satisfy the query.  This is preferable to generating a new
   79844   ** ephemeral table.
   79845   */
   79846   p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
   79847   if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
   79848     sqlite3 *db = pParse->db;              /* Database connection */
   79849     Table *pTab;                           /* Table <table>. */
   79850     Expr *pExpr;                           /* Expression <column> */
   79851     i16 iCol;                              /* Index of column <column> */
   79852     i16 iDb;                               /* Database idx for pTab */
   79853 
   79854     assert( p );                        /* Because of isCandidateForInOpt(p) */
   79855     assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
   79856     assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
   79857     assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */
   79858     pTab = p->pSrc->a[0].pTab;
   79859     pExpr = p->pEList->a[0].pExpr;
   79860     iCol = (i16)pExpr->iColumn;
   79861 
   79862     /* Code an OP_Transaction and OP_TableLock for <table>. */
   79863     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   79864     sqlite3CodeVerifySchema(pParse, iDb);
   79865     sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
   79866 
   79867     /* This function is only called from two places. In both cases the vdbe
   79868     ** has already been allocated. So assume sqlite3GetVdbe() is always
   79869     ** successful here.
   79870     */
   79871     assert(v);
   79872     if( iCol<0 ){
   79873       int iAddr = sqlite3CodeOnce(pParse);
   79874       VdbeCoverage(v);
   79875 
   79876       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
   79877       eType = IN_INDEX_ROWID;
   79878 
   79879       sqlite3VdbeJumpHere(v, iAddr);
   79880     }else{
   79881       Index *pIdx;                         /* Iterator variable */
   79882 
   79883       /* The collation sequence used by the comparison. If an index is to
   79884       ** be used in place of a temp-table, it must be ordered according
   79885       ** to this collation sequence.  */
   79886       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
   79887 
   79888       /* Check that the affinity that will be used to perform the
   79889       ** comparison is the same as the affinity of the column. If
   79890       ** it is not, it is not possible to use any index.
   79891       */
   79892       int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
   79893 
   79894       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
   79895         if( (pIdx->aiColumn[0]==iCol)
   79896          && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
   79897          && (!mustBeUnique || (pIdx->nKeyCol==1 && IsUniqueIndex(pIdx)))
   79898         ){
   79899           int iAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
   79900           sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
   79901           sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
   79902           VdbeComment((v, "%s", pIdx->zName));
   79903           assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
   79904           eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
   79905 
   79906           if( prRhsHasNull && !pTab->aCol[iCol].notNull ){
   79907             *prRhsHasNull = ++pParse->nMem;
   79908             sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
   79909           }
   79910           sqlite3VdbeJumpHere(v, iAddr);
   79911         }
   79912       }
   79913     }
   79914   }
   79915 
   79916   /* If no preexisting index is available for the IN clause
   79917   ** and IN_INDEX_NOOP is an allowed reply
   79918   ** and the RHS of the IN operator is a list, not a subquery
   79919   ** and the RHS is not contant or has two or fewer terms,
   79920   ** then it is not worth creating an ephermeral table to evaluate
   79921   ** the IN operator so return IN_INDEX_NOOP.
   79922   */
   79923   if( eType==0
   79924    && (inFlags & IN_INDEX_NOOP_OK)
   79925    && !ExprHasProperty(pX, EP_xIsSelect)
   79926    && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
   79927   ){
   79928     eType = IN_INDEX_NOOP;
   79929   }
   79930 
   79931 
   79932   if( eType==0 ){
   79933     /* Could not find an existing table or index to use as the RHS b-tree.
   79934     ** We will have to generate an ephemeral table to do the job.
   79935     */
   79936     u32 savedNQueryLoop = pParse->nQueryLoop;
   79937     int rMayHaveNull = 0;
   79938     eType = IN_INDEX_EPH;
   79939     if( inFlags & IN_INDEX_LOOP ){
   79940       pParse->nQueryLoop = 0;
   79941       if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
   79942         eType = IN_INDEX_ROWID;
   79943       }
   79944     }else if( prRhsHasNull ){
   79945       *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
   79946     }
   79947     sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
   79948     pParse->nQueryLoop = savedNQueryLoop;
   79949   }else{
   79950     pX->iTable = iTab;
   79951   }
   79952   return eType;
   79953 }
   79954 #endif
   79955 
   79956 /*
   79957 ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
   79958 ** or IN operators.  Examples:
   79959 **
   79960 **     (SELECT a FROM b)          -- subquery
   79961 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
   79962 **     x IN (4,5,11)              -- IN operator with list on right-hand side
   79963 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
   79964 **
   79965 ** The pExpr parameter describes the expression that contains the IN
   79966 ** operator or subquery.
   79967 **
   79968 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
   79969 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
   79970 ** to some integer key column of a table B-Tree. In this case, use an
   79971 ** intkey B-Tree to store the set of IN(...) values instead of the usual
   79972 ** (slower) variable length keys B-Tree.
   79973 **
   79974 ** If rMayHaveNull is non-zero, that means that the operation is an IN
   79975 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
   79976 ** All this routine does is initialize the register given by rMayHaveNull
   79977 ** to NULL.  Calling routines will take care of changing this register
   79978 ** value to non-NULL if the RHS is NULL-free.
   79979 **
   79980 ** For a SELECT or EXISTS operator, return the register that holds the
   79981 ** result.  For IN operators or if an error occurs, the return value is 0.
   79982 */
   79983 #ifndef SQLITE_OMIT_SUBQUERY
   79984 SQLITE_PRIVATE int sqlite3CodeSubselect(
   79985   Parse *pParse,          /* Parsing context */
   79986   Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
   79987   int rHasNullFlag,       /* Register that records whether NULLs exist in RHS */
   79988   int isRowid             /* If true, LHS of IN operator is a rowid */
   79989 ){
   79990   int jmpIfDynamic = -1;                      /* One-time test address */
   79991   int rReg = 0;                           /* Register storing resulting */
   79992   Vdbe *v = sqlite3GetVdbe(pParse);
   79993   if( NEVER(v==0) ) return 0;
   79994   sqlite3ExprCachePush(pParse);
   79995 
   79996   /* This code must be run in its entirety every time it is encountered
   79997   ** if any of the following is true:
   79998   **
   79999   **    *  The right-hand side is a correlated subquery
   80000   **    *  The right-hand side is an expression list containing variables
   80001   **    *  We are inside a trigger
   80002   **
   80003   ** If all of the above are false, then we can run this code just once
   80004   ** save the results, and reuse the same result on subsequent invocations.
   80005   */
   80006   if( !ExprHasProperty(pExpr, EP_VarSelect) ){
   80007     jmpIfDynamic = sqlite3CodeOnce(pParse); VdbeCoverage(v);
   80008   }
   80009 
   80010 #ifndef SQLITE_OMIT_EXPLAIN
   80011   if( pParse->explain==2 ){
   80012     char *zMsg = sqlite3MPrintf(
   80013         pParse->db, "EXECUTE %s%s SUBQUERY %d", jmpIfDynamic>=0?"":"CORRELATED ",
   80014         pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
   80015     );
   80016     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
   80017   }
   80018 #endif
   80019 
   80020   switch( pExpr->op ){
   80021     case TK_IN: {
   80022       char affinity;              /* Affinity of the LHS of the IN */
   80023       int addr;                   /* Address of OP_OpenEphemeral instruction */
   80024       Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
   80025       KeyInfo *pKeyInfo = 0;      /* Key information */
   80026 
   80027       affinity = sqlite3ExprAffinity(pLeft);
   80028 
   80029       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
   80030       ** expression it is handled the same way.  An ephemeral table is
   80031       ** filled with single-field index keys representing the results
   80032       ** from the SELECT or the <exprlist>.
   80033       **
   80034       ** If the 'x' expression is a column value, or the SELECT...
   80035       ** statement returns a column value, then the affinity of that
   80036       ** column is used to build the index keys. If both 'x' and the
   80037       ** SELECT... statement are columns, then numeric affinity is used
   80038       ** if either column has NUMERIC or INTEGER affinity. If neither
   80039       ** 'x' nor the SELECT... statement are columns, then numeric affinity
   80040       ** is used.
   80041       */
   80042       pExpr->iTable = pParse->nTab++;
   80043       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
   80044       pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, 1, 1);
   80045 
   80046       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   80047         /* Case 1:     expr IN (SELECT ...)
   80048         **
   80049         ** Generate code to write the results of the select into the temporary
   80050         ** table allocated and opened above.
   80051         */
   80052         Select *pSelect = pExpr->x.pSelect;
   80053         SelectDest dest;
   80054         ExprList *pEList;
   80055 
   80056         assert( !isRowid );
   80057         sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
   80058         dest.affSdst = (u8)affinity;
   80059         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
   80060         pSelect->iLimit = 0;
   80061         testcase( pSelect->selFlags & SF_Distinct );
   80062         pSelect->selFlags &= ~SF_Distinct;
   80063         testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
   80064         if( sqlite3Select(pParse, pSelect, &dest) ){
   80065           sqlite3KeyInfoUnref(pKeyInfo);
   80066           return 0;
   80067         }
   80068         pEList = pSelect->pEList;
   80069         assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
   80070         assert( pEList!=0 );
   80071         assert( pEList->nExpr>0 );
   80072         assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
   80073         pKeyInfo->aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
   80074                                                          pEList->a[0].pExpr);
   80075       }else if( ALWAYS(pExpr->x.pList!=0) ){
   80076         /* Case 2:     expr IN (exprlist)
   80077         **
   80078         ** For each expression, build an index key from the evaluation and
   80079         ** store it in the temporary table. If <expr> is a column, then use
   80080         ** that columns affinity when building index keys. If <expr> is not
   80081         ** a column, use numeric affinity.
   80082         */
   80083         int i;
   80084         ExprList *pList = pExpr->x.pList;
   80085         struct ExprList_item *pItem;
   80086         int r1, r2, r3;
   80087 
   80088         if( !affinity ){
   80089           affinity = SQLITE_AFF_NONE;
   80090         }
   80091         if( pKeyInfo ){
   80092           assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
   80093           pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
   80094         }
   80095 
   80096         /* Loop through each expression in <exprlist>. */
   80097         r1 = sqlite3GetTempReg(pParse);
   80098         r2 = sqlite3GetTempReg(pParse);
   80099         if( isRowid ) sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
   80100         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
   80101           Expr *pE2 = pItem->pExpr;
   80102           int iValToIns;
   80103 
   80104           /* If the expression is not constant then we will need to
   80105           ** disable the test that was generated above that makes sure
   80106           ** this code only executes once.  Because for a non-constant
   80107           ** expression we need to rerun this code each time.
   80108           */
   80109           if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
   80110             sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
   80111             jmpIfDynamic = -1;
   80112           }
   80113 
   80114           /* Evaluate the expression and insert it into the temp table */
   80115           if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
   80116             sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
   80117           }else{
   80118             r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
   80119             if( isRowid ){
   80120               sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
   80121                                 sqlite3VdbeCurrentAddr(v)+2);
   80122               VdbeCoverage(v);
   80123               sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
   80124             }else{
   80125               sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
   80126               sqlite3ExprCacheAffinityChange(pParse, r3, 1);
   80127               sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
   80128             }
   80129           }
   80130         }
   80131         sqlite3ReleaseTempReg(pParse, r1);
   80132         sqlite3ReleaseTempReg(pParse, r2);
   80133       }
   80134       if( pKeyInfo ){
   80135         sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
   80136       }
   80137       break;
   80138     }
   80139 
   80140     case TK_EXISTS:
   80141     case TK_SELECT:
   80142     default: {
   80143       /* If this has to be a scalar SELECT.  Generate code to put the
   80144       ** value of this select in a memory cell and record the number
   80145       ** of the memory cell in iColumn.  If this is an EXISTS, write
   80146       ** an integer 0 (not exists) or 1 (exists) into a memory cell
   80147       ** and record that memory cell in iColumn.
   80148       */
   80149       Select *pSel;                         /* SELECT statement to encode */
   80150       SelectDest dest;                      /* How to deal with SELECt result */
   80151 
   80152       testcase( pExpr->op==TK_EXISTS );
   80153       testcase( pExpr->op==TK_SELECT );
   80154       assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
   80155 
   80156       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
   80157       pSel = pExpr->x.pSelect;
   80158       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
   80159       if( pExpr->op==TK_SELECT ){
   80160         dest.eDest = SRT_Mem;
   80161         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
   80162         VdbeComment((v, "Init subquery result"));
   80163       }else{
   80164         dest.eDest = SRT_Exists;
   80165         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
   80166         VdbeComment((v, "Init EXISTS result"));
   80167       }
   80168       sqlite3ExprDelete(pParse->db, pSel->pLimit);
   80169       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
   80170                                   &sqlite3IntTokens[1]);
   80171       pSel->iLimit = 0;
   80172       if( sqlite3Select(pParse, pSel, &dest) ){
   80173         return 0;
   80174       }
   80175       rReg = dest.iSDParm;
   80176       ExprSetVVAProperty(pExpr, EP_NoReduce);
   80177       break;
   80178     }
   80179   }
   80180 
   80181   if( rHasNullFlag ){
   80182     sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
   80183   }
   80184 
   80185   if( jmpIfDynamic>=0 ){
   80186     sqlite3VdbeJumpHere(v, jmpIfDynamic);
   80187   }
   80188   sqlite3ExprCachePop(pParse);
   80189 
   80190   return rReg;
   80191 }
   80192 #endif /* SQLITE_OMIT_SUBQUERY */
   80193 
   80194 #ifndef SQLITE_OMIT_SUBQUERY
   80195 /*
   80196 ** Generate code for an IN expression.
   80197 **
   80198 **      x IN (SELECT ...)
   80199 **      x IN (value, value, ...)
   80200 **
   80201 ** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
   80202 ** is an array of zero or more values.  The expression is true if the LHS is
   80203 ** contained within the RHS.  The value of the expression is unknown (NULL)
   80204 ** if the LHS is NULL or if the LHS is not contained within the RHS and the
   80205 ** RHS contains one or more NULL values.
   80206 **
   80207 ** This routine generates code that jumps to destIfFalse if the LHS is not
   80208 ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
   80209 ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
   80210 ** within the RHS then fall through.
   80211 */
   80212 static void sqlite3ExprCodeIN(
   80213   Parse *pParse,        /* Parsing and code generating context */
   80214   Expr *pExpr,          /* The IN expression */
   80215   int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
   80216   int destIfNull        /* Jump here if the results are unknown due to NULLs */
   80217 ){
   80218   int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
   80219   char affinity;        /* Comparison affinity to use */
   80220   int eType;            /* Type of the RHS */
   80221   int r1;               /* Temporary use register */
   80222   Vdbe *v;              /* Statement under construction */
   80223 
   80224   /* Compute the RHS.   After this step, the table with cursor
   80225   ** pExpr->iTable will contains the values that make up the RHS.
   80226   */
   80227   v = pParse->pVdbe;
   80228   assert( v!=0 );       /* OOM detected prior to this routine */
   80229   VdbeNoopComment((v, "begin IN expr"));
   80230   eType = sqlite3FindInIndex(pParse, pExpr,
   80231                              IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
   80232                              destIfFalse==destIfNull ? 0 : &rRhsHasNull);
   80233 
   80234   /* Figure out the affinity to use to create a key from the results
   80235   ** of the expression. affinityStr stores a static string suitable for
   80236   ** P4 of OP_MakeRecord.
   80237   */
   80238   affinity = comparisonAffinity(pExpr);
   80239 
   80240   /* Code the LHS, the <expr> from "<expr> IN (...)".
   80241   */
   80242   sqlite3ExprCachePush(pParse);
   80243   r1 = sqlite3GetTempReg(pParse);
   80244   sqlite3ExprCode(pParse, pExpr->pLeft, r1);
   80245 
   80246   /* If sqlite3FindInIndex() did not find or create an index that is
   80247   ** suitable for evaluating the IN operator, then evaluate using a
   80248   ** sequence of comparisons.
   80249   */
   80250   if( eType==IN_INDEX_NOOP ){
   80251     ExprList *pList = pExpr->x.pList;
   80252     CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
   80253     int labelOk = sqlite3VdbeMakeLabel(v);
   80254     int r2, regToFree;
   80255     int regCkNull = 0;
   80256     int ii;
   80257     assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   80258     if( destIfNull!=destIfFalse ){
   80259       regCkNull = sqlite3GetTempReg(pParse);
   80260       sqlite3VdbeAddOp3(v, OP_BitAnd, r1, r1, regCkNull);
   80261     }
   80262     for(ii=0; ii<pList->nExpr; ii++){
   80263       r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
   80264       if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
   80265         sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
   80266       }
   80267       if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
   80268         sqlite3VdbeAddOp4(v, OP_Eq, r1, labelOk, r2,
   80269                           (void*)pColl, P4_COLLSEQ);
   80270         VdbeCoverageIf(v, ii<pList->nExpr-1);
   80271         VdbeCoverageIf(v, ii==pList->nExpr-1);
   80272         sqlite3VdbeChangeP5(v, affinity);
   80273       }else{
   80274         assert( destIfNull==destIfFalse );
   80275         sqlite3VdbeAddOp4(v, OP_Ne, r1, destIfFalse, r2,
   80276                           (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
   80277         sqlite3VdbeChangeP5(v, affinity | SQLITE_JUMPIFNULL);
   80278       }
   80279       sqlite3ReleaseTempReg(pParse, regToFree);
   80280     }
   80281     if( regCkNull ){
   80282       sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
   80283       sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
   80284     }
   80285     sqlite3VdbeResolveLabel(v, labelOk);
   80286     sqlite3ReleaseTempReg(pParse, regCkNull);
   80287   }else{
   80288 
   80289     /* If the LHS is NULL, then the result is either false or NULL depending
   80290     ** on whether the RHS is empty or not, respectively.
   80291     */
   80292     if( sqlite3ExprCanBeNull(pExpr->pLeft) ){
   80293       if( destIfNull==destIfFalse ){
   80294         /* Shortcut for the common case where the false and NULL outcomes are
   80295         ** the same. */
   80296         sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull); VdbeCoverage(v);
   80297       }else{
   80298         int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1); VdbeCoverage(v);
   80299         sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
   80300         VdbeCoverage(v);
   80301         sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
   80302         sqlite3VdbeJumpHere(v, addr1);
   80303       }
   80304     }
   80305 
   80306     if( eType==IN_INDEX_ROWID ){
   80307       /* In this case, the RHS is the ROWID of table b-tree
   80308       */
   80309       sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse); VdbeCoverage(v);
   80310       sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
   80311       VdbeCoverage(v);
   80312     }else{
   80313       /* In this case, the RHS is an index b-tree.
   80314       */
   80315       sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
   80316 
   80317       /* If the set membership test fails, then the result of the
   80318       ** "x IN (...)" expression must be either 0 or NULL. If the set
   80319       ** contains no NULL values, then the result is 0. If the set
   80320       ** contains one or more NULL values, then the result of the
   80321       ** expression is also NULL.
   80322       */
   80323       assert( destIfFalse!=destIfNull || rRhsHasNull==0 );
   80324       if( rRhsHasNull==0 ){
   80325         /* This branch runs if it is known at compile time that the RHS
   80326         ** cannot contain NULL values. This happens as the result
   80327         ** of a "NOT NULL" constraint in the database schema.
   80328         **
   80329         ** Also run this branch if NULL is equivalent to FALSE
   80330         ** for this particular IN operator.
   80331         */
   80332         sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
   80333         VdbeCoverage(v);
   80334       }else{
   80335         /* In this branch, the RHS of the IN might contain a NULL and
   80336         ** the presence of a NULL on the RHS makes a difference in the
   80337         ** outcome.
   80338         */
   80339         int j1;
   80340 
   80341         /* First check to see if the LHS is contained in the RHS.  If so,
   80342         ** then the answer is TRUE the presence of NULLs in the RHS does
   80343         ** not matter.  If the LHS is not contained in the RHS, then the
   80344         ** answer is NULL if the RHS contains NULLs and the answer is
   80345         ** FALSE if the RHS is NULL-free.
   80346         */
   80347         j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
   80348         VdbeCoverage(v);
   80349         sqlite3VdbeAddOp2(v, OP_IsNull, rRhsHasNull, destIfNull);
   80350         VdbeCoverage(v);
   80351         sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
   80352         sqlite3VdbeJumpHere(v, j1);
   80353       }
   80354     }
   80355   }
   80356   sqlite3ReleaseTempReg(pParse, r1);
   80357   sqlite3ExprCachePop(pParse);
   80358   VdbeComment((v, "end IN expr"));
   80359 }
   80360 #endif /* SQLITE_OMIT_SUBQUERY */
   80361 
   80362 /*
   80363 ** Duplicate an 8-byte value
   80364 */
   80365 static char *dup8bytes(Vdbe *v, const char *in){
   80366   char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
   80367   if( out ){
   80368     memcpy(out, in, 8);
   80369   }
   80370   return out;
   80371 }
   80372 
   80373 #ifndef SQLITE_OMIT_FLOATING_POINT
   80374 /*
   80375 ** Generate an instruction that will put the floating point
   80376 ** value described by z[0..n-1] into register iMem.
   80377 **
   80378 ** The z[] string will probably not be zero-terminated.  But the
   80379 ** z[n] character is guaranteed to be something that does not look
   80380 ** like the continuation of the number.
   80381 */
   80382 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
   80383   if( ALWAYS(z!=0) ){
   80384     double value;
   80385     char *zV;
   80386     sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
   80387     assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
   80388     if( negateFlag ) value = -value;
   80389     zV = dup8bytes(v, (char*)&value);
   80390     sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
   80391   }
   80392 }
   80393 #endif
   80394 
   80395 
   80396 /*
   80397 ** Generate an instruction that will put the integer describe by
   80398 ** text z[0..n-1] into register iMem.
   80399 **
   80400 ** Expr.u.zToken is always UTF8 and zero-terminated.
   80401 */
   80402 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
   80403   Vdbe *v = pParse->pVdbe;
   80404   if( pExpr->flags & EP_IntValue ){
   80405     int i = pExpr->u.iValue;
   80406     assert( i>=0 );
   80407     if( negFlag ) i = -i;
   80408     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
   80409   }else{
   80410     int c;
   80411     i64 value;
   80412     const char *z = pExpr->u.zToken;
   80413     assert( z!=0 );
   80414     c = sqlite3DecOrHexToI64(z, &value);
   80415     if( c==0 || (c==2 && negFlag) ){
   80416       char *zV;
   80417       if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
   80418       zV = dup8bytes(v, (char*)&value);
   80419       sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
   80420     }else{
   80421 #ifdef SQLITE_OMIT_FLOATING_POINT
   80422       sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
   80423 #else
   80424 #ifndef SQLITE_OMIT_HEX_INTEGER
   80425       if( sqlite3_strnicmp(z,"0x",2)==0 ){
   80426         sqlite3ErrorMsg(pParse, "hex literal too big: %s", z);
   80427       }else
   80428 #endif
   80429       {
   80430         codeReal(v, z, negFlag, iMem);
   80431       }
   80432 #endif
   80433     }
   80434   }
   80435 }
   80436 
   80437 /*
   80438 ** Clear a cache entry.
   80439 */
   80440 static void cacheEntryClear(Parse *pParse, struct yColCache *p){
   80441   if( p->tempReg ){
   80442     if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
   80443       pParse->aTempReg[pParse->nTempReg++] = p->iReg;
   80444     }
   80445     p->tempReg = 0;
   80446   }
   80447 }
   80448 
   80449 
   80450 /*
   80451 ** Record in the column cache that a particular column from a
   80452 ** particular table is stored in a particular register.
   80453 */
   80454 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
   80455   int i;
   80456   int minLru;
   80457   int idxLru;
   80458   struct yColCache *p;
   80459 
   80460   assert( iReg>0 );  /* Register numbers are always positive */
   80461   assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
   80462 
   80463   /* The SQLITE_ColumnCache flag disables the column cache.  This is used
   80464   ** for testing only - to verify that SQLite always gets the same answer
   80465   ** with and without the column cache.
   80466   */
   80467   if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
   80468 
   80469   /* First replace any existing entry.
   80470   **
   80471   ** Actually, the way the column cache is currently used, we are guaranteed
   80472   ** that the object will never already be in cache.  Verify this guarantee.
   80473   */
   80474 #ifndef NDEBUG
   80475   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   80476     assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
   80477   }
   80478 #endif
   80479 
   80480   /* Find an empty slot and replace it */
   80481   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   80482     if( p->iReg==0 ){
   80483       p->iLevel = pParse->iCacheLevel;
   80484       p->iTable = iTab;
   80485       p->iColumn = iCol;
   80486       p->iReg = iReg;
   80487       p->tempReg = 0;
   80488       p->lru = pParse->iCacheCnt++;
   80489       return;
   80490     }
   80491   }
   80492 
   80493   /* Replace the last recently used */
   80494   minLru = 0x7fffffff;
   80495   idxLru = -1;
   80496   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   80497     if( p->lru<minLru ){
   80498       idxLru = i;
   80499       minLru = p->lru;
   80500     }
   80501   }
   80502   if( ALWAYS(idxLru>=0) ){
   80503     p = &pParse->aColCache[idxLru];
   80504     p->iLevel = pParse->iCacheLevel;
   80505     p->iTable = iTab;
   80506     p->iColumn = iCol;
   80507     p->iReg = iReg;
   80508     p->tempReg = 0;
   80509     p->lru = pParse->iCacheCnt++;
   80510     return;
   80511   }
   80512 }
   80513 
   80514 /*
   80515 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
   80516 ** Purge the range of registers from the column cache.
   80517 */
   80518 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
   80519   int i;
   80520   int iLast = iReg + nReg - 1;
   80521   struct yColCache *p;
   80522   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   80523     int r = p->iReg;
   80524     if( r>=iReg && r<=iLast ){
   80525       cacheEntryClear(pParse, p);
   80526       p->iReg = 0;
   80527     }
   80528   }
   80529 }
   80530 
   80531 /*
   80532 ** Remember the current column cache context.  Any new entries added
   80533 ** added to the column cache after this call are removed when the
   80534 ** corresponding pop occurs.
   80535 */
   80536 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
   80537   pParse->iCacheLevel++;
   80538 #ifdef SQLITE_DEBUG
   80539   if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
   80540     printf("PUSH to %d\n", pParse->iCacheLevel);
   80541   }
   80542 #endif
   80543 }
   80544 
   80545 /*
   80546 ** Remove from the column cache any entries that were added since the
   80547 ** the previous sqlite3ExprCachePush operation.  In other words, restore
   80548 ** the cache to the state it was in prior the most recent Push.
   80549 */
   80550 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse){
   80551   int i;
   80552   struct yColCache *p;
   80553   assert( pParse->iCacheLevel>=1 );
   80554   pParse->iCacheLevel--;
   80555 #ifdef SQLITE_DEBUG
   80556   if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
   80557     printf("POP  to %d\n", pParse->iCacheLevel);
   80558   }
   80559 #endif
   80560   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   80561     if( p->iReg && p->iLevel>pParse->iCacheLevel ){
   80562       cacheEntryClear(pParse, p);
   80563       p->iReg = 0;
   80564     }
   80565   }
   80566 }
   80567 
   80568 /*
   80569 ** When a cached column is reused, make sure that its register is
   80570 ** no longer available as a temp register.  ticket #3879:  that same
   80571 ** register might be in the cache in multiple places, so be sure to
   80572 ** get them all.
   80573 */
   80574 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
   80575   int i;
   80576   struct yColCache *p;
   80577   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   80578     if( p->iReg==iReg ){
   80579       p->tempReg = 0;
   80580     }
   80581   }
   80582 }
   80583 
   80584 /*
   80585 ** Generate code to extract the value of the iCol-th column of a table.
   80586 */
   80587 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
   80588   Vdbe *v,        /* The VDBE under construction */
   80589   Table *pTab,    /* The table containing the value */
   80590   int iTabCur,    /* The table cursor.  Or the PK cursor for WITHOUT ROWID */
   80591   int iCol,       /* Index of the column to extract */
   80592   int regOut      /* Extract the value into this register */
   80593 ){
   80594   if( iCol<0 || iCol==pTab->iPKey ){
   80595     sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
   80596   }else{
   80597     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
   80598     int x = iCol;
   80599     if( !HasRowid(pTab) ){
   80600       x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
   80601     }
   80602     sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
   80603   }
   80604   if( iCol>=0 ){
   80605     sqlite3ColumnDefault(v, pTab, iCol, regOut);
   80606   }
   80607 }
   80608 
   80609 /*
   80610 ** Generate code that will extract the iColumn-th column from
   80611 ** table pTab and store the column value in a register.  An effort
   80612 ** is made to store the column value in register iReg, but this is
   80613 ** not guaranteed.  The location of the column value is returned.
   80614 **
   80615 ** There must be an open cursor to pTab in iTable when this routine
   80616 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
   80617 */
   80618 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
   80619   Parse *pParse,   /* Parsing and code generating context */
   80620   Table *pTab,     /* Description of the table we are reading from */
   80621   int iColumn,     /* Index of the table column */
   80622   int iTable,      /* The cursor pointing to the table */
   80623   int iReg,        /* Store results here */
   80624   u8 p5            /* P5 value for OP_Column */
   80625 ){
   80626   Vdbe *v = pParse->pVdbe;
   80627   int i;
   80628   struct yColCache *p;
   80629 
   80630   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   80631     if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
   80632       p->lru = pParse->iCacheCnt++;
   80633       sqlite3ExprCachePinRegister(pParse, p->iReg);
   80634       return p->iReg;
   80635     }
   80636   }
   80637   assert( v!=0 );
   80638   sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
   80639   if( p5 ){
   80640     sqlite3VdbeChangeP5(v, p5);
   80641   }else{
   80642     sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
   80643   }
   80644   return iReg;
   80645 }
   80646 
   80647 /*
   80648 ** Clear all column cache entries.
   80649 */
   80650 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
   80651   int i;
   80652   struct yColCache *p;
   80653 
   80654 #if SQLITE_DEBUG
   80655   if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
   80656     printf("CLEAR\n");
   80657   }
   80658 #endif
   80659   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   80660     if( p->iReg ){
   80661       cacheEntryClear(pParse, p);
   80662       p->iReg = 0;
   80663     }
   80664   }
   80665 }
   80666 
   80667 /*
   80668 ** Record the fact that an affinity change has occurred on iCount
   80669 ** registers starting with iStart.
   80670 */
   80671 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
   80672   sqlite3ExprCacheRemove(pParse, iStart, iCount);
   80673 }
   80674 
   80675 /*
   80676 ** Generate code to move content from registers iFrom...iFrom+nReg-1
   80677 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
   80678 */
   80679 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
   80680   int i;
   80681   struct yColCache *p;
   80682   assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
   80683   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
   80684   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   80685     int x = p->iReg;
   80686     if( x>=iFrom && x<iFrom+nReg ){
   80687       p->iReg += iTo-iFrom;
   80688     }
   80689   }
   80690 }
   80691 
   80692 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
   80693 /*
   80694 ** Return true if any register in the range iFrom..iTo (inclusive)
   80695 ** is used as part of the column cache.
   80696 **
   80697 ** This routine is used within assert() and testcase() macros only
   80698 ** and does not appear in a normal build.
   80699 */
   80700 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
   80701   int i;
   80702   struct yColCache *p;
   80703   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   80704     int r = p->iReg;
   80705     if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
   80706   }
   80707   return 0;
   80708 }
   80709 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
   80710 
   80711 /*
   80712 ** Convert an expression node to a TK_REGISTER
   80713 */
   80714 static void exprToRegister(Expr *p, int iReg){
   80715   p->op2 = p->op;
   80716   p->op = TK_REGISTER;
   80717   p->iTable = iReg;
   80718   ExprClearProperty(p, EP_Skip);
   80719 }
   80720 
   80721 /*
   80722 ** Generate code into the current Vdbe to evaluate the given
   80723 ** expression.  Attempt to store the results in register "target".
   80724 ** Return the register where results are stored.
   80725 **
   80726 ** With this routine, there is no guarantee that results will
   80727 ** be stored in target.  The result might be stored in some other
   80728 ** register if it is convenient to do so.  The calling function
   80729 ** must check the return code and move the results to the desired
   80730 ** register.
   80731 */
   80732 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
   80733   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
   80734   int op;                   /* The opcode being coded */
   80735   int inReg = target;       /* Results stored in register inReg */
   80736   int regFree1 = 0;         /* If non-zero free this temporary register */
   80737   int regFree2 = 0;         /* If non-zero free this temporary register */
   80738   int r1, r2, r3, r4;       /* Various register numbers */
   80739   sqlite3 *db = pParse->db; /* The database connection */
   80740   Expr tempX;               /* Temporary expression node */
   80741 
   80742   assert( target>0 && target<=pParse->nMem );
   80743   if( v==0 ){
   80744     assert( pParse->db->mallocFailed );
   80745     return 0;
   80746   }
   80747 
   80748   if( pExpr==0 ){
   80749     op = TK_NULL;
   80750   }else{
   80751     op = pExpr->op;
   80752   }
   80753   switch( op ){
   80754     case TK_AGG_COLUMN: {
   80755       AggInfo *pAggInfo = pExpr->pAggInfo;
   80756       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
   80757       if( !pAggInfo->directMode ){
   80758         assert( pCol->iMem>0 );
   80759         inReg = pCol->iMem;
   80760         break;
   80761       }else if( pAggInfo->useSortingIdx ){
   80762         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
   80763                               pCol->iSorterColumn, target);
   80764         break;
   80765       }
   80766       /* Otherwise, fall thru into the TK_COLUMN case */
   80767     }
   80768     case TK_COLUMN: {
   80769       int iTab = pExpr->iTable;
   80770       if( iTab<0 ){
   80771         if( pParse->ckBase>0 ){
   80772           /* Generating CHECK constraints or inserting into partial index */
   80773           inReg = pExpr->iColumn + pParse->ckBase;
   80774           break;
   80775         }else{
   80776           /* Deleting from a partial index */
   80777           iTab = pParse->iPartIdxTab;
   80778         }
   80779       }
   80780       inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
   80781                                pExpr->iColumn, iTab, target,
   80782                                pExpr->op2);
   80783       break;
   80784     }
   80785     case TK_INTEGER: {
   80786       codeInteger(pParse, pExpr, 0, target);
   80787       break;
   80788     }
   80789 #ifndef SQLITE_OMIT_FLOATING_POINT
   80790     case TK_FLOAT: {
   80791       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   80792       codeReal(v, pExpr->u.zToken, 0, target);
   80793       break;
   80794     }
   80795 #endif
   80796     case TK_STRING: {
   80797       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   80798       sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
   80799       break;
   80800     }
   80801     case TK_NULL: {
   80802       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
   80803       break;
   80804     }
   80805 #ifndef SQLITE_OMIT_BLOB_LITERAL
   80806     case TK_BLOB: {
   80807       int n;
   80808       const char *z;
   80809       char *zBlob;
   80810       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   80811       assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
   80812       assert( pExpr->u.zToken[1]=='\'' );
   80813       z = &pExpr->u.zToken[2];
   80814       n = sqlite3Strlen30(z) - 1;
   80815       assert( z[n]=='\'' );
   80816       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
   80817       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
   80818       break;
   80819     }
   80820 #endif
   80821     case TK_VARIABLE: {
   80822       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   80823       assert( pExpr->u.zToken!=0 );
   80824       assert( pExpr->u.zToken[0]!=0 );
   80825       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
   80826       if( pExpr->u.zToken[1]!=0 ){
   80827         assert( pExpr->u.zToken[0]=='?'
   80828              || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
   80829         sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
   80830       }
   80831       break;
   80832     }
   80833     case TK_REGISTER: {
   80834       inReg = pExpr->iTable;
   80835       break;
   80836     }
   80837     case TK_AS: {
   80838       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
   80839       break;
   80840     }
   80841 #ifndef SQLITE_OMIT_CAST
   80842     case TK_CAST: {
   80843       /* Expressions of the form:   CAST(pLeft AS token) */
   80844       int aff, to_op;
   80845       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
   80846       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   80847       aff = sqlite3AffinityType(pExpr->u.zToken, 0);
   80848       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
   80849       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
   80850       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
   80851       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
   80852       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
   80853       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
   80854       testcase( to_op==OP_ToText );
   80855       testcase( to_op==OP_ToBlob );
   80856       testcase( to_op==OP_ToNumeric );
   80857       testcase( to_op==OP_ToInt );
   80858       testcase( to_op==OP_ToReal );
   80859       if( inReg!=target ){
   80860         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
   80861         inReg = target;
   80862       }
   80863       sqlite3VdbeAddOp1(v, to_op, inReg);
   80864       testcase( usedAsColumnCache(pParse, inReg, inReg) );
   80865       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
   80866       break;
   80867     }
   80868 #endif /* SQLITE_OMIT_CAST */
   80869     case TK_LT:
   80870     case TK_LE:
   80871     case TK_GT:
   80872     case TK_GE:
   80873     case TK_NE:
   80874     case TK_EQ: {
   80875       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   80876       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   80877       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
   80878                   r1, r2, inReg, SQLITE_STOREP2);
   80879       assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
   80880       assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
   80881       assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
   80882       assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
   80883       assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
   80884       assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
   80885       testcase( regFree1==0 );
   80886       testcase( regFree2==0 );
   80887       break;
   80888     }
   80889     case TK_IS:
   80890     case TK_ISNOT: {
   80891       testcase( op==TK_IS );
   80892       testcase( op==TK_ISNOT );
   80893       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   80894       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   80895       op = (op==TK_IS) ? TK_EQ : TK_NE;
   80896       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
   80897                   r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
   80898       VdbeCoverageIf(v, op==TK_EQ);
   80899       VdbeCoverageIf(v, op==TK_NE);
   80900       testcase( regFree1==0 );
   80901       testcase( regFree2==0 );
   80902       break;
   80903     }
   80904     case TK_AND:
   80905     case TK_OR:
   80906     case TK_PLUS:
   80907     case TK_STAR:
   80908     case TK_MINUS:
   80909     case TK_REM:
   80910     case TK_BITAND:
   80911     case TK_BITOR:
   80912     case TK_SLASH:
   80913     case TK_LSHIFT:
   80914     case TK_RSHIFT:
   80915     case TK_CONCAT: {
   80916       assert( TK_AND==OP_And );            testcase( op==TK_AND );
   80917       assert( TK_OR==OP_Or );              testcase( op==TK_OR );
   80918       assert( TK_PLUS==OP_Add );           testcase( op==TK_PLUS );
   80919       assert( TK_MINUS==OP_Subtract );     testcase( op==TK_MINUS );
   80920       assert( TK_REM==OP_Remainder );      testcase( op==TK_REM );
   80921       assert( TK_BITAND==OP_BitAnd );      testcase( op==TK_BITAND );
   80922       assert( TK_BITOR==OP_BitOr );        testcase( op==TK_BITOR );
   80923       assert( TK_SLASH==OP_Divide );       testcase( op==TK_SLASH );
   80924       assert( TK_LSHIFT==OP_ShiftLeft );   testcase( op==TK_LSHIFT );
   80925       assert( TK_RSHIFT==OP_ShiftRight );  testcase( op==TK_RSHIFT );
   80926       assert( TK_CONCAT==OP_Concat );      testcase( op==TK_CONCAT );
   80927       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   80928       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   80929       sqlite3VdbeAddOp3(v, op, r2, r1, target);
   80930       testcase( regFree1==0 );
   80931       testcase( regFree2==0 );
   80932       break;
   80933     }
   80934     case TK_UMINUS: {
   80935       Expr *pLeft = pExpr->pLeft;
   80936       assert( pLeft );
   80937       if( pLeft->op==TK_INTEGER ){
   80938         codeInteger(pParse, pLeft, 1, target);
   80939 #ifndef SQLITE_OMIT_FLOATING_POINT
   80940       }else if( pLeft->op==TK_FLOAT ){
   80941         assert( !ExprHasProperty(pExpr, EP_IntValue) );
   80942         codeReal(v, pLeft->u.zToken, 1, target);
   80943 #endif
   80944       }else{
   80945         tempX.op = TK_INTEGER;
   80946         tempX.flags = EP_IntValue|EP_TokenOnly;
   80947         tempX.u.iValue = 0;
   80948         r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
   80949         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
   80950         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
   80951         testcase( regFree2==0 );
   80952       }
   80953       inReg = target;
   80954       break;
   80955     }
   80956     case TK_BITNOT:
   80957     case TK_NOT: {
   80958       assert( TK_BITNOT==OP_BitNot );   testcase( op==TK_BITNOT );
   80959       assert( TK_NOT==OP_Not );         testcase( op==TK_NOT );
   80960       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   80961       testcase( regFree1==0 );
   80962       inReg = target;
   80963       sqlite3VdbeAddOp2(v, op, r1, inReg);
   80964       break;
   80965     }
   80966     case TK_ISNULL:
   80967     case TK_NOTNULL: {
   80968       int addr;
   80969       assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
   80970       assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
   80971       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
   80972       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   80973       testcase( regFree1==0 );
   80974       addr = sqlite3VdbeAddOp1(v, op, r1);
   80975       VdbeCoverageIf(v, op==TK_ISNULL);
   80976       VdbeCoverageIf(v, op==TK_NOTNULL);
   80977       sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
   80978       sqlite3VdbeJumpHere(v, addr);
   80979       break;
   80980     }
   80981     case TK_AGG_FUNCTION: {
   80982       AggInfo *pInfo = pExpr->pAggInfo;
   80983       if( pInfo==0 ){
   80984         assert( !ExprHasProperty(pExpr, EP_IntValue) );
   80985         sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
   80986       }else{
   80987         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
   80988       }
   80989       break;
   80990     }
   80991     case TK_FUNCTION: {
   80992       ExprList *pFarg;       /* List of function arguments */
   80993       int nFarg;             /* Number of function arguments */
   80994       FuncDef *pDef;         /* The function definition object */
   80995       int nId;               /* Length of the function name in bytes */
   80996       const char *zId;       /* The function name */
   80997       u32 constMask = 0;     /* Mask of function arguments that are constant */
   80998       int i;                 /* Loop counter */
   80999       u8 enc = ENC(db);      /* The text encoding used by this database */
   81000       CollSeq *pColl = 0;    /* A collating sequence */
   81001 
   81002       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   81003       if( ExprHasProperty(pExpr, EP_TokenOnly) ){
   81004         pFarg = 0;
   81005       }else{
   81006         pFarg = pExpr->x.pList;
   81007       }
   81008       nFarg = pFarg ? pFarg->nExpr : 0;
   81009       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   81010       zId = pExpr->u.zToken;
   81011       nId = sqlite3Strlen30(zId);
   81012       pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
   81013       if( pDef==0 || pDef->xFunc==0 ){
   81014         sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
   81015         break;
   81016       }
   81017 
   81018       /* Attempt a direct implementation of the built-in COALESCE() and
   81019       ** IFNULL() functions.  This avoids unnecessary evalation of
   81020       ** arguments past the first non-NULL argument.
   81021       */
   81022       if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
   81023         int endCoalesce = sqlite3VdbeMakeLabel(v);
   81024         assert( nFarg>=2 );
   81025         sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
   81026         for(i=1; i<nFarg; i++){
   81027           sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
   81028           VdbeCoverage(v);
   81029           sqlite3ExprCacheRemove(pParse, target, 1);
   81030           sqlite3ExprCachePush(pParse);
   81031           sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
   81032           sqlite3ExprCachePop(pParse);
   81033         }
   81034         sqlite3VdbeResolveLabel(v, endCoalesce);
   81035         break;
   81036       }
   81037 
   81038       /* The UNLIKELY() function is a no-op.  The result is the value
   81039       ** of the first argument.
   81040       */
   81041       if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
   81042         assert( nFarg>=1 );
   81043         sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
   81044         break;
   81045       }
   81046 
   81047       for(i=0; i<nFarg; i++){
   81048         if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
   81049           testcase( i==31 );
   81050           constMask |= MASKBIT32(i);
   81051         }
   81052         if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
   81053           pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
   81054         }
   81055       }
   81056       if( pFarg ){
   81057         if( constMask ){
   81058           r1 = pParse->nMem+1;
   81059           pParse->nMem += nFarg;
   81060         }else{
   81061           r1 = sqlite3GetTempRange(pParse, nFarg);
   81062         }
   81063 
   81064         /* For length() and typeof() functions with a column argument,
   81065         ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
   81066         ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
   81067         ** loading.
   81068         */
   81069         if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
   81070           u8 exprOp;
   81071           assert( nFarg==1 );
   81072           assert( pFarg->a[0].pExpr!=0 );
   81073           exprOp = pFarg->a[0].pExpr->op;
   81074           if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
   81075             assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
   81076             assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
   81077             testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
   81078             pFarg->a[0].pExpr->op2 =
   81079                   pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
   81080           }
   81081         }
   81082 
   81083         sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
   81084         sqlite3ExprCodeExprList(pParse, pFarg, r1,
   81085                                 SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
   81086         sqlite3ExprCachePop(pParse);      /* Ticket 2ea2425d34be */
   81087       }else{
   81088         r1 = 0;
   81089       }
   81090 #ifndef SQLITE_OMIT_VIRTUALTABLE
   81091       /* Possibly overload the function if the first argument is
   81092       ** a virtual table column.
   81093       **
   81094       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
   81095       ** second argument, not the first, as the argument to test to
   81096       ** see if it is a column in a virtual table.  This is done because
   81097       ** the left operand of infix functions (the operand we want to
   81098       ** control overloading) ends up as the second argument to the
   81099       ** function.  The expression "A glob B" is equivalent to
   81100       ** "glob(B,A).  We want to use the A in "A glob B" to test
   81101       ** for function overloading.  But we use the B term in "glob(B,A)".
   81102       */
   81103       if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
   81104         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
   81105       }else if( nFarg>0 ){
   81106         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
   81107       }
   81108 #endif
   81109       if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
   81110         if( !pColl ) pColl = db->pDfltColl;
   81111         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
   81112       }
   81113       sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
   81114                         (char*)pDef, P4_FUNCDEF);
   81115       sqlite3VdbeChangeP5(v, (u8)nFarg);
   81116       if( nFarg && constMask==0 ){
   81117         sqlite3ReleaseTempRange(pParse, r1, nFarg);
   81118       }
   81119       break;
   81120     }
   81121 #ifndef SQLITE_OMIT_SUBQUERY
   81122     case TK_EXISTS:
   81123     case TK_SELECT: {
   81124       testcase( op==TK_EXISTS );
   81125       testcase( op==TK_SELECT );
   81126       inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
   81127       break;
   81128     }
   81129     case TK_IN: {
   81130       int destIfFalse = sqlite3VdbeMakeLabel(v);
   81131       int destIfNull = sqlite3VdbeMakeLabel(v);
   81132       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
   81133       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
   81134       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
   81135       sqlite3VdbeResolveLabel(v, destIfFalse);
   81136       sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
   81137       sqlite3VdbeResolveLabel(v, destIfNull);
   81138       break;
   81139     }
   81140 #endif /* SQLITE_OMIT_SUBQUERY */
   81141 
   81142 
   81143     /*
   81144     **    x BETWEEN y AND z
   81145     **
   81146     ** This is equivalent to
   81147     **
   81148     **    x>=y AND x<=z
   81149     **
   81150     ** X is stored in pExpr->pLeft.
   81151     ** Y is stored in pExpr->pList->a[0].pExpr.
   81152     ** Z is stored in pExpr->pList->a[1].pExpr.
   81153     */
   81154     case TK_BETWEEN: {
   81155       Expr *pLeft = pExpr->pLeft;
   81156       struct ExprList_item *pLItem = pExpr->x.pList->a;
   81157       Expr *pRight = pLItem->pExpr;
   81158 
   81159       r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
   81160       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
   81161       testcase( regFree1==0 );
   81162       testcase( regFree2==0 );
   81163       r3 = sqlite3GetTempReg(pParse);
   81164       r4 = sqlite3GetTempReg(pParse);
   81165       codeCompare(pParse, pLeft, pRight, OP_Ge,
   81166                   r1, r2, r3, SQLITE_STOREP2);  VdbeCoverage(v);
   81167       pLItem++;
   81168       pRight = pLItem->pExpr;
   81169       sqlite3ReleaseTempReg(pParse, regFree2);
   81170       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
   81171       testcase( regFree2==0 );
   81172       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
   81173       VdbeCoverage(v);
   81174       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
   81175       sqlite3ReleaseTempReg(pParse, r3);
   81176       sqlite3ReleaseTempReg(pParse, r4);
   81177       break;
   81178     }
   81179     case TK_COLLATE:
   81180     case TK_UPLUS: {
   81181       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
   81182       break;
   81183     }
   81184 
   81185     case TK_TRIGGER: {
   81186       /* If the opcode is TK_TRIGGER, then the expression is a reference
   81187       ** to a column in the new.* or old.* pseudo-tables available to
   81188       ** trigger programs. In this case Expr.iTable is set to 1 for the
   81189       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
   81190       ** is set to the column of the pseudo-table to read, or to -1 to
   81191       ** read the rowid field.
   81192       **
   81193       ** The expression is implemented using an OP_Param opcode. The p1
   81194       ** parameter is set to 0 for an old.rowid reference, or to (i+1)
   81195       ** to reference another column of the old.* pseudo-table, where
   81196       ** i is the index of the column. For a new.rowid reference, p1 is
   81197       ** set to (n+1), where n is the number of columns in each pseudo-table.
   81198       ** For a reference to any other column in the new.* pseudo-table, p1
   81199       ** is set to (n+2+i), where n and i are as defined previously. For
   81200       ** example, if the table on which triggers are being fired is
   81201       ** declared as:
   81202       **
   81203       **   CREATE TABLE t1(a, b);
   81204       **
   81205       ** Then p1 is interpreted as follows:
   81206       **
   81207       **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
   81208       **   p1==1   ->    old.a         p1==4   ->    new.a
   81209       **   p1==2   ->    old.b         p1==5   ->    new.b
   81210       */
   81211       Table *pTab = pExpr->pTab;
   81212       int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
   81213 
   81214       assert( pExpr->iTable==0 || pExpr->iTable==1 );
   81215       assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
   81216       assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
   81217       assert( p1>=0 && p1<(pTab->nCol*2+2) );
   81218 
   81219       sqlite3VdbeAddOp2(v, OP_Param, p1, target);
   81220       VdbeComment((v, "%s.%s -> $%d",
   81221         (pExpr->iTable ? "new" : "old"),
   81222         (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
   81223         target
   81224       ));
   81225 
   81226 #ifndef SQLITE_OMIT_FLOATING_POINT
   81227       /* If the column has REAL affinity, it may currently be stored as an
   81228       ** integer. Use OP_RealAffinity to make sure it is really real.  */
   81229       if( pExpr->iColumn>=0
   81230        && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
   81231       ){
   81232         sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
   81233       }
   81234 #endif
   81235       break;
   81236     }
   81237 
   81238 
   81239     /*
   81240     ** Form A:
   81241     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
   81242     **
   81243     ** Form B:
   81244     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
   81245     **
   81246     ** Form A is can be transformed into the equivalent form B as follows:
   81247     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
   81248     **        WHEN x=eN THEN rN ELSE y END
   81249     **
   81250     ** X (if it exists) is in pExpr->pLeft.
   81251     ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
   81252     ** odd.  The Y is also optional.  If the number of elements in x.pList
   81253     ** is even, then Y is omitted and the "otherwise" result is NULL.
   81254     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
   81255     **
   81256     ** The result of the expression is the Ri for the first matching Ei,
   81257     ** or if there is no matching Ei, the ELSE term Y, or if there is
   81258     ** no ELSE term, NULL.
   81259     */
   81260     default: assert( op==TK_CASE ); {
   81261       int endLabel;                     /* GOTO label for end of CASE stmt */
   81262       int nextCase;                     /* GOTO label for next WHEN clause */
   81263       int nExpr;                        /* 2x number of WHEN terms */
   81264       int i;                            /* Loop counter */
   81265       ExprList *pEList;                 /* List of WHEN terms */
   81266       struct ExprList_item *aListelem;  /* Array of WHEN terms */
   81267       Expr opCompare;                   /* The X==Ei expression */
   81268       Expr *pX;                         /* The X expression */
   81269       Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
   81270       VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
   81271 
   81272       assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
   81273       assert(pExpr->x.pList->nExpr > 0);
   81274       pEList = pExpr->x.pList;
   81275       aListelem = pEList->a;
   81276       nExpr = pEList->nExpr;
   81277       endLabel = sqlite3VdbeMakeLabel(v);
   81278       if( (pX = pExpr->pLeft)!=0 ){
   81279         tempX = *pX;
   81280         testcase( pX->op==TK_COLUMN );
   81281         exprToRegister(&tempX, sqlite3ExprCodeTemp(pParse, pX, &regFree1));
   81282         testcase( regFree1==0 );
   81283         opCompare.op = TK_EQ;
   81284         opCompare.pLeft = &tempX;
   81285         pTest = &opCompare;
   81286         /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
   81287         ** The value in regFree1 might get SCopy-ed into the file result.
   81288         ** So make sure that the regFree1 register is not reused for other
   81289         ** purposes and possibly overwritten.  */
   81290         regFree1 = 0;
   81291       }
   81292       for(i=0; i<nExpr-1; i=i+2){
   81293         sqlite3ExprCachePush(pParse);
   81294         if( pX ){
   81295           assert( pTest!=0 );
   81296           opCompare.pRight = aListelem[i].pExpr;
   81297         }else{
   81298           pTest = aListelem[i].pExpr;
   81299         }
   81300         nextCase = sqlite3VdbeMakeLabel(v);
   81301         testcase( pTest->op==TK_COLUMN );
   81302         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
   81303         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
   81304         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
   81305         sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
   81306         sqlite3ExprCachePop(pParse);
   81307         sqlite3VdbeResolveLabel(v, nextCase);
   81308       }
   81309       if( (nExpr&1)!=0 ){
   81310         sqlite3ExprCachePush(pParse);
   81311         sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
   81312         sqlite3ExprCachePop(pParse);
   81313       }else{
   81314         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
   81315       }
   81316       assert( db->mallocFailed || pParse->nErr>0
   81317            || pParse->iCacheLevel==iCacheLevel );
   81318       sqlite3VdbeResolveLabel(v, endLabel);
   81319       break;
   81320     }
   81321 #ifndef SQLITE_OMIT_TRIGGER
   81322     case TK_RAISE: {
   81323       assert( pExpr->affinity==OE_Rollback
   81324            || pExpr->affinity==OE_Abort
   81325            || pExpr->affinity==OE_Fail
   81326            || pExpr->affinity==OE_Ignore
   81327       );
   81328       if( !pParse->pTriggerTab ){
   81329         sqlite3ErrorMsg(pParse,
   81330                        "RAISE() may only be used within a trigger-program");
   81331         return 0;
   81332       }
   81333       if( pExpr->affinity==OE_Abort ){
   81334         sqlite3MayAbort(pParse);
   81335       }
   81336       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   81337       if( pExpr->affinity==OE_Ignore ){
   81338         sqlite3VdbeAddOp4(
   81339             v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
   81340         VdbeCoverage(v);
   81341       }else{
   81342         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
   81343                               pExpr->affinity, pExpr->u.zToken, 0, 0);
   81344       }
   81345 
   81346       break;
   81347     }
   81348 #endif
   81349   }
   81350   sqlite3ReleaseTempReg(pParse, regFree1);
   81351   sqlite3ReleaseTempReg(pParse, regFree2);
   81352   return inReg;
   81353 }
   81354 
   81355 /*
   81356 ** Factor out the code of the given expression to initialization time.
   81357 */
   81358 SQLITE_PRIVATE void sqlite3ExprCodeAtInit(
   81359   Parse *pParse,    /* Parsing context */
   81360   Expr *pExpr,      /* The expression to code when the VDBE initializes */
   81361   int regDest,      /* Store the value in this register */
   81362   u8 reusable       /* True if this expression is reusable */
   81363 ){
   81364   ExprList *p;
   81365   assert( ConstFactorOk(pParse) );
   81366   p = pParse->pConstExpr;
   81367   pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
   81368   p = sqlite3ExprListAppend(pParse, p, pExpr);
   81369   if( p ){
   81370      struct ExprList_item *pItem = &p->a[p->nExpr-1];
   81371      pItem->u.iConstExprReg = regDest;
   81372      pItem->reusable = reusable;
   81373   }
   81374   pParse->pConstExpr = p;
   81375 }
   81376 
   81377 /*
   81378 ** Generate code to evaluate an expression and store the results
   81379 ** into a register.  Return the register number where the results
   81380 ** are stored.
   81381 **
   81382 ** If the register is a temporary register that can be deallocated,
   81383 ** then write its number into *pReg.  If the result register is not
   81384 ** a temporary, then set *pReg to zero.
   81385 **
   81386 ** If pExpr is a constant, then this routine might generate this
   81387 ** code to fill the register in the initialization section of the
   81388 ** VDBE program, in order to factor it out of the evaluation loop.
   81389 */
   81390 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
   81391   int r2;
   81392   pExpr = sqlite3ExprSkipCollate(pExpr);
   81393   if( ConstFactorOk(pParse)
   81394    && pExpr->op!=TK_REGISTER
   81395    && sqlite3ExprIsConstantNotJoin(pExpr)
   81396   ){
   81397     ExprList *p = pParse->pConstExpr;
   81398     int i;
   81399     *pReg  = 0;
   81400     if( p ){
   81401       struct ExprList_item *pItem;
   81402       for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
   81403         if( pItem->reusable && sqlite3ExprCompare(pItem->pExpr,pExpr,-1)==0 ){
   81404           return pItem->u.iConstExprReg;
   81405         }
   81406       }
   81407     }
   81408     r2 = ++pParse->nMem;
   81409     sqlite3ExprCodeAtInit(pParse, pExpr, r2, 1);
   81410   }else{
   81411     int r1 = sqlite3GetTempReg(pParse);
   81412     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
   81413     if( r2==r1 ){
   81414       *pReg = r1;
   81415     }else{
   81416       sqlite3ReleaseTempReg(pParse, r1);
   81417       *pReg = 0;
   81418     }
   81419   }
   81420   return r2;
   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.
   81427 */
   81428 SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
   81429   int inReg;
   81430 
   81431   assert( target>0 && target<=pParse->nMem );
   81432   if( pExpr && pExpr->op==TK_REGISTER ){
   81433     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
   81434   }else{
   81435     inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
   81436     assert( pParse->pVdbe || pParse->db->mallocFailed );
   81437     if( inReg!=target && pParse->pVdbe ){
   81438       sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
   81439     }
   81440   }
   81441 }
   81442 
   81443 /*
   81444 ** Generate code that will evaluate expression pExpr and store the
   81445 ** results in register target.  The results are guaranteed to appear
   81446 ** in register target.  If the expression is constant, then this routine
   81447 ** might choose to code the expression at initialization time.
   81448 */
   81449 SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
   81450   if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
   81451     sqlite3ExprCodeAtInit(pParse, pExpr, target, 0);
   81452   }else{
   81453     sqlite3ExprCode(pParse, pExpr, target);
   81454   }
   81455 }
   81456 
   81457 /*
   81458 ** Generate code that evalutes the given expression and puts the result
   81459 ** in register target.
   81460 **
   81461 ** Also make a copy of the expression results into another "cache" register
   81462 ** and modify the expression so that the next time it is evaluated,
   81463 ** the result is a copy of the cache register.
   81464 **
   81465 ** This routine is used for expressions that are used multiple
   81466 ** times.  They are evaluated once and the results of the expression
   81467 ** are reused.
   81468 */
   81469 SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
   81470   Vdbe *v = pParse->pVdbe;
   81471   int iMem;
   81472 
   81473   assert( target>0 );
   81474   assert( pExpr->op!=TK_REGISTER );
   81475   sqlite3ExprCode(pParse, pExpr, target);
   81476   iMem = ++pParse->nMem;
   81477   sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
   81478   exprToRegister(pExpr, iMem);
   81479 }
   81480 
   81481 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
   81482 /*
   81483 ** Generate a human-readable explanation of an expression tree.
   81484 */
   81485 SQLITE_PRIVATE void sqlite3ExplainExpr(Vdbe *pOut, Expr *pExpr){
   81486   int op;                   /* The opcode being coded */
   81487   const char *zBinOp = 0;   /* Binary operator */
   81488   const char *zUniOp = 0;   /* Unary operator */
   81489   if( pExpr==0 ){
   81490     op = TK_NULL;
   81491   }else{
   81492     op = pExpr->op;
   81493   }
   81494   switch( op ){
   81495     case TK_AGG_COLUMN: {
   81496       sqlite3ExplainPrintf(pOut, "AGG{%d:%d}",
   81497             pExpr->iTable, pExpr->iColumn);
   81498       break;
   81499     }
   81500     case TK_COLUMN: {
   81501       if( pExpr->iTable<0 ){
   81502         /* This only happens when coding check constraints */
   81503         sqlite3ExplainPrintf(pOut, "COLUMN(%d)", pExpr->iColumn);
   81504       }else{
   81505         sqlite3ExplainPrintf(pOut, "{%d:%d}",
   81506                              pExpr->iTable, pExpr->iColumn);
   81507       }
   81508       break;
   81509     }
   81510     case TK_INTEGER: {
   81511       if( pExpr->flags & EP_IntValue ){
   81512         sqlite3ExplainPrintf(pOut, "%d", pExpr->u.iValue);
   81513       }else{
   81514         sqlite3ExplainPrintf(pOut, "%s", pExpr->u.zToken);
   81515       }
   81516       break;
   81517     }
   81518 #ifndef SQLITE_OMIT_FLOATING_POINT
   81519     case TK_FLOAT: {
   81520       sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
   81521       break;
   81522     }
   81523 #endif
   81524     case TK_STRING: {
   81525       sqlite3ExplainPrintf(pOut,"%Q", pExpr->u.zToken);
   81526       break;
   81527     }
   81528     case TK_NULL: {
   81529       sqlite3ExplainPrintf(pOut,"NULL");
   81530       break;
   81531     }
   81532 #ifndef SQLITE_OMIT_BLOB_LITERAL
   81533     case TK_BLOB: {
   81534       sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
   81535       break;
   81536     }
   81537 #endif
   81538     case TK_VARIABLE: {
   81539       sqlite3ExplainPrintf(pOut,"VARIABLE(%s,%d)",
   81540                            pExpr->u.zToken, pExpr->iColumn);
   81541       break;
   81542     }
   81543     case TK_REGISTER: {
   81544       sqlite3ExplainPrintf(pOut,"REGISTER(%d)", pExpr->iTable);
   81545       break;
   81546     }
   81547     case TK_AS: {
   81548       sqlite3ExplainExpr(pOut, pExpr->pLeft);
   81549       break;
   81550     }
   81551 #ifndef SQLITE_OMIT_CAST
   81552     case TK_CAST: {
   81553       /* Expressions of the form:   CAST(pLeft AS token) */
   81554       const char *zAff = "unk";
   81555       switch( sqlite3AffinityType(pExpr->u.zToken, 0) ){
   81556         case SQLITE_AFF_TEXT:    zAff = "TEXT";     break;
   81557         case SQLITE_AFF_NONE:    zAff = "NONE";     break;
   81558         case SQLITE_AFF_NUMERIC: zAff = "NUMERIC";  break;
   81559         case SQLITE_AFF_INTEGER: zAff = "INTEGER";  break;
   81560         case SQLITE_AFF_REAL:    zAff = "REAL";     break;
   81561       }
   81562       sqlite3ExplainPrintf(pOut, "CAST-%s(", zAff);
   81563       sqlite3ExplainExpr(pOut, pExpr->pLeft);
   81564       sqlite3ExplainPrintf(pOut, ")");
   81565       break;
   81566     }
   81567 #endif /* SQLITE_OMIT_CAST */
   81568     case TK_LT:      zBinOp = "LT";     break;
   81569     case TK_LE:      zBinOp = "LE";     break;
   81570     case TK_GT:      zBinOp = "GT";     break;
   81571     case TK_GE:      zBinOp = "GE";     break;
   81572     case TK_NE:      zBinOp = "NE";     break;
   81573     case TK_EQ:      zBinOp = "EQ";     break;
   81574     case TK_IS:      zBinOp = "IS";     break;
   81575     case TK_ISNOT:   zBinOp = "ISNOT";  break;
   81576     case TK_AND:     zBinOp = "AND";    break;
   81577     case TK_OR:      zBinOp = "OR";     break;
   81578     case TK_PLUS:    zBinOp = "ADD";    break;
   81579     case TK_STAR:    zBinOp = "MUL";    break;
   81580     case TK_MINUS:   zBinOp = "SUB";    break;
   81581     case TK_REM:     zBinOp = "REM";    break;
   81582     case TK_BITAND:  zBinOp = "BITAND"; break;
   81583     case TK_BITOR:   zBinOp = "BITOR";  break;
   81584     case TK_SLASH:   zBinOp = "DIV";    break;
   81585     case TK_LSHIFT:  zBinOp = "LSHIFT"; break;
   81586     case TK_RSHIFT:  zBinOp = "RSHIFT"; break;
   81587     case TK_CONCAT:  zBinOp = "CONCAT"; break;
   81588 
   81589     case TK_UMINUS:  zUniOp = "UMINUS"; break;
   81590     case TK_UPLUS:   zUniOp = "UPLUS";  break;
   81591     case TK_BITNOT:  zUniOp = "BITNOT"; break;
   81592     case TK_NOT:     zUniOp = "NOT";    break;
   81593     case TK_ISNULL:  zUniOp = "ISNULL"; break;
   81594     case TK_NOTNULL: zUniOp = "NOTNULL"; break;
   81595 
   81596     case TK_COLLATE: {
   81597       sqlite3ExplainExpr(pOut, pExpr->pLeft);
   81598       sqlite3ExplainPrintf(pOut,".COLLATE(%s)",pExpr->u.zToken);
   81599       break;
   81600     }
   81601 
   81602     case TK_AGG_FUNCTION:
   81603     case TK_FUNCTION: {
   81604       ExprList *pFarg;       /* List of function arguments */
   81605       if( ExprHasProperty(pExpr, EP_TokenOnly) ){
   81606         pFarg = 0;
   81607       }else{
   81608         pFarg = pExpr->x.pList;
   81609       }
   81610       if( op==TK_AGG_FUNCTION ){
   81611         sqlite3ExplainPrintf(pOut, "AGG_FUNCTION%d:%s(",
   81612                              pExpr->op2, pExpr->u.zToken);
   81613       }else{
   81614         sqlite3ExplainPrintf(pOut, "FUNCTION:%s(", pExpr->u.zToken);
   81615       }
   81616       if( pFarg ){
   81617         sqlite3ExplainExprList(pOut, pFarg);
   81618       }
   81619       sqlite3ExplainPrintf(pOut, ")");
   81620       break;
   81621     }
   81622 #ifndef SQLITE_OMIT_SUBQUERY
   81623     case TK_EXISTS: {
   81624       sqlite3ExplainPrintf(pOut, "EXISTS(");
   81625       sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
   81626       sqlite3ExplainPrintf(pOut,")");
   81627       break;
   81628     }
   81629     case TK_SELECT: {
   81630       sqlite3ExplainPrintf(pOut, "(");
   81631       sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
   81632       sqlite3ExplainPrintf(pOut, ")");
   81633       break;
   81634     }
   81635     case TK_IN: {
   81636       sqlite3ExplainPrintf(pOut, "IN(");
   81637       sqlite3ExplainExpr(pOut, pExpr->pLeft);
   81638       sqlite3ExplainPrintf(pOut, ",");
   81639       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   81640         sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
   81641       }else{
   81642         sqlite3ExplainExprList(pOut, pExpr->x.pList);
   81643       }
   81644       sqlite3ExplainPrintf(pOut, ")");
   81645       break;
   81646     }
   81647 #endif /* SQLITE_OMIT_SUBQUERY */
   81648 
   81649     /*
   81650     **    x BETWEEN y AND z
   81651     **
   81652     ** This is equivalent to
   81653     **
   81654     **    x>=y AND x<=z
   81655     **
   81656     ** X is stored in pExpr->pLeft.
   81657     ** Y is stored in pExpr->pList->a[0].pExpr.
   81658     ** Z is stored in pExpr->pList->a[1].pExpr.
   81659     */
   81660     case TK_BETWEEN: {
   81661       Expr *pX = pExpr->pLeft;
   81662       Expr *pY = pExpr->x.pList->a[0].pExpr;
   81663       Expr *pZ = pExpr->x.pList->a[1].pExpr;
   81664       sqlite3ExplainPrintf(pOut, "BETWEEN(");
   81665       sqlite3ExplainExpr(pOut, pX);
   81666       sqlite3ExplainPrintf(pOut, ",");
   81667       sqlite3ExplainExpr(pOut, pY);
   81668       sqlite3ExplainPrintf(pOut, ",");
   81669       sqlite3ExplainExpr(pOut, pZ);
   81670       sqlite3ExplainPrintf(pOut, ")");
   81671       break;
   81672     }
   81673     case TK_TRIGGER: {
   81674       /* If the opcode is TK_TRIGGER, then the expression is a reference
   81675       ** to a column in the new.* or old.* pseudo-tables available to
   81676       ** trigger programs. In this case Expr.iTable is set to 1 for the
   81677       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
   81678       ** is set to the column of the pseudo-table to read, or to -1 to
   81679       ** read the rowid field.
   81680       */
   81681       sqlite3ExplainPrintf(pOut, "%s(%d)",
   81682           pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
   81683       break;
   81684     }
   81685     case TK_CASE: {
   81686       sqlite3ExplainPrintf(pOut, "CASE(");
   81687       sqlite3ExplainExpr(pOut, pExpr->pLeft);
   81688       sqlite3ExplainPrintf(pOut, ",");
   81689       sqlite3ExplainExprList(pOut, pExpr->x.pList);
   81690       break;
   81691     }
   81692 #ifndef SQLITE_OMIT_TRIGGER
   81693     case TK_RAISE: {
   81694       const char *zType = "unk";
   81695       switch( pExpr->affinity ){
   81696         case OE_Rollback:   zType = "rollback";  break;
   81697         case OE_Abort:      zType = "abort";     break;
   81698         case OE_Fail:       zType = "fail";      break;
   81699         case OE_Ignore:     zType = "ignore";    break;
   81700       }
   81701       sqlite3ExplainPrintf(pOut, "RAISE-%s(%s)", zType, pExpr->u.zToken);
   81702       break;
   81703     }
   81704 #endif
   81705   }
   81706   if( zBinOp ){
   81707     sqlite3ExplainPrintf(pOut,"%s(", zBinOp);
   81708     sqlite3ExplainExpr(pOut, pExpr->pLeft);
   81709     sqlite3ExplainPrintf(pOut,",");
   81710     sqlite3ExplainExpr(pOut, pExpr->pRight);
   81711     sqlite3ExplainPrintf(pOut,")");
   81712   }else if( zUniOp ){
   81713     sqlite3ExplainPrintf(pOut,"%s(", zUniOp);
   81714     sqlite3ExplainExpr(pOut, pExpr->pLeft);
   81715     sqlite3ExplainPrintf(pOut,")");
   81716   }
   81717 }
   81718 #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
   81719 
   81720 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
   81721 /*
   81722 ** Generate a human-readable explanation of an expression list.
   81723 */
   81724 SQLITE_PRIVATE void sqlite3ExplainExprList(Vdbe *pOut, ExprList *pList){
   81725   int i;
   81726   if( pList==0 || pList->nExpr==0 ){
   81727     sqlite3ExplainPrintf(pOut, "(empty-list)");
   81728     return;
   81729   }else if( pList->nExpr==1 ){
   81730     sqlite3ExplainExpr(pOut, pList->a[0].pExpr);
   81731   }else{
   81732     sqlite3ExplainPush(pOut);
   81733     for(i=0; i<pList->nExpr; i++){
   81734       sqlite3ExplainPrintf(pOut, "item[%d] = ", i);
   81735       sqlite3ExplainPush(pOut);
   81736       sqlite3ExplainExpr(pOut, pList->a[i].pExpr);
   81737       sqlite3ExplainPop(pOut);
   81738       if( pList->a[i].zName ){
   81739         sqlite3ExplainPrintf(pOut, " AS %s", pList->a[i].zName);
   81740       }
   81741       if( pList->a[i].bSpanIsTab ){
   81742         sqlite3ExplainPrintf(pOut, " (%s)", pList->a[i].zSpan);
   81743       }
   81744       if( i<pList->nExpr-1 ){
   81745         sqlite3ExplainNL(pOut);
   81746       }
   81747     }
   81748     sqlite3ExplainPop(pOut);
   81749   }
   81750 }
   81751 #endif /* SQLITE_DEBUG */
   81752 
   81753 /*
   81754 ** Generate code that pushes the value of every element of the given
   81755 ** expression list into a sequence of registers beginning at target.
   81756 **
   81757 ** Return the number of elements evaluated.
   81758 **
   81759 ** The SQLITE_ECEL_DUP flag prevents the arguments from being
   81760 ** filled using OP_SCopy.  OP_Copy must be used instead.
   81761 **
   81762 ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
   81763 ** factored out into initialization code.
   81764 */
   81765 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
   81766   Parse *pParse,     /* Parsing context */
   81767   ExprList *pList,   /* The expression list to be coded */
   81768   int target,        /* Where to write results */
   81769   u8 flags           /* SQLITE_ECEL_* flags */
   81770 ){
   81771   struct ExprList_item *pItem;
   81772   int i, n;
   81773   u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
   81774   assert( pList!=0 );
   81775   assert( target>0 );
   81776   assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
   81777   n = pList->nExpr;
   81778   if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
   81779   for(pItem=pList->a, i=0; i<n; i++, pItem++){
   81780     Expr *pExpr = pItem->pExpr;
   81781     if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
   81782       sqlite3ExprCodeAtInit(pParse, pExpr, target+i, 0);
   81783     }else{
   81784       int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
   81785       if( inReg!=target+i ){
   81786         VdbeOp *pOp;
   81787         Vdbe *v = pParse->pVdbe;
   81788         if( copyOp==OP_Copy
   81789          && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
   81790          && pOp->p1+pOp->p3+1==inReg
   81791          && pOp->p2+pOp->p3+1==target+i
   81792         ){
   81793           pOp->p3++;
   81794         }else{
   81795           sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
   81796         }
   81797       }
   81798     }
   81799   }
   81800   return n;
   81801 }
   81802 
   81803 /*
   81804 ** Generate code for a BETWEEN operator.
   81805 **
   81806 **    x BETWEEN y AND z
   81807 **
   81808 ** The above is equivalent to
   81809 **
   81810 **    x>=y AND x<=z
   81811 **
   81812 ** Code it as such, taking care to do the common subexpression
   81813 ** elementation of x.
   81814 */
   81815 static void exprCodeBetween(
   81816   Parse *pParse,    /* Parsing and code generating context */
   81817   Expr *pExpr,      /* The BETWEEN expression */
   81818   int dest,         /* Jump here if the jump is taken */
   81819   int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
   81820   int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
   81821 ){
   81822   Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
   81823   Expr compLeft;    /* The  x>=y  term */
   81824   Expr compRight;   /* The  x<=z  term */
   81825   Expr exprX;       /* The  x  subexpression */
   81826   int regFree1 = 0; /* Temporary use register */
   81827 
   81828   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   81829   exprX = *pExpr->pLeft;
   81830   exprAnd.op = TK_AND;
   81831   exprAnd.pLeft = &compLeft;
   81832   exprAnd.pRight = &compRight;
   81833   compLeft.op = TK_GE;
   81834   compLeft.pLeft = &exprX;
   81835   compLeft.pRight = pExpr->x.pList->a[0].pExpr;
   81836   compRight.op = TK_LE;
   81837   compRight.pLeft = &exprX;
   81838   compRight.pRight = pExpr->x.pList->a[1].pExpr;
   81839   exprToRegister(&exprX, sqlite3ExprCodeTemp(pParse, &exprX, &regFree1));
   81840   if( jumpIfTrue ){
   81841     sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
   81842   }else{
   81843     sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
   81844   }
   81845   sqlite3ReleaseTempReg(pParse, regFree1);
   81846 
   81847   /* Ensure adequate test coverage */
   81848   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
   81849   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
   81850   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
   81851   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
   81852   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
   81853   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
   81854   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
   81855   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
   81856 }
   81857 
   81858 /*
   81859 ** Generate code for a boolean expression such that a jump is made
   81860 ** to the label "dest" if the expression is true but execution
   81861 ** continues straight thru if the expression is false.
   81862 **
   81863 ** If the expression evaluates to NULL (neither true nor false), then
   81864 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
   81865 **
   81866 ** This code depends on the fact that certain token values (ex: TK_EQ)
   81867 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
   81868 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
   81869 ** the make process cause these values to align.  Assert()s in the code
   81870 ** below verify that the numbers are aligned correctly.
   81871 */
   81872 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
   81873   Vdbe *v = pParse->pVdbe;
   81874   int op = 0;
   81875   int regFree1 = 0;
   81876   int regFree2 = 0;
   81877   int r1, r2;
   81878 
   81879   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
   81880   if( NEVER(v==0) )     return;  /* Existence of VDBE checked by caller */
   81881   if( NEVER(pExpr==0) ) return;  /* No way this can happen */
   81882   op = pExpr->op;
   81883   switch( op ){
   81884     case TK_AND: {
   81885       int d2 = sqlite3VdbeMakeLabel(v);
   81886       testcase( jumpIfNull==0 );
   81887       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
   81888       sqlite3ExprCachePush(pParse);
   81889       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
   81890       sqlite3VdbeResolveLabel(v, d2);
   81891       sqlite3ExprCachePop(pParse);
   81892       break;
   81893     }
   81894     case TK_OR: {
   81895       testcase( jumpIfNull==0 );
   81896       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
   81897       sqlite3ExprCachePush(pParse);
   81898       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
   81899       sqlite3ExprCachePop(pParse);
   81900       break;
   81901     }
   81902     case TK_NOT: {
   81903       testcase( jumpIfNull==0 );
   81904       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
   81905       break;
   81906     }
   81907     case TK_LT:
   81908     case TK_LE:
   81909     case TK_GT:
   81910     case TK_GE:
   81911     case TK_NE:
   81912     case TK_EQ: {
   81913       testcase( jumpIfNull==0 );
   81914       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   81915       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   81916       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
   81917                   r1, r2, dest, jumpIfNull);
   81918       assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
   81919       assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
   81920       assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
   81921       assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
   81922       assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
   81923       assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
   81924       testcase( regFree1==0 );
   81925       testcase( regFree2==0 );
   81926       break;
   81927     }
   81928     case TK_IS:
   81929     case TK_ISNOT: {
   81930       testcase( op==TK_IS );
   81931       testcase( op==TK_ISNOT );
   81932       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   81933       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   81934       op = (op==TK_IS) ? TK_EQ : TK_NE;
   81935       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
   81936                   r1, r2, dest, SQLITE_NULLEQ);
   81937       VdbeCoverageIf(v, op==TK_EQ);
   81938       VdbeCoverageIf(v, op==TK_NE);
   81939       testcase( regFree1==0 );
   81940       testcase( regFree2==0 );
   81941       break;
   81942     }
   81943     case TK_ISNULL:
   81944     case TK_NOTNULL: {
   81945       assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
   81946       assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
   81947       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   81948       sqlite3VdbeAddOp2(v, op, r1, dest);
   81949       VdbeCoverageIf(v, op==TK_ISNULL);
   81950       VdbeCoverageIf(v, op==TK_NOTNULL);
   81951       testcase( regFree1==0 );
   81952       break;
   81953     }
   81954     case TK_BETWEEN: {
   81955       testcase( jumpIfNull==0 );
   81956       exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
   81957       break;
   81958     }
   81959 #ifndef SQLITE_OMIT_SUBQUERY
   81960     case TK_IN: {
   81961       int destIfFalse = sqlite3VdbeMakeLabel(v);
   81962       int destIfNull = jumpIfNull ? dest : destIfFalse;
   81963       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
   81964       sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
   81965       sqlite3VdbeResolveLabel(v, destIfFalse);
   81966       break;
   81967     }
   81968 #endif
   81969     default: {
   81970       if( exprAlwaysTrue(pExpr) ){
   81971         sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
   81972       }else if( exprAlwaysFalse(pExpr) ){
   81973         /* No-op */
   81974       }else{
   81975         r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
   81976         sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
   81977         VdbeCoverage(v);
   81978         testcase( regFree1==0 );
   81979         testcase( jumpIfNull==0 );
   81980       }
   81981       break;
   81982     }
   81983   }
   81984   sqlite3ReleaseTempReg(pParse, regFree1);
   81985   sqlite3ReleaseTempReg(pParse, regFree2);
   81986 }
   81987 
   81988 /*
   81989 ** Generate code for a boolean expression such that a jump is made
   81990 ** to the label "dest" if the expression is false but execution
   81991 ** continues straight thru if the expression is true.
   81992 **
   81993 ** If the expression evaluates to NULL (neither true nor false) then
   81994 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
   81995 ** is 0.
   81996 */
   81997 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
   81998   Vdbe *v = pParse->pVdbe;
   81999   int op = 0;
   82000   int regFree1 = 0;
   82001   int regFree2 = 0;
   82002   int r1, r2;
   82003 
   82004   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
   82005   if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
   82006   if( pExpr==0 )    return;
   82007 
   82008   /* The value of pExpr->op and op are related as follows:
   82009   **
   82010   **       pExpr->op            op
   82011   **       ---------          ----------
   82012   **       TK_ISNULL          OP_NotNull
   82013   **       TK_NOTNULL         OP_IsNull
   82014   **       TK_NE              OP_Eq
   82015   **       TK_EQ              OP_Ne
   82016   **       TK_GT              OP_Le
   82017   **       TK_LE              OP_Gt
   82018   **       TK_GE              OP_Lt
   82019   **       TK_LT              OP_Ge
   82020   **
   82021   ** For other values of pExpr->op, op is undefined and unused.
   82022   ** The value of TK_ and OP_ constants are arranged such that we
   82023   ** can compute the mapping above using the following expression.
   82024   ** Assert()s verify that the computation is correct.
   82025   */
   82026   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
   82027 
   82028   /* Verify correct alignment of TK_ and OP_ constants
   82029   */
   82030   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
   82031   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
   82032   assert( pExpr->op!=TK_NE || op==OP_Eq );
   82033   assert( pExpr->op!=TK_EQ || op==OP_Ne );
   82034   assert( pExpr->op!=TK_LT || op==OP_Ge );
   82035   assert( pExpr->op!=TK_LE || op==OP_Gt );
   82036   assert( pExpr->op!=TK_GT || op==OP_Le );
   82037   assert( pExpr->op!=TK_GE || op==OP_Lt );
   82038 
   82039   switch( pExpr->op ){
   82040     case TK_AND: {
   82041       testcase( jumpIfNull==0 );
   82042       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
   82043       sqlite3ExprCachePush(pParse);
   82044       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
   82045       sqlite3ExprCachePop(pParse);
   82046       break;
   82047     }
   82048     case TK_OR: {
   82049       int d2 = sqlite3VdbeMakeLabel(v);
   82050       testcase( jumpIfNull==0 );
   82051       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
   82052       sqlite3ExprCachePush(pParse);
   82053       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
   82054       sqlite3VdbeResolveLabel(v, d2);
   82055       sqlite3ExprCachePop(pParse);
   82056       break;
   82057     }
   82058     case TK_NOT: {
   82059       testcase( jumpIfNull==0 );
   82060       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
   82061       break;
   82062     }
   82063     case TK_LT:
   82064     case TK_LE:
   82065     case TK_GT:
   82066     case TK_GE:
   82067     case TK_NE:
   82068     case TK_EQ: {
   82069       testcase( jumpIfNull==0 );
   82070       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   82071       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   82072       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
   82073                   r1, r2, dest, jumpIfNull);
   82074       assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
   82075       assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
   82076       assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
   82077       assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
   82078       assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
   82079       assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
   82080       testcase( regFree1==0 );
   82081       testcase( regFree2==0 );
   82082       break;
   82083     }
   82084     case TK_IS:
   82085     case TK_ISNOT: {
   82086       testcase( pExpr->op==TK_IS );
   82087       testcase( pExpr->op==TK_ISNOT );
   82088       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   82089       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   82090       op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
   82091       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
   82092                   r1, r2, dest, SQLITE_NULLEQ);
   82093       VdbeCoverageIf(v, op==TK_EQ);
   82094       VdbeCoverageIf(v, op==TK_NE);
   82095       testcase( regFree1==0 );
   82096       testcase( regFree2==0 );
   82097       break;
   82098     }
   82099     case TK_ISNULL:
   82100     case TK_NOTNULL: {
   82101       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   82102       sqlite3VdbeAddOp2(v, op, r1, dest);
   82103       testcase( op==TK_ISNULL );   VdbeCoverageIf(v, op==TK_ISNULL);
   82104       testcase( op==TK_NOTNULL );  VdbeCoverageIf(v, op==TK_NOTNULL);
   82105       testcase( regFree1==0 );
   82106       break;
   82107     }
   82108     case TK_BETWEEN: {
   82109       testcase( jumpIfNull==0 );
   82110       exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
   82111       break;
   82112     }
   82113 #ifndef SQLITE_OMIT_SUBQUERY
   82114     case TK_IN: {
   82115       if( jumpIfNull ){
   82116         sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
   82117       }else{
   82118         int destIfNull = sqlite3VdbeMakeLabel(v);
   82119         sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
   82120         sqlite3VdbeResolveLabel(v, destIfNull);
   82121       }
   82122       break;
   82123     }
   82124 #endif
   82125     default: {
   82126       if( exprAlwaysFalse(pExpr) ){
   82127         sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
   82128       }else if( exprAlwaysTrue(pExpr) ){
   82129         /* no-op */
   82130       }else{
   82131         r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
   82132         sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
   82133         VdbeCoverage(v);
   82134         testcase( regFree1==0 );
   82135         testcase( jumpIfNull==0 );
   82136       }
   82137       break;
   82138     }
   82139   }
   82140   sqlite3ReleaseTempReg(pParse, regFree1);
   82141   sqlite3ReleaseTempReg(pParse, regFree2);
   82142 }
   82143 
   82144 /*
   82145 ** Do a deep comparison of two expression trees.  Return 0 if the two
   82146 ** expressions are completely identical.  Return 1 if they differ only
   82147 ** by a COLLATE operator at the top level.  Return 2 if there are differences
   82148 ** other than the top-level COLLATE operator.
   82149 **
   82150 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
   82151 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
   82152 **
   82153 ** The pA side might be using TK_REGISTER.  If that is the case and pB is
   82154 ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
   82155 **
   82156 ** Sometimes this routine will return 2 even if the two expressions
   82157 ** really are equivalent.  If we cannot prove that the expressions are
   82158 ** identical, we return 2 just to be safe.  So if this routine
   82159 ** returns 2, then you do not really know for certain if the two
   82160 ** expressions are the same.  But if you get a 0 or 1 return, then you
   82161 ** can be sure the expressions are the same.  In the places where
   82162 ** this routine is used, it does not hurt to get an extra 2 - that
   82163 ** just might result in some slightly slower code.  But returning
   82164 ** an incorrect 0 or 1 could lead to a malfunction.
   82165 */
   82166 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
   82167   u32 combinedFlags;
   82168   if( pA==0 || pB==0 ){
   82169     return pB==pA ? 0 : 2;
   82170   }
   82171   combinedFlags = pA->flags | pB->flags;
   82172   if( combinedFlags & EP_IntValue ){
   82173     if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
   82174       return 0;
   82175     }
   82176     return 2;
   82177   }
   82178   if( pA->op!=pB->op ){
   82179     if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
   82180       return 1;
   82181     }
   82182     if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
   82183       return 1;
   82184     }
   82185     return 2;
   82186   }
   82187   if( pA->op!=TK_COLUMN && ALWAYS(pA->op!=TK_AGG_COLUMN) && pA->u.zToken ){
   82188     if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
   82189       return pA->op==TK_COLLATE ? 1 : 2;
   82190     }
   82191   }
   82192   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
   82193   if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
   82194     if( combinedFlags & EP_xIsSelect ) return 2;
   82195     if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
   82196     if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
   82197     if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
   82198     if( ALWAYS((combinedFlags & EP_Reduced)==0) ){
   82199       if( pA->iColumn!=pB->iColumn ) return 2;
   82200       if( pA->iTable!=pB->iTable
   82201        && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
   82202     }
   82203   }
   82204   return 0;
   82205 }
   82206 
   82207 /*
   82208 ** Compare two ExprList objects.  Return 0 if they are identical and
   82209 ** non-zero if they differ in any way.
   82210 **
   82211 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
   82212 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
   82213 **
   82214 ** This routine might return non-zero for equivalent ExprLists.  The
   82215 ** only consequence will be disabled optimizations.  But this routine
   82216 ** must never return 0 if the two ExprList objects are different, or
   82217 ** a malfunction will result.
   82218 **
   82219 ** Two NULL pointers are considered to be the same.  But a NULL pointer
   82220 ** always differs from a non-NULL pointer.
   82221 */
   82222 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
   82223   int i;
   82224   if( pA==0 && pB==0 ) return 0;
   82225   if( pA==0 || pB==0 ) return 1;
   82226   if( pA->nExpr!=pB->nExpr ) return 1;
   82227   for(i=0; i<pA->nExpr; i++){
   82228     Expr *pExprA = pA->a[i].pExpr;
   82229     Expr *pExprB = pB->a[i].pExpr;
   82230     if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
   82231     if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
   82232   }
   82233   return 0;
   82234 }
   82235 
   82236 /*
   82237 ** Return true if we can prove the pE2 will always be true if pE1 is
   82238 ** true.  Return false if we cannot complete the proof or if pE2 might
   82239 ** be false.  Examples:
   82240 **
   82241 **     pE1: x==5       pE2: x==5             Result: true
   82242 **     pE1: x>0        pE2: x==5             Result: false
   82243 **     pE1: x=21       pE2: x=21 OR y=43     Result: true
   82244 **     pE1: x!=123     pE2: x IS NOT NULL    Result: true
   82245 **     pE1: x!=?1      pE2: x IS NOT NULL    Result: true
   82246 **     pE1: x IS NULL  pE2: x IS NOT NULL    Result: false
   82247 **     pE1: x IS ?2    pE2: x IS NOT NULL    Reuslt: false
   82248 **
   82249 ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
   82250 ** Expr.iTable<0 then assume a table number given by iTab.
   82251 **
   82252 ** When in doubt, return false.  Returning true might give a performance
   82253 ** improvement.  Returning false might cause a performance reduction, but
   82254 ** it will always give the correct answer and is hence always safe.
   82255 */
   82256 SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
   82257   if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
   82258     return 1;
   82259   }
   82260   if( pE2->op==TK_OR
   82261    && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
   82262              || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
   82263   ){
   82264     return 1;
   82265   }
   82266   if( pE2->op==TK_NOTNULL
   82267    && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0
   82268    && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS)
   82269   ){
   82270     return 1;
   82271   }
   82272   return 0;
   82273 }
   82274 
   82275 /*
   82276 ** An instance of the following structure is used by the tree walker
   82277 ** to count references to table columns in the arguments of an
   82278 ** aggregate function, in order to implement the
   82279 ** sqlite3FunctionThisSrc() routine.
   82280 */
   82281 struct SrcCount {
   82282   SrcList *pSrc;   /* One particular FROM clause in a nested query */
   82283   int nThis;       /* Number of references to columns in pSrcList */
   82284   int nOther;      /* Number of references to columns in other FROM clauses */
   82285 };
   82286 
   82287 /*
   82288 ** Count the number of references to columns.
   82289 */
   82290 static int exprSrcCount(Walker *pWalker, Expr *pExpr){
   82291   /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
   82292   ** is always called before sqlite3ExprAnalyzeAggregates() and so the
   82293   ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN.  If
   82294   ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
   82295   ** NEVER() will need to be removed. */
   82296   if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
   82297     int i;
   82298     struct SrcCount *p = pWalker->u.pSrcCount;
   82299     SrcList *pSrc = p->pSrc;
   82300     for(i=0; i<pSrc->nSrc; i++){
   82301       if( pExpr->iTable==pSrc->a[i].iCursor ) break;
   82302     }
   82303     if( i<pSrc->nSrc ){
   82304       p->nThis++;
   82305     }else{
   82306       p->nOther++;
   82307     }
   82308   }
   82309   return WRC_Continue;
   82310 }
   82311 
   82312 /*
   82313 ** Determine if any of the arguments to the pExpr Function reference
   82314 ** pSrcList.  Return true if they do.  Also return true if the function
   82315 ** has no arguments or has only constant arguments.  Return false if pExpr
   82316 ** references columns but not columns of tables found in pSrcList.
   82317 */
   82318 SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
   82319   Walker w;
   82320   struct SrcCount cnt;
   82321   assert( pExpr->op==TK_AGG_FUNCTION );
   82322   memset(&w, 0, sizeof(w));
   82323   w.xExprCallback = exprSrcCount;
   82324   w.u.pSrcCount = &cnt;
   82325   cnt.pSrc = pSrcList;
   82326   cnt.nThis = 0;
   82327   cnt.nOther = 0;
   82328   sqlite3WalkExprList(&w, pExpr->x.pList);
   82329   return cnt.nThis>0 || cnt.nOther==0;
   82330 }
   82331 
   82332 /*
   82333 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
   82334 ** the new element.  Return a negative number if malloc fails.
   82335 */
   82336 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
   82337   int i;
   82338   pInfo->aCol = sqlite3ArrayAllocate(
   82339        db,
   82340        pInfo->aCol,
   82341        sizeof(pInfo->aCol[0]),
   82342        &pInfo->nColumn,
   82343        &i
   82344   );
   82345   return i;
   82346 }
   82347 
   82348 /*
   82349 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
   82350 ** the new element.  Return a negative number if malloc fails.
   82351 */
   82352 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
   82353   int i;
   82354   pInfo->aFunc = sqlite3ArrayAllocate(
   82355        db,
   82356        pInfo->aFunc,
   82357        sizeof(pInfo->aFunc[0]),
   82358        &pInfo->nFunc,
   82359        &i
   82360   );
   82361   return i;
   82362 }
   82363 
   82364 /*
   82365 ** This is the xExprCallback for a tree walker.  It is used to
   82366 ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
   82367 ** for additional information.
   82368 */
   82369 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
   82370   int i;
   82371   NameContext *pNC = pWalker->u.pNC;
   82372   Parse *pParse = pNC->pParse;
   82373   SrcList *pSrcList = pNC->pSrcList;
   82374   AggInfo *pAggInfo = pNC->pAggInfo;
   82375 
   82376   switch( pExpr->op ){
   82377     case TK_AGG_COLUMN:
   82378     case TK_COLUMN: {
   82379       testcase( pExpr->op==TK_AGG_COLUMN );
   82380       testcase( pExpr->op==TK_COLUMN );
   82381       /* Check to see if the column is in one of the tables in the FROM
   82382       ** clause of the aggregate query */
   82383       if( ALWAYS(pSrcList!=0) ){
   82384         struct SrcList_item *pItem = pSrcList->a;
   82385         for(i=0; i<pSrcList->nSrc; i++, pItem++){
   82386           struct AggInfo_col *pCol;
   82387           assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
   82388           if( pExpr->iTable==pItem->iCursor ){
   82389             /* If we reach this point, it means that pExpr refers to a table
   82390             ** that is in the FROM clause of the aggregate query.
   82391             **
   82392             ** Make an entry for the column in pAggInfo->aCol[] if there
   82393             ** is not an entry there already.
   82394             */
   82395             int k;
   82396             pCol = pAggInfo->aCol;
   82397             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
   82398               if( pCol->iTable==pExpr->iTable &&
   82399                   pCol->iColumn==pExpr->iColumn ){
   82400                 break;
   82401               }
   82402             }
   82403             if( (k>=pAggInfo->nColumn)
   82404              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
   82405             ){
   82406               pCol = &pAggInfo->aCol[k];
   82407               pCol->pTab = pExpr->pTab;
   82408               pCol->iTable = pExpr->iTable;
   82409               pCol->iColumn = pExpr->iColumn;
   82410               pCol->iMem = ++pParse->nMem;
   82411               pCol->iSorterColumn = -1;
   82412               pCol->pExpr = pExpr;
   82413               if( pAggInfo->pGroupBy ){
   82414                 int j, n;
   82415                 ExprList *pGB = pAggInfo->pGroupBy;
   82416                 struct ExprList_item *pTerm = pGB->a;
   82417                 n = pGB->nExpr;
   82418                 for(j=0; j<n; j++, pTerm++){
   82419                   Expr *pE = pTerm->pExpr;
   82420                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
   82421                       pE->iColumn==pExpr->iColumn ){
   82422                     pCol->iSorterColumn = j;
   82423                     break;
   82424                   }
   82425                 }
   82426               }
   82427               if( pCol->iSorterColumn<0 ){
   82428                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
   82429               }
   82430             }
   82431             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
   82432             ** because it was there before or because we just created it).
   82433             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
   82434             ** pAggInfo->aCol[] entry.
   82435             */
   82436             ExprSetVVAProperty(pExpr, EP_NoReduce);
   82437             pExpr->pAggInfo = pAggInfo;
   82438             pExpr->op = TK_AGG_COLUMN;
   82439             pExpr->iAgg = (i16)k;
   82440             break;
   82441           } /* endif pExpr->iTable==pItem->iCursor */
   82442         } /* end loop over pSrcList */
   82443       }
   82444       return WRC_Prune;
   82445     }
   82446     case TK_AGG_FUNCTION: {
   82447       if( (pNC->ncFlags & NC_InAggFunc)==0
   82448        && pWalker->walkerDepth==pExpr->op2
   82449       ){
   82450         /* Check to see if pExpr is a duplicate of another aggregate
   82451         ** function that is already in the pAggInfo structure
   82452         */
   82453         struct AggInfo_func *pItem = pAggInfo->aFunc;
   82454         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
   82455           if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
   82456             break;
   82457           }
   82458         }
   82459         if( i>=pAggInfo->nFunc ){
   82460           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
   82461           */
   82462           u8 enc = ENC(pParse->db);
   82463           i = addAggInfoFunc(pParse->db, pAggInfo);
   82464           if( i>=0 ){
   82465             assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   82466             pItem = &pAggInfo->aFunc[i];
   82467             pItem->pExpr = pExpr;
   82468             pItem->iMem = ++pParse->nMem;
   82469             assert( !ExprHasProperty(pExpr, EP_IntValue) );
   82470             pItem->pFunc = sqlite3FindFunction(pParse->db,
   82471                    pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
   82472                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
   82473             if( pExpr->flags & EP_Distinct ){
   82474               pItem->iDistinct = pParse->nTab++;
   82475             }else{
   82476               pItem->iDistinct = -1;
   82477             }
   82478           }
   82479         }
   82480         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
   82481         */
   82482         assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
   82483         ExprSetVVAProperty(pExpr, EP_NoReduce);
   82484         pExpr->iAgg = (i16)i;
   82485         pExpr->pAggInfo = pAggInfo;
   82486         return WRC_Prune;
   82487       }else{
   82488         return WRC_Continue;
   82489       }
   82490     }
   82491   }
   82492   return WRC_Continue;
   82493 }
   82494 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
   82495   UNUSED_PARAMETER(pWalker);
   82496   UNUSED_PARAMETER(pSelect);
   82497   return WRC_Continue;
   82498 }
   82499 
   82500 /*
   82501 ** Analyze the pExpr expression looking for aggregate functions and
   82502 ** for variables that need to be added to AggInfo object that pNC->pAggInfo
   82503 ** points to.  Additional entries are made on the AggInfo object as
   82504 ** necessary.
   82505 **
   82506 ** This routine should only be called after the expression has been
   82507 ** analyzed by sqlite3ResolveExprNames().
   82508 */
   82509 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
   82510   Walker w;
   82511   memset(&w, 0, sizeof(w));
   82512   w.xExprCallback = analyzeAggregate;
   82513   w.xSelectCallback = analyzeAggregatesInSelect;
   82514   w.u.pNC = pNC;
   82515   assert( pNC->pSrcList!=0 );
   82516   sqlite3WalkExpr(&w, pExpr);
   82517 }
   82518 
   82519 /*
   82520 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
   82521 ** expression list.  Return the number of errors.
   82522 **
   82523 ** If an error is found, the analysis is cut short.
   82524 */
   82525 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
   82526   struct ExprList_item *pItem;
   82527   int i;
   82528   if( pList ){
   82529     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
   82530       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
   82531     }
   82532   }
   82533 }
   82534 
   82535 /*
   82536 ** Allocate a single new register for use to hold some intermediate result.
   82537 */
   82538 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
   82539   if( pParse->nTempReg==0 ){
   82540     return ++pParse->nMem;
   82541   }
   82542   return pParse->aTempReg[--pParse->nTempReg];
   82543 }
   82544 
   82545 /*
   82546 ** Deallocate a register, making available for reuse for some other
   82547 ** purpose.
   82548 **
   82549 ** If a register is currently being used by the column cache, then
   82550 ** the dallocation is deferred until the column cache line that uses
   82551 ** the register becomes stale.
   82552 */
   82553 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
   82554   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
   82555     int i;
   82556     struct yColCache *p;
   82557     for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   82558       if( p->iReg==iReg ){
   82559         p->tempReg = 1;
   82560         return;
   82561       }
   82562     }
   82563     pParse->aTempReg[pParse->nTempReg++] = iReg;
   82564   }
   82565 }
   82566 
   82567 /*
   82568 ** Allocate or deallocate a block of nReg consecutive registers
   82569 */
   82570 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
   82571   int i, n;
   82572   i = pParse->iRangeReg;
   82573   n = pParse->nRangeReg;
   82574   if( nReg<=n ){
   82575     assert( !usedAsColumnCache(pParse, i, i+n-1) );
   82576     pParse->iRangeReg += nReg;
   82577     pParse->nRangeReg -= nReg;
   82578   }else{
   82579     i = pParse->nMem+1;
   82580     pParse->nMem += nReg;
   82581   }
   82582   return i;
   82583 }
   82584 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
   82585   sqlite3ExprCacheRemove(pParse, iReg, nReg);
   82586   if( nReg>pParse->nRangeReg ){
   82587     pParse->nRangeReg = nReg;
   82588     pParse->iRangeReg = iReg;
   82589   }
   82590 }
   82591 
   82592 /*
   82593 ** Mark all temporary registers as being unavailable for reuse.
   82594 */
   82595 SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
   82596   pParse->nTempReg = 0;
   82597   pParse->nRangeReg = 0;
   82598 }
   82599 
   82600 /************** End of expr.c ************************************************/
   82601 /************** Begin file alter.c *******************************************/
   82602 /*
   82603 ** 2005 February 15
   82604 **
   82605 ** The author disclaims copyright to this source code.  In place of
   82606 ** a legal notice, here is a blessing:
   82607 **
   82608 **    May you do good and not evil.
   82609 **    May you find forgiveness for yourself and forgive others.
   82610 **    May you share freely, never taking more than you give.
   82611 **
   82612 *************************************************************************
   82613 ** This file contains C code routines that used to generate VDBE code
   82614 ** that implements the ALTER TABLE command.
   82615 */
   82616 
   82617 /*
   82618 ** The code in this file only exists if we are not omitting the
   82619 ** ALTER TABLE logic from the build.
   82620 */
   82621 #ifndef SQLITE_OMIT_ALTERTABLE
   82622 
   82623 
   82624 /*
   82625 ** This function is used by SQL generated to implement the
   82626 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
   82627 ** CREATE INDEX command. The second is a table name. The table name in
   82628 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
   82629 ** argument and the result returned. Examples:
   82630 **
   82631 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
   82632 **     -> 'CREATE TABLE def(a, b, c)'
   82633 **
   82634 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
   82635 **     -> 'CREATE INDEX i ON def(a, b, c)'
   82636 */
   82637 static void renameTableFunc(
   82638   sqlite3_context *context,
   82639   int NotUsed,
   82640   sqlite3_value **argv
   82641 ){
   82642   unsigned char const *zSql = sqlite3_value_text(argv[0]);
   82643   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
   82644 
   82645   int token;
   82646   Token tname;
   82647   unsigned char const *zCsr = zSql;
   82648   int len = 0;
   82649   char *zRet;
   82650 
   82651   sqlite3 *db = sqlite3_context_db_handle(context);
   82652 
   82653   UNUSED_PARAMETER(NotUsed);
   82654 
   82655   /* The principle used to locate the table name in the CREATE TABLE
   82656   ** statement is that the table name is the first non-space token that
   82657   ** is immediately followed by a TK_LP or TK_USING token.
   82658   */
   82659   if( zSql ){
   82660     do {
   82661       if( !*zCsr ){
   82662         /* Ran out of input before finding an opening bracket. Return NULL. */
   82663         return;
   82664       }
   82665 
   82666       /* Store the token that zCsr points to in tname. */
   82667       tname.z = (char*)zCsr;
   82668       tname.n = len;
   82669 
   82670       /* Advance zCsr to the next token. Store that token type in 'token',
   82671       ** and its length in 'len' (to be used next iteration of this loop).
   82672       */
   82673       do {
   82674         zCsr += len;
   82675         len = sqlite3GetToken(zCsr, &token);
   82676       } while( token==TK_SPACE );
   82677       assert( len>0 );
   82678     } while( token!=TK_LP && token!=TK_USING );
   82679 
   82680     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
   82681        zSql, zTableName, tname.z+tname.n);
   82682     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
   82683   }
   82684 }
   82685 
   82686 /*
   82687 ** This C function implements an SQL user function that is used by SQL code
   82688 ** generated by the ALTER TABLE ... RENAME command to modify the definition
   82689 ** of any foreign key constraints that use the table being renamed as the
   82690 ** parent table. It is passed three arguments:
   82691 **
   82692 **   1) The complete text of the CREATE TABLE statement being modified,
   82693 **   2) The old name of the table being renamed, and
   82694 **   3) The new name of the table being renamed.
   82695 **
   82696 ** It returns the new CREATE TABLE statement. For example:
   82697 **
   82698 **   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
   82699 **       -> 'CREATE TABLE t1(a REFERENCES t3)'
   82700 */
   82701 #ifndef SQLITE_OMIT_FOREIGN_KEY
   82702 static void renameParentFunc(
   82703   sqlite3_context *context,
   82704   int NotUsed,
   82705   sqlite3_value **argv
   82706 ){
   82707   sqlite3 *db = sqlite3_context_db_handle(context);
   82708   char *zOutput = 0;
   82709   char *zResult;
   82710   unsigned char const *zInput = sqlite3_value_text(argv[0]);
   82711   unsigned char const *zOld = sqlite3_value_text(argv[1]);
   82712   unsigned char const *zNew = sqlite3_value_text(argv[2]);
   82713 
   82714   unsigned const char *z;         /* Pointer to token */
   82715   int n;                          /* Length of token z */
   82716   int token;                      /* Type of token */
   82717 
   82718   UNUSED_PARAMETER(NotUsed);
   82719   if( zInput==0 || zOld==0 ) return;
   82720   for(z=zInput; *z; z=z+n){
   82721     n = sqlite3GetToken(z, &token);
   82722     if( token==TK_REFERENCES ){
   82723       char *zParent;
   82724       do {
   82725         z += n;
   82726         n = sqlite3GetToken(z, &token);
   82727       }while( token==TK_SPACE );
   82728 
   82729       zParent = sqlite3DbStrNDup(db, (const char *)z, n);
   82730       if( zParent==0 ) break;
   82731       sqlite3Dequote(zParent);
   82732       if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
   82733         char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
   82734             (zOutput?zOutput:""), (int)(z-zInput), zInput, (const char *)zNew
   82735         );
   82736         sqlite3DbFree(db, zOutput);
   82737         zOutput = zOut;
   82738         zInput = &z[n];
   82739       }
   82740       sqlite3DbFree(db, zParent);
   82741     }
   82742   }
   82743 
   82744   zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
   82745   sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
   82746   sqlite3DbFree(db, zOutput);
   82747 }
   82748 #endif
   82749 
   82750 #ifndef SQLITE_OMIT_TRIGGER
   82751 /* This function is used by SQL generated to implement the
   82752 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
   82753 ** statement. The second is a table name. The table name in the CREATE
   82754 ** TRIGGER statement is replaced with the third argument and the result
   82755 ** returned. This is analagous to renameTableFunc() above, except for CREATE
   82756 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
   82757 */
   82758 static void renameTriggerFunc(
   82759   sqlite3_context *context,
   82760   int NotUsed,
   82761   sqlite3_value **argv
   82762 ){
   82763   unsigned char const *zSql = sqlite3_value_text(argv[0]);
   82764   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
   82765 
   82766   int token;
   82767   Token tname;
   82768   int dist = 3;
   82769   unsigned char const *zCsr = zSql;
   82770   int len = 0;
   82771   char *zRet;
   82772   sqlite3 *db = sqlite3_context_db_handle(context);
   82773 
   82774   UNUSED_PARAMETER(NotUsed);
   82775 
   82776   /* The principle used to locate the table name in the CREATE TRIGGER
   82777   ** statement is that the table name is the first token that is immediatedly
   82778   ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
   82779   ** of TK_WHEN, TK_BEGIN or TK_FOR.
   82780   */
   82781   if( zSql ){
   82782     do {
   82783 
   82784       if( !*zCsr ){
   82785         /* Ran out of input before finding the table name. Return NULL. */
   82786         return;
   82787       }
   82788 
   82789       /* Store the token that zCsr points to in tname. */
   82790       tname.z = (char*)zCsr;
   82791       tname.n = len;
   82792 
   82793       /* Advance zCsr to the next token. Store that token type in 'token',
   82794       ** and its length in 'len' (to be used next iteration of this loop).
   82795       */
   82796       do {
   82797         zCsr += len;
   82798         len = sqlite3GetToken(zCsr, &token);
   82799       }while( token==TK_SPACE );
   82800       assert( len>0 );
   82801 
   82802       /* Variable 'dist' stores the number of tokens read since the most
   82803       ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
   82804       ** token is read and 'dist' equals 2, the condition stated above
   82805       ** to be met.
   82806       **
   82807       ** Note that ON cannot be a database, table or column name, so
   82808       ** there is no need to worry about syntax like
   82809       ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
   82810       */
   82811       dist++;
   82812       if( token==TK_DOT || token==TK_ON ){
   82813         dist = 0;
   82814       }
   82815     } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
   82816 
   82817     /* Variable tname now contains the token that is the old table-name
   82818     ** in the CREATE TRIGGER statement.
   82819     */
   82820     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
   82821        zSql, zTableName, tname.z+tname.n);
   82822     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
   82823   }
   82824 }
   82825 #endif   /* !SQLITE_OMIT_TRIGGER */
   82826 
   82827 /*
   82828 ** Register built-in functions used to help implement ALTER TABLE
   82829 */
   82830 SQLITE_PRIVATE void sqlite3AlterFunctions(void){
   82831   static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
   82832     FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
   82833 #ifndef SQLITE_OMIT_TRIGGER
   82834     FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
   82835 #endif
   82836 #ifndef SQLITE_OMIT_FOREIGN_KEY
   82837     FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
   82838 #endif
   82839   };
   82840   int i;
   82841   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
   82842   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
   82843 
   82844   for(i=0; i<ArraySize(aAlterTableFuncs); i++){
   82845     sqlite3FuncDefInsert(pHash, &aFunc[i]);
   82846   }
   82847 }
   82848 
   82849 /*
   82850 ** This function is used to create the text of expressions of the form:
   82851 **
   82852 **   name=<constant1> OR name=<constant2> OR ...
   82853 **
   82854 ** If argument zWhere is NULL, then a pointer string containing the text
   82855 ** "name=<constant>" is returned, where <constant> is the quoted version
   82856 ** of the string passed as argument zConstant. The returned buffer is
   82857 ** allocated using sqlite3DbMalloc(). It is the responsibility of the
   82858 ** caller to ensure that it is eventually freed.
   82859 **
   82860 ** If argument zWhere is not NULL, then the string returned is
   82861 ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
   82862 ** In this case zWhere is passed to sqlite3DbFree() before returning.
   82863 **
   82864 */
   82865 static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
   82866   char *zNew;
   82867   if( !zWhere ){
   82868     zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
   82869   }else{
   82870     zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
   82871     sqlite3DbFree(db, zWhere);
   82872   }
   82873   return zNew;
   82874 }
   82875 
   82876 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
   82877 /*
   82878 ** Generate the text of a WHERE expression which can be used to select all
   82879 ** tables that have foreign key constraints that refer to table pTab (i.e.
   82880 ** constraints for which pTab is the parent table) from the sqlite_master
   82881 ** table.
   82882 */
   82883 static char *whereForeignKeys(Parse *pParse, Table *pTab){
   82884   FKey *p;
   82885   char *zWhere = 0;
   82886   for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
   82887     zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
   82888   }
   82889   return zWhere;
   82890 }
   82891 #endif
   82892 
   82893 /*
   82894 ** Generate the text of a WHERE expression which can be used to select all
   82895 ** temporary triggers on table pTab from the sqlite_temp_master table. If
   82896 ** table pTab has no temporary triggers, or is itself stored in the
   82897 ** temporary database, NULL is returned.
   82898 */
   82899 static char *whereTempTriggers(Parse *pParse, Table *pTab){
   82900   Trigger *pTrig;
   82901   char *zWhere = 0;
   82902   const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
   82903 
   82904   /* If the table is not located in the temp-db (in which case NULL is
   82905   ** returned, loop through the tables list of triggers. For each trigger
   82906   ** that is not part of the temp-db schema, add a clause to the WHERE
   82907   ** expression being built up in zWhere.
   82908   */
   82909   if( pTab->pSchema!=pTempSchema ){
   82910     sqlite3 *db = pParse->db;
   82911     for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
   82912       if( pTrig->pSchema==pTempSchema ){
   82913         zWhere = whereOrName(db, zWhere, pTrig->zName);
   82914       }
   82915     }
   82916   }
   82917   if( zWhere ){
   82918     char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
   82919     sqlite3DbFree(pParse->db, zWhere);
   82920     zWhere = zNew;
   82921   }
   82922   return zWhere;
   82923 }
   82924 
   82925 /*
   82926 ** Generate code to drop and reload the internal representation of table
   82927 ** pTab from the database, including triggers and temporary triggers.
   82928 ** Argument zName is the name of the table in the database schema at
   82929 ** the time the generated code is executed. This can be different from
   82930 ** pTab->zName if this function is being called to code part of an
   82931 ** "ALTER TABLE RENAME TO" statement.
   82932 */
   82933 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
   82934   Vdbe *v;
   82935   char *zWhere;
   82936   int iDb;                   /* Index of database containing pTab */
   82937 #ifndef SQLITE_OMIT_TRIGGER
   82938   Trigger *pTrig;
   82939 #endif
   82940 
   82941   v = sqlite3GetVdbe(pParse);
   82942   if( NEVER(v==0) ) return;
   82943   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
   82944   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   82945   assert( iDb>=0 );
   82946 
   82947 #ifndef SQLITE_OMIT_TRIGGER
   82948   /* Drop any table triggers from the internal schema. */
   82949   for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
   82950     int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
   82951     assert( iTrigDb==iDb || iTrigDb==1 );
   82952     sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
   82953   }
   82954 #endif
   82955 
   82956   /* Drop the table and index from the internal schema.  */
   82957   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
   82958 
   82959   /* Reload the table, index and permanent trigger schemas. */
   82960   zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
   82961   if( !zWhere ) return;
   82962   sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
   82963 
   82964 #ifndef SQLITE_OMIT_TRIGGER
   82965   /* Now, if the table is not stored in the temp database, reload any temp
   82966   ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
   82967   */
   82968   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
   82969     sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
   82970   }
   82971 #endif
   82972 }
   82973 
   82974 /*
   82975 ** Parameter zName is the name of a table that is about to be altered
   82976 ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
   82977 ** If the table is a system table, this function leaves an error message
   82978 ** in pParse->zErr (system tables may not be altered) and returns non-zero.
   82979 **
   82980 ** Or, if zName is not a system table, zero is returned.
   82981 */
   82982 static int isSystemTable(Parse *pParse, const char *zName){
   82983   if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
   82984     sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
   82985     return 1;
   82986   }
   82987   return 0;
   82988 }
   82989 
   82990 /*
   82991 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
   82992 ** command.
   82993 */
   82994 SQLITE_PRIVATE void sqlite3AlterRenameTable(
   82995   Parse *pParse,            /* Parser context. */
   82996   SrcList *pSrc,            /* The table to rename. */
   82997   Token *pName              /* The new table name. */
   82998 ){
   82999   int iDb;                  /* Database that contains the table */
   83000   char *zDb;                /* Name of database iDb */
   83001   Table *pTab;              /* Table being renamed */
   83002   char *zName = 0;          /* NULL-terminated version of pName */
   83003   sqlite3 *db = pParse->db; /* Database connection */
   83004   int nTabName;             /* Number of UTF-8 characters in zTabName */
   83005   const char *zTabName;     /* Original name of the table */
   83006   Vdbe *v;
   83007 #ifndef SQLITE_OMIT_TRIGGER
   83008   char *zWhere = 0;         /* Where clause to locate temp triggers */
   83009 #endif
   83010   VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
   83011   int savedDbFlags;         /* Saved value of db->flags */
   83012 
   83013   savedDbFlags = db->flags;
   83014   if( NEVER(db->mallocFailed) ) goto exit_rename_table;
   83015   assert( pSrc->nSrc==1 );
   83016   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
   83017 
   83018   pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
   83019   if( !pTab ) goto exit_rename_table;
   83020   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   83021   zDb = db->aDb[iDb].zName;
   83022   db->flags |= SQLITE_PreferBuiltin;
   83023 
   83024   /* Get a NULL terminated version of the new table name. */
   83025   zName = sqlite3NameFromToken(db, pName);
   83026   if( !zName ) goto exit_rename_table;
   83027 
   83028   /* Check that a table or index named 'zName' does not already exist
   83029   ** in database iDb. If so, this is an error.
   83030   */
   83031   if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
   83032     sqlite3ErrorMsg(pParse,
   83033         "there is already another table or index with this name: %s", zName);
   83034     goto exit_rename_table;
   83035   }
   83036 
   83037   /* Make sure it is not a system table being altered, or a reserved name
   83038   ** that the table is being renamed to.
   83039   */
   83040   if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
   83041     goto exit_rename_table;
   83042   }
   83043   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
   83044     exit_rename_table;
   83045   }
   83046 
   83047 #ifndef SQLITE_OMIT_VIEW
   83048   if( pTab->pSelect ){
   83049     sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
   83050     goto exit_rename_table;
   83051   }
   83052 #endif
   83053 
   83054 #ifndef SQLITE_OMIT_AUTHORIZATION
   83055   /* Invoke the authorization callback. */
   83056   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
   83057     goto exit_rename_table;
   83058   }
   83059 #endif
   83060 
   83061 #ifndef SQLITE_OMIT_VIRTUALTABLE
   83062   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
   83063     goto exit_rename_table;
   83064   }
   83065   if( IsVirtual(pTab) ){
   83066     pVTab = sqlite3GetVTable(db, pTab);
   83067     if( pVTab->pVtab->pModule->xRename==0 ){
   83068       pVTab = 0;
   83069     }
   83070   }
   83071 #endif
   83072 
   83073   /* Begin a transaction for database iDb.
   83074   ** Then modify the schema cookie (since the ALTER TABLE modifies the
   83075   ** schema). Open a statement transaction if the table is a virtual
   83076   ** table.
   83077   */
   83078   v = sqlite3GetVdbe(pParse);
   83079   if( v==0 ){
   83080     goto exit_rename_table;
   83081   }
   83082   sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
   83083   sqlite3ChangeCookie(pParse, iDb);
   83084 
   83085   /* If this is a virtual table, invoke the xRename() function if
   83086   ** one is defined. The xRename() callback will modify the names
   83087   ** of any resources used by the v-table implementation (including other
   83088   ** SQLite tables) that are identified by the name of the virtual table.
   83089   */
   83090 #ifndef SQLITE_OMIT_VIRTUALTABLE
   83091   if( pVTab ){
   83092     int i = ++pParse->nMem;
   83093     sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
   83094     sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
   83095     sqlite3MayAbort(pParse);
   83096   }
   83097 #endif
   83098 
   83099   /* figure out how many UTF-8 characters are in zName */
   83100   zTabName = pTab->zName;
   83101   nTabName = sqlite3Utf8CharLen(zTabName, -1);
   83102 
   83103 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
   83104   if( db->flags&SQLITE_ForeignKeys ){
   83105     /* If foreign-key support is enabled, rewrite the CREATE TABLE
   83106     ** statements corresponding to all child tables of foreign key constraints
   83107     ** for which the renamed table is the parent table.  */
   83108     if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
   83109       sqlite3NestedParse(pParse,
   83110           "UPDATE \"%w\".%s SET "
   83111               "sql = sqlite_rename_parent(sql, %Q, %Q) "
   83112               "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
   83113       sqlite3DbFree(db, zWhere);
   83114     }
   83115   }
   83116 #endif
   83117 
   83118   /* Modify the sqlite_master table to use the new table name. */
   83119   sqlite3NestedParse(pParse,
   83120       "UPDATE %Q.%s SET "
   83121 #ifdef SQLITE_OMIT_TRIGGER
   83122           "sql = sqlite_rename_table(sql, %Q), "
   83123 #else
   83124           "sql = CASE "
   83125             "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
   83126             "ELSE sqlite_rename_table(sql, %Q) END, "
   83127 #endif
   83128           "tbl_name = %Q, "
   83129           "name = CASE "
   83130             "WHEN type='table' THEN %Q "
   83131             "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
   83132              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
   83133             "ELSE name END "
   83134       "WHERE tbl_name=%Q COLLATE nocase AND "
   83135           "(type='table' OR type='index' OR type='trigger');",
   83136       zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
   83137 #ifndef SQLITE_OMIT_TRIGGER
   83138       zName,
   83139 #endif
   83140       zName, nTabName, zTabName
   83141   );
   83142 
   83143 #ifndef SQLITE_OMIT_AUTOINCREMENT
   83144   /* If the sqlite_sequence table exists in this database, then update
   83145   ** it with the new table name.
   83146   */
   83147   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
   83148     sqlite3NestedParse(pParse,
   83149         "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
   83150         zDb, zName, pTab->zName);
   83151   }
   83152 #endif
   83153 
   83154 #ifndef SQLITE_OMIT_TRIGGER
   83155   /* If there are TEMP triggers on this table, modify the sqlite_temp_master
   83156   ** table. Don't do this if the table being ALTERed is itself located in
   83157   ** the temp database.
   83158   */
   83159   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
   83160     sqlite3NestedParse(pParse,
   83161         "UPDATE sqlite_temp_master SET "
   83162             "sql = sqlite_rename_trigger(sql, %Q), "
   83163             "tbl_name = %Q "
   83164             "WHERE %s;", zName, zName, zWhere);
   83165     sqlite3DbFree(db, zWhere);
   83166   }
   83167 #endif
   83168 
   83169 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
   83170   if( db->flags&SQLITE_ForeignKeys ){
   83171     FKey *p;
   83172     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
   83173       Table *pFrom = p->pFrom;
   83174       if( pFrom!=pTab ){
   83175         reloadTableSchema(pParse, p->pFrom, pFrom->zName);
   83176       }
   83177     }
   83178   }
   83179 #endif
   83180 
   83181   /* Drop and reload the internal table schema. */
   83182   reloadTableSchema(pParse, pTab, zName);
   83183 
   83184 exit_rename_table:
   83185   sqlite3SrcListDelete(db, pSrc);
   83186   sqlite3DbFree(db, zName);
   83187   db->flags = savedDbFlags;
   83188 }
   83189 
   83190 
   83191 /*
   83192 ** Generate code to make sure the file format number is at least minFormat.
   83193 ** The generated code will increase the file format number if necessary.
   83194 */
   83195 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
   83196   Vdbe *v;
   83197   v = sqlite3GetVdbe(pParse);
   83198   /* The VDBE should have been allocated before this routine is called.
   83199   ** If that allocation failed, we would have quit before reaching this
   83200   ** point */
   83201   if( ALWAYS(v) ){
   83202     int r1 = sqlite3GetTempReg(pParse);
   83203     int r2 = sqlite3GetTempReg(pParse);
   83204     int j1;
   83205     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
   83206     sqlite3VdbeUsesBtree(v, iDb);
   83207     sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
   83208     j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
   83209     sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); VdbeCoverage(v);
   83210     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
   83211     sqlite3VdbeJumpHere(v, j1);
   83212     sqlite3ReleaseTempReg(pParse, r1);
   83213     sqlite3ReleaseTempReg(pParse, r2);
   83214   }
   83215 }
   83216 
   83217 /*
   83218 ** This function is called after an "ALTER TABLE ... ADD" statement
   83219 ** has been parsed. Argument pColDef contains the text of the new
   83220 ** column definition.
   83221 **
   83222 ** The Table structure pParse->pNewTable was extended to include
   83223 ** the new column during parsing.
   83224 */
   83225 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
   83226   Table *pNew;              /* Copy of pParse->pNewTable */
   83227   Table *pTab;              /* Table being altered */
   83228   int iDb;                  /* Database number */
   83229   const char *zDb;          /* Database name */
   83230   const char *zTab;         /* Table name */
   83231   char *zCol;               /* Null-terminated column definition */
   83232   Column *pCol;             /* The new column */
   83233   Expr *pDflt;              /* Default value for the new column */
   83234   sqlite3 *db;              /* The database connection; */
   83235 
   83236   db = pParse->db;
   83237   if( pParse->nErr || db->mallocFailed ) return;
   83238   pNew = pParse->pNewTable;
   83239   assert( pNew );
   83240 
   83241   assert( sqlite3BtreeHoldsAllMutexes(db) );
   83242   iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
   83243   zDb = db->aDb[iDb].zName;
   83244   zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
   83245   pCol = &pNew->aCol[pNew->nCol-1];
   83246   pDflt = pCol->pDflt;
   83247   pTab = sqlite3FindTable(db, zTab, zDb);
   83248   assert( pTab );
   83249 
   83250 #ifndef SQLITE_OMIT_AUTHORIZATION
   83251   /* Invoke the authorization callback. */
   83252   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
   83253     return;
   83254   }
   83255 #endif
   83256 
   83257   /* If the default value for the new column was specified with a
   83258   ** literal NULL, then set pDflt to 0. This simplifies checking
   83259   ** for an SQL NULL default below.
   83260   */
   83261   if( pDflt && pDflt->op==TK_NULL ){
   83262     pDflt = 0;
   83263   }
   83264 
   83265   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
   83266   ** If there is a NOT NULL constraint, then the default value for the
   83267   ** column must not be NULL.
   83268   */
   83269   if( pCol->colFlags & COLFLAG_PRIMKEY ){
   83270     sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
   83271     return;
   83272   }
   83273   if( pNew->pIndex ){
   83274     sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
   83275     return;
   83276   }
   83277   if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
   83278     sqlite3ErrorMsg(pParse,
   83279         "Cannot add a REFERENCES column with non-NULL default value");
   83280     return;
   83281   }
   83282   if( pCol->notNull && !pDflt ){
   83283     sqlite3ErrorMsg(pParse,
   83284         "Cannot add a NOT NULL column with default value NULL");
   83285     return;
   83286   }
   83287 
   83288   /* Ensure the default expression is something that sqlite3ValueFromExpr()
   83289   ** can handle (i.e. not CURRENT_TIME etc.)
   83290   */
   83291   if( pDflt ){
   83292     sqlite3_value *pVal = 0;
   83293     if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
   83294       db->mallocFailed = 1;
   83295       return;
   83296     }
   83297     if( !pVal ){
   83298       sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
   83299       return;
   83300     }
   83301     sqlite3ValueFree(pVal);
   83302   }
   83303 
   83304   /* Modify the CREATE TABLE statement. */
   83305   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
   83306   if( zCol ){
   83307     char *zEnd = &zCol[pColDef->n-1];
   83308     int savedDbFlags = db->flags;
   83309     while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
   83310       *zEnd-- = '\0';
   83311     }
   83312     db->flags |= SQLITE_PreferBuiltin;
   83313     sqlite3NestedParse(pParse,
   83314         "UPDATE \"%w\".%s SET "
   83315           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
   83316         "WHERE type = 'table' AND name = %Q",
   83317       zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
   83318       zTab
   83319     );
   83320     sqlite3DbFree(db, zCol);
   83321     db->flags = savedDbFlags;
   83322   }
   83323 
   83324   /* If the default value of the new column is NULL, then set the file
   83325   ** format to 2. If the default value of the new column is not NULL,
   83326   ** the file format becomes 3.
   83327   */
   83328   sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
   83329 
   83330   /* Reload the schema of the modified table. */
   83331   reloadTableSchema(pParse, pTab, pTab->zName);
   83332 }
   83333 
   83334 /*
   83335 ** This function is called by the parser after the table-name in
   83336 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
   83337 ** pSrc is the full-name of the table being altered.
   83338 **
   83339 ** This routine makes a (partial) copy of the Table structure
   83340 ** for the table being altered and sets Parse.pNewTable to point
   83341 ** to it. Routines called by the parser as the column definition
   83342 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
   83343 ** the copy. The copy of the Table structure is deleted by tokenize.c
   83344 ** after parsing is finished.
   83345 **
   83346 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
   83347 ** coding the "ALTER TABLE ... ADD" statement.
   83348 */
   83349 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
   83350   Table *pNew;
   83351   Table *pTab;
   83352   Vdbe *v;
   83353   int iDb;
   83354   int i;
   83355   int nAlloc;
   83356   sqlite3 *db = pParse->db;
   83357 
   83358   /* Look up the table being altered. */
   83359   assert( pParse->pNewTable==0 );
   83360   assert( sqlite3BtreeHoldsAllMutexes(db) );
   83361   if( db->mallocFailed ) goto exit_begin_add_column;
   83362   pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
   83363   if( !pTab ) goto exit_begin_add_column;
   83364 
   83365 #ifndef SQLITE_OMIT_VIRTUALTABLE
   83366   if( IsVirtual(pTab) ){
   83367     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
   83368     goto exit_begin_add_column;
   83369   }
   83370 #endif
   83371 
   83372   /* Make sure this is not an attempt to ALTER a view. */
   83373   if( pTab->pSelect ){
   83374     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
   83375     goto exit_begin_add_column;
   83376   }
   83377   if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
   83378     goto exit_begin_add_column;
   83379   }
   83380 
   83381   assert( pTab->addColOffset>0 );
   83382   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   83383 
   83384   /* Put a copy of the Table struct in Parse.pNewTable for the
   83385   ** sqlite3AddColumn() function and friends to modify.  But modify
   83386   ** the name by adding an "sqlite_altertab_" prefix.  By adding this
   83387   ** prefix, we insure that the name will not collide with an existing
   83388   ** table because user table are not allowed to have the "sqlite_"
   83389   ** prefix on their name.
   83390   */
   83391   pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
   83392   if( !pNew ) goto exit_begin_add_column;
   83393   pParse->pNewTable = pNew;
   83394   pNew->nRef = 1;
   83395   pNew->nCol = pTab->nCol;
   83396   assert( pNew->nCol>0 );
   83397   nAlloc = (((pNew->nCol-1)/8)*8)+8;
   83398   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
   83399   pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
   83400   pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
   83401   if( !pNew->aCol || !pNew->zName ){
   83402     db->mallocFailed = 1;
   83403     goto exit_begin_add_column;
   83404   }
   83405   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
   83406   for(i=0; i<pNew->nCol; i++){
   83407     Column *pCol = &pNew->aCol[i];
   83408     pCol->zName = sqlite3DbStrDup(db, pCol->zName);
   83409     pCol->zColl = 0;
   83410     pCol->zType = 0;
   83411     pCol->pDflt = 0;
   83412     pCol->zDflt = 0;
   83413   }
   83414   pNew->pSchema = db->aDb[iDb].pSchema;
   83415   pNew->addColOffset = pTab->addColOffset;
   83416   pNew->nRef = 1;
   83417 
   83418   /* Begin a transaction and increment the schema cookie.  */
   83419   sqlite3BeginWriteOperation(pParse, 0, iDb);
   83420   v = sqlite3GetVdbe(pParse);
   83421   if( !v ) goto exit_begin_add_column;
   83422   sqlite3ChangeCookie(pParse, iDb);
   83423 
   83424 exit_begin_add_column:
   83425   sqlite3SrcListDelete(db, pSrc);
   83426   return;
   83427 }
   83428 #endif  /* SQLITE_ALTER_TABLE */
   83429 
   83430 /************** End of alter.c ***********************************************/
   83431 /************** Begin file analyze.c *****************************************/
   83432 /*
   83433 ** 2005-07-08
   83434 **
   83435 ** The author disclaims copyright to this source code.  In place of
   83436 ** a legal notice, here is a blessing:
   83437 **
   83438 **    May you do good and not evil.
   83439 **    May you find forgiveness for yourself and forgive others.
   83440 **    May you share freely, never taking more than you give.
   83441 **
   83442 *************************************************************************
   83443 ** This file contains code associated with the ANALYZE command.
   83444 **
   83445 ** The ANALYZE command gather statistics about the content of tables
   83446 ** and indices.  These statistics are made available to the query planner
   83447 ** to help it make better decisions about how to perform queries.
   83448 **
   83449 ** The following system tables are or have been supported:
   83450 **
   83451 **    CREATE TABLE sqlite_stat1(tbl, idx, stat);
   83452 **    CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
   83453 **    CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
   83454 **    CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
   83455 **
   83456 ** Additional tables might be added in future releases of SQLite.
   83457 ** The sqlite_stat2 table is not created or used unless the SQLite version
   83458 ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
   83459 ** with SQLITE_ENABLE_STAT2.  The sqlite_stat2 table is deprecated.
   83460 ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
   83461 ** created and used by SQLite versions 3.7.9 and later and with
   83462 ** SQLITE_ENABLE_STAT3 defined.  The functionality of sqlite_stat3
   83463 ** is a superset of sqlite_stat2.  The sqlite_stat4 is an enhanced
   83464 ** version of sqlite_stat3 and is only available when compiled with
   83465 ** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later.  It is
   83466 ** not possible to enable both STAT3 and STAT4 at the same time.  If they
   83467 ** are both enabled, then STAT4 takes precedence.
   83468 **
   83469 ** For most applications, sqlite_stat1 provides all the statisics required
   83470 ** for the query planner to make good choices.
   83471 **
   83472 ** Format of sqlite_stat1:
   83473 **
   83474 ** There is normally one row per index, with the index identified by the
   83475 ** name in the idx column.  The tbl column is the name of the table to
   83476 ** which the index belongs.  In each such row, the stat column will be
   83477 ** a string consisting of a list of integers.  The first integer in this
   83478 ** list is the number of rows in the index.  (This is the same as the
   83479 ** number of rows in the table, except for partial indices.)  The second
   83480 ** integer is the average number of rows in the index that have the same
   83481 ** value in the first column of the index.  The third integer is the average
   83482 ** number of rows in the index that have the same value for the first two
   83483 ** columns.  The N-th integer (for N>1) is the average number of rows in
   83484 ** the index which have the same value for the first N-1 columns.  For
   83485 ** a K-column index, there will be K+1 integers in the stat column.  If
   83486 ** the index is unique, then the last integer will be 1.
   83487 **
   83488 ** The list of integers in the stat column can optionally be followed
   83489 ** by the keyword "unordered".  The "unordered" keyword, if it is present,
   83490 ** must be separated from the last integer by a single space.  If the
   83491 ** "unordered" keyword is present, then the query planner assumes that
   83492 ** the index is unordered and will not use the index for a range query.
   83493 **
   83494 ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
   83495 ** column contains a single integer which is the (estimated) number of
   83496 ** rows in the table identified by sqlite_stat1.tbl.
   83497 **
   83498 ** Format of sqlite_stat2:
   83499 **
   83500 ** The sqlite_stat2 is only created and is only used if SQLite is compiled
   83501 ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
   83502 ** 3.6.18 and 3.7.8.  The "stat2" table contains additional information
   83503 ** about the distribution of keys within an index.  The index is identified by
   83504 ** the "idx" column and the "tbl" column is the name of the table to which
   83505 ** the index belongs.  There are usually 10 rows in the sqlite_stat2
   83506 ** table for each index.
   83507 **
   83508 ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
   83509 ** inclusive are samples of the left-most key value in the index taken at
   83510 ** evenly spaced points along the index.  Let the number of samples be S
   83511 ** (10 in the standard build) and let C be the number of rows in the index.
   83512 ** Then the sampled rows are given by:
   83513 **
   83514 **     rownumber = (i*C*2 + C)/(S*2)
   83515 **
   83516 ** For i between 0 and S-1.  Conceptually, the index space is divided into
   83517 ** S uniform buckets and the samples are the middle row from each bucket.
   83518 **
   83519 ** The format for sqlite_stat2 is recorded here for legacy reference.  This
   83520 ** version of SQLite does not support sqlite_stat2.  It neither reads nor
   83521 ** writes the sqlite_stat2 table.  This version of SQLite only supports
   83522 ** sqlite_stat3.
   83523 **
   83524 ** Format for sqlite_stat3:
   83525 **
   83526 ** The sqlite_stat3 format is a subset of sqlite_stat4.  Hence, the
   83527 ** sqlite_stat4 format will be described first.  Further information
   83528 ** about sqlite_stat3 follows the sqlite_stat4 description.
   83529 **
   83530 ** Format for sqlite_stat4:
   83531 **
   83532 ** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
   83533 ** to aid the query planner in choosing good indices based on the values
   83534 ** that indexed columns are compared against in the WHERE clauses of
   83535 ** queries.
   83536 **
   83537 ** The sqlite_stat4 table contains multiple entries for each index.
   83538 ** The idx column names the index and the tbl column is the table of the
   83539 ** index.  If the idx and tbl columns are the same, then the sample is
   83540 ** of the INTEGER PRIMARY KEY.  The sample column is a blob which is the
   83541 ** binary encoding of a key from the index.  The nEq column is a
   83542 ** list of integers.  The first integer is the approximate number
   83543 ** of entries in the index whose left-most column exactly matches
   83544 ** the left-most column of the sample.  The second integer in nEq
   83545 ** is the approximate number of entries in the index where the
   83546 ** first two columns match the first two columns of the sample.
   83547 ** And so forth.  nLt is another list of integers that show the approximate
   83548 ** number of entries that are strictly less than the sample.  The first
   83549 ** integer in nLt contains the number of entries in the index where the
   83550 ** left-most column is less than the left-most column of the sample.
   83551 ** The K-th integer in the nLt entry is the number of index entries
   83552 ** where the first K columns are less than the first K columns of the
   83553 ** sample.  The nDLt column is like nLt except that it contains the
   83554 ** number of distinct entries in the index that are less than the
   83555 ** sample.
   83556 **
   83557 ** There can be an arbitrary number of sqlite_stat4 entries per index.
   83558 ** The ANALYZE command will typically generate sqlite_stat4 tables
   83559 ** that contain between 10 and 40 samples which are distributed across
   83560 ** the key space, though not uniformly, and which include samples with
   83561 ** large nEq values.
   83562 **
   83563 ** Format for sqlite_stat3 redux:
   83564 **
   83565 ** The sqlite_stat3 table is like sqlite_stat4 except that it only
   83566 ** looks at the left-most column of the index.  The sqlite_stat3.sample
   83567 ** column contains the actual value of the left-most column instead
   83568 ** of a blob encoding of the complete index key as is found in
   83569 ** sqlite_stat4.sample.  The nEq, nLt, and nDLt entries of sqlite_stat3
   83570 ** all contain just a single integer which is the same as the first
   83571 ** integer in the equivalent columns in sqlite_stat4.
   83572 */
   83573 #ifndef SQLITE_OMIT_ANALYZE
   83574 
   83575 #if defined(SQLITE_ENABLE_STAT4)
   83576 # define IsStat4     1
   83577 # define IsStat3     0
   83578 #elif defined(SQLITE_ENABLE_STAT3)
   83579 # define IsStat4     0
   83580 # define IsStat3     1
   83581 #else
   83582 # define IsStat4     0
   83583 # define IsStat3     0
   83584 # undef SQLITE_STAT4_SAMPLES
   83585 # define SQLITE_STAT4_SAMPLES 1
   83586 #endif
   83587 #define IsStat34    (IsStat3+IsStat4)  /* 1 for STAT3 or STAT4. 0 otherwise */
   83588 
   83589 /*
   83590 ** This routine generates code that opens the sqlite_statN tables.
   83591 ** The sqlite_stat1 table is always relevant.  sqlite_stat2 is now
   83592 ** obsolete.  sqlite_stat3 and sqlite_stat4 are only opened when
   83593 ** appropriate compile-time options are provided.
   83594 **
   83595 ** If the sqlite_statN tables do not previously exist, it is created.
   83596 **
   83597 ** Argument zWhere may be a pointer to a buffer containing a table name,
   83598 ** or it may be a NULL pointer. If it is not NULL, then all entries in
   83599 ** the sqlite_statN tables associated with the named table are deleted.
   83600 ** If zWhere==0, then code is generated to delete all stat table entries.
   83601 */
   83602 static void openStatTable(
   83603   Parse *pParse,          /* Parsing context */
   83604   int iDb,                /* The database we are looking in */
   83605   int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
   83606   const char *zWhere,     /* Delete entries for this table or index */
   83607   const char *zWhereType  /* Either "tbl" or "idx" */
   83608 ){
   83609   static const struct {
   83610     const char *zName;
   83611     const char *zCols;
   83612   } aTable[] = {
   83613     { "sqlite_stat1", "tbl,idx,stat" },
   83614 #if defined(SQLITE_ENABLE_STAT4)
   83615     { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
   83616     { "sqlite_stat3", 0 },
   83617 #elif defined(SQLITE_ENABLE_STAT3)
   83618     { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
   83619     { "sqlite_stat4", 0 },
   83620 #else
   83621     { "sqlite_stat3", 0 },
   83622     { "sqlite_stat4", 0 },
   83623 #endif
   83624   };
   83625   int i;
   83626   sqlite3 *db = pParse->db;
   83627   Db *pDb;
   83628   Vdbe *v = sqlite3GetVdbe(pParse);
   83629   int aRoot[ArraySize(aTable)];
   83630   u8 aCreateTbl[ArraySize(aTable)];
   83631 
   83632   if( v==0 ) return;
   83633   assert( sqlite3BtreeHoldsAllMutexes(db) );
   83634   assert( sqlite3VdbeDb(v)==db );
   83635   pDb = &db->aDb[iDb];
   83636 
   83637   /* Create new statistic tables if they do not exist, or clear them
   83638   ** if they do already exist.
   83639   */
   83640   for(i=0; i<ArraySize(aTable); i++){
   83641     const char *zTab = aTable[i].zName;
   83642     Table *pStat;
   83643     if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
   83644       if( aTable[i].zCols ){
   83645         /* The sqlite_statN table does not exist. Create it. Note that a
   83646         ** side-effect of the CREATE TABLE statement is to leave the rootpage
   83647         ** of the new table in register pParse->regRoot. This is important
   83648         ** because the OpenWrite opcode below will be needing it. */
   83649         sqlite3NestedParse(pParse,
   83650             "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
   83651         );
   83652         aRoot[i] = pParse->regRoot;
   83653         aCreateTbl[i] = OPFLAG_P2ISREG;
   83654       }
   83655     }else{
   83656       /* The table already exists. If zWhere is not NULL, delete all entries
   83657       ** associated with the table zWhere. If zWhere is NULL, delete the
   83658       ** entire contents of the table. */
   83659       aRoot[i] = pStat->tnum;
   83660       aCreateTbl[i] = 0;
   83661       sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
   83662       if( zWhere ){
   83663         sqlite3NestedParse(pParse,
   83664            "DELETE FROM %Q.%s WHERE %s=%Q",
   83665            pDb->zName, zTab, zWhereType, zWhere
   83666         );
   83667       }else{
   83668         /* The sqlite_stat[134] table already exists.  Delete all rows. */
   83669         sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
   83670       }
   83671     }
   83672   }
   83673 
   83674   /* Open the sqlite_stat[134] tables for writing. */
   83675   for(i=0; aTable[i].zCols; i++){
   83676     assert( i<ArraySize(aTable) );
   83677     sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3);
   83678     sqlite3VdbeChangeP5(v, aCreateTbl[i]);
   83679     VdbeComment((v, aTable[i].zName));
   83680   }
   83681 }
   83682 
   83683 /*
   83684 ** Recommended number of samples for sqlite_stat4
   83685 */
   83686 #ifndef SQLITE_STAT4_SAMPLES
   83687 # define SQLITE_STAT4_SAMPLES 24
   83688 #endif
   83689 
   83690 /*
   83691 ** Three SQL functions - stat_init(), stat_push(), and stat_get() -
   83692 ** share an instance of the following structure to hold their state
   83693 ** information.
   83694 */
   83695 typedef struct Stat4Accum Stat4Accum;
   83696 typedef struct Stat4Sample Stat4Sample;
   83697 struct Stat4Sample {
   83698   tRowcnt *anEq;                  /* sqlite_stat4.nEq */
   83699   tRowcnt *anDLt;                 /* sqlite_stat4.nDLt */
   83700 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   83701   tRowcnt *anLt;                  /* sqlite_stat4.nLt */
   83702   union {
   83703     i64 iRowid;                     /* Rowid in main table of the key */
   83704     u8 *aRowid;                     /* Key for WITHOUT ROWID tables */
   83705   } u;
   83706   u32 nRowid;                     /* Sizeof aRowid[] */
   83707   u8 isPSample;                   /* True if a periodic sample */
   83708   int iCol;                       /* If !isPSample, the reason for inclusion */
   83709   u32 iHash;                      /* Tiebreaker hash */
   83710 #endif
   83711 };
   83712 struct Stat4Accum {
   83713   tRowcnt nRow;             /* Number of rows in the entire table */
   83714   tRowcnt nPSample;         /* How often to do a periodic sample */
   83715   int nCol;                 /* Number of columns in index + pk/rowid */
   83716   int nKeyCol;              /* Number of index columns w/o the pk/rowid */
   83717   int mxSample;             /* Maximum number of samples to accumulate */
   83718   Stat4Sample current;      /* Current row as a Stat4Sample */
   83719   u32 iPrn;                 /* Pseudo-random number used for sampling */
   83720   Stat4Sample *aBest;       /* Array of nCol best samples */
   83721   int iMin;                 /* Index in a[] of entry with minimum score */
   83722   int nSample;              /* Current number of samples */
   83723   int iGet;                 /* Index of current sample accessed by stat_get() */
   83724   Stat4Sample *a;           /* Array of mxSample Stat4Sample objects */
   83725   sqlite3 *db;              /* Database connection, for malloc() */
   83726 };
   83727 
   83728 /* Reclaim memory used by a Stat4Sample
   83729 */
   83730 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   83731 static void sampleClear(sqlite3 *db, Stat4Sample *p){
   83732   assert( db!=0 );
   83733   if( p->nRowid ){
   83734     sqlite3DbFree(db, p->u.aRowid);
   83735     p->nRowid = 0;
   83736   }
   83737 }
   83738 #endif
   83739 
   83740 /* Initialize the BLOB value of a ROWID
   83741 */
   83742 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   83743 static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
   83744   assert( db!=0 );
   83745   if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
   83746   p->u.aRowid = sqlite3DbMallocRaw(db, n);
   83747   if( p->u.aRowid ){
   83748     p->nRowid = n;
   83749     memcpy(p->u.aRowid, pData, n);
   83750   }else{
   83751     p->nRowid = 0;
   83752   }
   83753 }
   83754 #endif
   83755 
   83756 /* Initialize the INTEGER value of a ROWID.
   83757 */
   83758 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   83759 static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){
   83760   assert( db!=0 );
   83761   if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
   83762   p->nRowid = 0;
   83763   p->u.iRowid = iRowid;
   83764 }
   83765 #endif
   83766 
   83767 
   83768 /*
   83769 ** Copy the contents of object (*pFrom) into (*pTo).
   83770 */
   83771 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   83772 static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
   83773   pTo->isPSample = pFrom->isPSample;
   83774   pTo->iCol = pFrom->iCol;
   83775   pTo->iHash = pFrom->iHash;
   83776   memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
   83777   memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
   83778   memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
   83779   if( pFrom->nRowid ){
   83780     sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
   83781   }else{
   83782     sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
   83783   }
   83784 }
   83785 #endif
   83786 
   83787 /*
   83788 ** Reclaim all memory of a Stat4Accum structure.
   83789 */
   83790 static void stat4Destructor(void *pOld){
   83791   Stat4Accum *p = (Stat4Accum*)pOld;
   83792 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   83793   int i;
   83794   for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
   83795   for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
   83796   sampleClear(p->db, &p->current);
   83797 #endif
   83798   sqlite3DbFree(p->db, p);
   83799 }
   83800 
   83801 /*
   83802 ** Implementation of the stat_init(N,K,C) SQL function. The three parameters
   83803 ** are:
   83804 **     N:    The number of columns in the index including the rowid/pk (note 1)
   83805 **     K:    The number of columns in the index excluding the rowid/pk.
   83806 **     C:    The number of rows in the index (note 2)
   83807 **
   83808 ** Note 1:  In the special case of the covering index that implements a
   83809 ** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the
   83810 ** total number of columns in the table.
   83811 **
   83812 ** Note 2:  C is only used for STAT3 and STAT4.
   83813 **
   83814 ** For indexes on ordinary rowid tables, N==K+1.  But for indexes on
   83815 ** WITHOUT ROWID tables, N=K+P where P is the number of columns in the
   83816 ** PRIMARY KEY of the table.  The covering index that implements the
   83817 ** original WITHOUT ROWID table as N==K as a special case.
   83818 **
   83819 ** This routine allocates the Stat4Accum object in heap memory. The return
   83820 ** value is a pointer to the the Stat4Accum object encoded as a blob (i.e.
   83821 ** the size of the blob is sizeof(void*) bytes).
   83822 */
   83823 static void statInit(
   83824   sqlite3_context *context,
   83825   int argc,
   83826   sqlite3_value **argv
   83827 ){
   83828   Stat4Accum *p;
   83829   int nCol;                       /* Number of columns in index being sampled */
   83830   int nKeyCol;                    /* Number of key columns */
   83831   int nColUp;                     /* nCol rounded up for alignment */
   83832   int n;                          /* Bytes of space to allocate */
   83833   sqlite3 *db;                    /* Database connection */
   83834 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   83835   int mxSample = SQLITE_STAT4_SAMPLES;
   83836 #endif
   83837 
   83838   /* Decode the three function arguments */
   83839   UNUSED_PARAMETER(argc);
   83840   nCol = sqlite3_value_int(argv[0]);
   83841   assert( nCol>0 );
   83842   nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
   83843   nKeyCol = sqlite3_value_int(argv[1]);
   83844   assert( nKeyCol<=nCol );
   83845   assert( nKeyCol>0 );
   83846 
   83847   /* Allocate the space required for the Stat4Accum object */
   83848   n = sizeof(*p)
   83849     + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anEq */
   83850     + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anDLt */
   83851 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   83852     + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anLt */
   83853     + sizeof(Stat4Sample)*(nCol+mxSample)     /* Stat4Accum.aBest[], a[] */
   83854     + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
   83855 #endif
   83856   ;
   83857   db = sqlite3_context_db_handle(context);
   83858   p = sqlite3DbMallocZero(db, n);
   83859   if( p==0 ){
   83860     sqlite3_result_error_nomem(context);
   83861     return;
   83862   }
   83863 
   83864   p->db = db;
   83865   p->nRow = 0;
   83866   p->nCol = nCol;
   83867   p->nKeyCol = nKeyCol;
   83868   p->current.anDLt = (tRowcnt*)&p[1];
   83869   p->current.anEq = &p->current.anDLt[nColUp];
   83870 
   83871 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   83872   {
   83873     u8 *pSpace;                     /* Allocated space not yet assigned */
   83874     int i;                          /* Used to iterate through p->aSample[] */
   83875 
   83876     p->iGet = -1;
   83877     p->mxSample = mxSample;
   83878     p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[2])/(mxSample/3+1) + 1);
   83879     p->current.anLt = &p->current.anEq[nColUp];
   83880     p->iPrn = nCol*0x689e962d ^ sqlite3_value_int(argv[2])*0xd0944565;
   83881 
   83882     /* Set up the Stat4Accum.a[] and aBest[] arrays */
   83883     p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
   83884     p->aBest = &p->a[mxSample];
   83885     pSpace = (u8*)(&p->a[mxSample+nCol]);
   83886     for(i=0; i<(mxSample+nCol); i++){
   83887       p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
   83888       p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
   83889       p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
   83890     }
   83891     assert( (pSpace - (u8*)p)==n );
   83892 
   83893     for(i=0; i<nCol; i++){
   83894       p->aBest[i].iCol = i;
   83895     }
   83896   }
   83897 #endif
   83898 
   83899   /* Return a pointer to the allocated object to the caller */
   83900   sqlite3_result_blob(context, p, sizeof(p), stat4Destructor);
   83901 }
   83902 static const FuncDef statInitFuncdef = {
   83903   2+IsStat34,      /* nArg */
   83904   SQLITE_UTF8,     /* funcFlags */
   83905   0,               /* pUserData */
   83906   0,               /* pNext */
   83907   statInit,        /* xFunc */
   83908   0,               /* xStep */
   83909   0,               /* xFinalize */
   83910   "stat_init",     /* zName */
   83911   0,               /* pHash */
   83912   0                /* pDestructor */
   83913 };
   83914 
   83915 #ifdef SQLITE_ENABLE_STAT4
   83916 /*
   83917 ** pNew and pOld are both candidate non-periodic samples selected for
   83918 ** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
   83919 ** considering only any trailing columns and the sample hash value, this
   83920 ** function returns true if sample pNew is to be preferred over pOld.
   83921 ** In other words, if we assume that the cardinalities of the selected
   83922 ** column for pNew and pOld are equal, is pNew to be preferred over pOld.
   83923 **
   83924 ** This function assumes that for each argument sample, the contents of
   83925 ** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
   83926 */
   83927 static int sampleIsBetterPost(
   83928   Stat4Accum *pAccum,
   83929   Stat4Sample *pNew,
   83930   Stat4Sample *pOld
   83931 ){
   83932   int nCol = pAccum->nCol;
   83933   int i;
   83934   assert( pNew->iCol==pOld->iCol );
   83935   for(i=pNew->iCol+1; i<nCol; i++){
   83936     if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
   83937     if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
   83938   }
   83939   if( pNew->iHash>pOld->iHash ) return 1;
   83940   return 0;
   83941 }
   83942 #endif
   83943 
   83944 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   83945 /*
   83946 ** Return true if pNew is to be preferred over pOld.
   83947 **
   83948 ** This function assumes that for each argument sample, the contents of
   83949 ** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
   83950 */
   83951 static int sampleIsBetter(
   83952   Stat4Accum *pAccum,
   83953   Stat4Sample *pNew,
   83954   Stat4Sample *pOld
   83955 ){
   83956   tRowcnt nEqNew = pNew->anEq[pNew->iCol];
   83957   tRowcnt nEqOld = pOld->anEq[pOld->iCol];
   83958 
   83959   assert( pOld->isPSample==0 && pNew->isPSample==0 );
   83960   assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
   83961 
   83962   if( (nEqNew>nEqOld) ) return 1;
   83963 #ifdef SQLITE_ENABLE_STAT4
   83964   if( nEqNew==nEqOld ){
   83965     if( pNew->iCol<pOld->iCol ) return 1;
   83966     return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
   83967   }
   83968   return 0;
   83969 #else
   83970   return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
   83971 #endif
   83972 }
   83973 
   83974 /*
   83975 ** Copy the contents of sample *pNew into the p->a[] array. If necessary,
   83976 ** remove the least desirable sample from p->a[] to make room.
   83977 */
   83978 static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
   83979   Stat4Sample *pSample = 0;
   83980   int i;
   83981 
   83982   assert( IsStat4 || nEqZero==0 );
   83983 
   83984 #ifdef SQLITE_ENABLE_STAT4
   83985   if( pNew->isPSample==0 ){
   83986     Stat4Sample *pUpgrade = 0;
   83987     assert( pNew->anEq[pNew->iCol]>0 );
   83988 
   83989     /* This sample is being added because the prefix that ends in column
   83990     ** iCol occurs many times in the table. However, if we have already
   83991     ** added a sample that shares this prefix, there is no need to add
   83992     ** this one. Instead, upgrade the priority of the highest priority
   83993     ** existing sample that shares this prefix.  */
   83994     for(i=p->nSample-1; i>=0; i--){
   83995       Stat4Sample *pOld = &p->a[i];
   83996       if( pOld->anEq[pNew->iCol]==0 ){
   83997         if( pOld->isPSample ) return;
   83998         assert( pOld->iCol>pNew->iCol );
   83999         assert( sampleIsBetter(p, pNew, pOld) );
   84000         if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
   84001           pUpgrade = pOld;
   84002         }
   84003       }
   84004     }
   84005     if( pUpgrade ){
   84006       pUpgrade->iCol = pNew->iCol;
   84007       pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
   84008       goto find_new_min;
   84009     }
   84010   }
   84011 #endif
   84012 
   84013   /* If necessary, remove sample iMin to make room for the new sample. */
   84014   if( p->nSample>=p->mxSample ){
   84015     Stat4Sample *pMin = &p->a[p->iMin];
   84016     tRowcnt *anEq = pMin->anEq;
   84017     tRowcnt *anLt = pMin->anLt;
   84018     tRowcnt *anDLt = pMin->anDLt;
   84019     sampleClear(p->db, pMin);
   84020     memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
   84021     pSample = &p->a[p->nSample-1];
   84022     pSample->nRowid = 0;
   84023     pSample->anEq = anEq;
   84024     pSample->anDLt = anDLt;
   84025     pSample->anLt = anLt;
   84026     p->nSample = p->mxSample-1;
   84027   }
   84028 
   84029   /* The "rows less-than" for the rowid column must be greater than that
   84030   ** for the last sample in the p->a[] array. Otherwise, the samples would
   84031   ** be out of order. */
   84032 #ifdef SQLITE_ENABLE_STAT4
   84033   assert( p->nSample==0
   84034        || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
   84035 #endif
   84036 
   84037   /* Insert the new sample */
   84038   pSample = &p->a[p->nSample];
   84039   sampleCopy(p, pSample, pNew);
   84040   p->nSample++;
   84041 
   84042   /* Zero the first nEqZero entries in the anEq[] array. */
   84043   memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
   84044 
   84045 #ifdef SQLITE_ENABLE_STAT4
   84046  find_new_min:
   84047 #endif
   84048   if( p->nSample>=p->mxSample ){
   84049     int iMin = -1;
   84050     for(i=0; i<p->mxSample; i++){
   84051       if( p->a[i].isPSample ) continue;
   84052       if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
   84053         iMin = i;
   84054       }
   84055     }
   84056     assert( iMin>=0 );
   84057     p->iMin = iMin;
   84058   }
   84059 }
   84060 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
   84061 
   84062 /*
   84063 ** Field iChng of the index being scanned has changed. So at this point
   84064 ** p->current contains a sample that reflects the previous row of the
   84065 ** index. The value of anEq[iChng] and subsequent anEq[] elements are
   84066 ** correct at this point.
   84067 */
   84068 static void samplePushPrevious(Stat4Accum *p, int iChng){
   84069 #ifdef SQLITE_ENABLE_STAT4
   84070   int i;
   84071 
   84072   /* Check if any samples from the aBest[] array should be pushed
   84073   ** into IndexSample.a[] at this point.  */
   84074   for(i=(p->nCol-2); i>=iChng; i--){
   84075     Stat4Sample *pBest = &p->aBest[i];
   84076     pBest->anEq[i] = p->current.anEq[i];
   84077     if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
   84078       sampleInsert(p, pBest, i);
   84079     }
   84080   }
   84081 
   84082   /* Update the anEq[] fields of any samples already collected. */
   84083   for(i=p->nSample-1; i>=0; i--){
   84084     int j;
   84085     for(j=iChng; j<p->nCol; j++){
   84086       if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
   84087     }
   84088   }
   84089 #endif
   84090 
   84091 #if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
   84092   if( iChng==0 ){
   84093     tRowcnt nLt = p->current.anLt[0];
   84094     tRowcnt nEq = p->current.anEq[0];
   84095 
   84096     /* Check if this is to be a periodic sample. If so, add it. */
   84097     if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
   84098       p->current.isPSample = 1;
   84099       sampleInsert(p, &p->current, 0);
   84100       p->current.isPSample = 0;
   84101     }else
   84102 
   84103     /* Or if it is a non-periodic sample. Add it in this case too. */
   84104     if( p->nSample<p->mxSample
   84105      || sampleIsBetter(p, &p->current, &p->a[p->iMin])
   84106     ){
   84107       sampleInsert(p, &p->current, 0);
   84108     }
   84109   }
   84110 #endif
   84111 
   84112 #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
   84113   UNUSED_PARAMETER( p );
   84114   UNUSED_PARAMETER( iChng );
   84115 #endif
   84116 }
   84117 
   84118 /*
   84119 ** Implementation of the stat_push SQL function:  stat_push(P,C,R)
   84120 ** Arguments:
   84121 **
   84122 **    P     Pointer to the Stat4Accum object created by stat_init()
   84123 **    C     Index of left-most column to differ from previous row
   84124 **    R     Rowid for the current row.  Might be a key record for
   84125 **          WITHOUT ROWID tables.
   84126 **
   84127 ** This SQL function always returns NULL.  It's purpose it to accumulate
   84128 ** statistical data and/or samples in the Stat4Accum object about the
   84129 ** index being analyzed.  The stat_get() SQL function will later be used to
   84130 ** extract relevant information for constructing the sqlite_statN tables.
   84131 **
   84132 ** The R parameter is only used for STAT3 and STAT4
   84133 */
   84134 static void statPush(
   84135   sqlite3_context *context,
   84136   int argc,
   84137   sqlite3_value **argv
   84138 ){
   84139   int i;
   84140 
   84141   /* The three function arguments */
   84142   Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
   84143   int iChng = sqlite3_value_int(argv[1]);
   84144 
   84145   UNUSED_PARAMETER( argc );
   84146   UNUSED_PARAMETER( context );
   84147   assert( p->nCol>0 );
   84148   assert( iChng<p->nCol );
   84149 
   84150   if( p->nRow==0 ){
   84151     /* This is the first call to this function. Do initialization. */
   84152     for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
   84153   }else{
   84154     /* Second and subsequent calls get processed here */
   84155     samplePushPrevious(p, iChng);
   84156 
   84157     /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
   84158     ** to the current row of the index. */
   84159     for(i=0; i<iChng; i++){
   84160       p->current.anEq[i]++;
   84161     }
   84162     for(i=iChng; i<p->nCol; i++){
   84163       p->current.anDLt[i]++;
   84164 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   84165       p->current.anLt[i] += p->current.anEq[i];
   84166 #endif
   84167       p->current.anEq[i] = 1;
   84168     }
   84169   }
   84170   p->nRow++;
   84171 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   84172   if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
   84173     sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
   84174   }else{
   84175     sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
   84176                                        sqlite3_value_blob(argv[2]));
   84177   }
   84178   p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
   84179 #endif
   84180 
   84181 #ifdef SQLITE_ENABLE_STAT4
   84182   {
   84183     tRowcnt nLt = p->current.anLt[p->nCol-1];
   84184 
   84185     /* Check if this is to be a periodic sample. If so, add it. */
   84186     if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
   84187       p->current.isPSample = 1;
   84188       p->current.iCol = 0;
   84189       sampleInsert(p, &p->current, p->nCol-1);
   84190       p->current.isPSample = 0;
   84191     }
   84192 
   84193     /* Update the aBest[] array. */
   84194     for(i=0; i<(p->nCol-1); i++){
   84195       p->current.iCol = i;
   84196       if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
   84197         sampleCopy(p, &p->aBest[i], &p->current);
   84198       }
   84199     }
   84200   }
   84201 #endif
   84202 }
   84203 static const FuncDef statPushFuncdef = {
   84204   2+IsStat34,      /* nArg */
   84205   SQLITE_UTF8,     /* funcFlags */
   84206   0,               /* pUserData */
   84207   0,               /* pNext */
   84208   statPush,        /* xFunc */
   84209   0,               /* xStep */
   84210   0,               /* xFinalize */
   84211   "stat_push",     /* zName */
   84212   0,               /* pHash */
   84213   0                /* pDestructor */
   84214 };
   84215 
   84216 #define STAT_GET_STAT1 0          /* "stat" column of stat1 table */
   84217 #define STAT_GET_ROWID 1          /* "rowid" column of stat[34] entry */
   84218 #define STAT_GET_NEQ   2          /* "neq" column of stat[34] entry */
   84219 #define STAT_GET_NLT   3          /* "nlt" column of stat[34] entry */
   84220 #define STAT_GET_NDLT  4          /* "ndlt" column of stat[34] entry */
   84221 
   84222 /*
   84223 ** Implementation of the stat_get(P,J) SQL function.  This routine is
   84224 ** used to query statistical information that has been gathered into
   84225 ** the Stat4Accum object by prior calls to stat_push().  The P parameter
   84226 ** is a BLOB which is decoded into a pointer to the Stat4Accum objects.
   84227 ** The content to returned is determined by the parameter J
   84228 ** which is one of the STAT_GET_xxxx values defined above.
   84229 **
   84230 ** If neither STAT3 nor STAT4 are enabled, then J is always
   84231 ** STAT_GET_STAT1 and is hence omitted and this routine becomes
   84232 ** a one-parameter function, stat_get(P), that always returns the
   84233 ** stat1 table entry information.
   84234 */
   84235 static void statGet(
   84236   sqlite3_context *context,
   84237   int argc,
   84238   sqlite3_value **argv
   84239 ){
   84240   Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
   84241 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   84242   /* STAT3 and STAT4 have a parameter on this routine. */
   84243   int eCall = sqlite3_value_int(argv[1]);
   84244   assert( argc==2 );
   84245   assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
   84246        || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
   84247        || eCall==STAT_GET_NDLT
   84248   );
   84249   if( eCall==STAT_GET_STAT1 )
   84250 #else
   84251   assert( argc==1 );
   84252 #endif
   84253   {
   84254     /* Return the value to store in the "stat" column of the sqlite_stat1
   84255     ** table for this index.
   84256     **
   84257     ** The value is a string composed of a list of integers describing
   84258     ** the index. The first integer in the list is the total number of
   84259     ** entries in the index. There is one additional integer in the list
   84260     ** for each indexed column. This additional integer is an estimate of
   84261     ** the number of rows matched by a stabbing query on the index using
   84262     ** a key with the corresponding number of fields. In other words,
   84263     ** if the index is on columns (a,b) and the sqlite_stat1 value is
   84264     ** "100 10 2", then SQLite estimates that:
   84265     **
   84266     **   * the index contains 100 rows,
   84267     **   * "WHERE a=?" matches 10 rows, and
   84268     **   * "WHERE a=? AND b=?" matches 2 rows.
   84269     **
   84270     ** If D is the count of distinct values and K is the total number of
   84271     ** rows, then each estimate is computed as:
   84272     **
   84273     **        I = (K+D-1)/D
   84274     */
   84275     char *z;
   84276     int i;
   84277 
   84278     char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 );
   84279     if( zRet==0 ){
   84280       sqlite3_result_error_nomem(context);
   84281       return;
   84282     }
   84283 
   84284     sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
   84285     z = zRet + sqlite3Strlen30(zRet);
   84286     for(i=0; i<p->nKeyCol; i++){
   84287       u64 nDistinct = p->current.anDLt[i] + 1;
   84288       u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
   84289       sqlite3_snprintf(24, z, " %llu", iVal);
   84290       z += sqlite3Strlen30(z);
   84291       assert( p->current.anEq[i] );
   84292     }
   84293     assert( z[0]=='\0' && z>zRet );
   84294 
   84295     sqlite3_result_text(context, zRet, -1, sqlite3_free);
   84296   }
   84297 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   84298   else if( eCall==STAT_GET_ROWID ){
   84299     if( p->iGet<0 ){
   84300       samplePushPrevious(p, 0);
   84301       p->iGet = 0;
   84302     }
   84303     if( p->iGet<p->nSample ){
   84304       Stat4Sample *pS = p->a + p->iGet;
   84305       if( pS->nRowid==0 ){
   84306         sqlite3_result_int64(context, pS->u.iRowid);
   84307       }else{
   84308         sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
   84309                             SQLITE_TRANSIENT);
   84310       }
   84311     }
   84312   }else{
   84313     tRowcnt *aCnt = 0;
   84314 
   84315     assert( p->iGet<p->nSample );
   84316     switch( eCall ){
   84317       case STAT_GET_NEQ:  aCnt = p->a[p->iGet].anEq; break;
   84318       case STAT_GET_NLT:  aCnt = p->a[p->iGet].anLt; break;
   84319       default: {
   84320         aCnt = p->a[p->iGet].anDLt;
   84321         p->iGet++;
   84322         break;
   84323       }
   84324     }
   84325 
   84326     if( IsStat3 ){
   84327       sqlite3_result_int64(context, (i64)aCnt[0]);
   84328     }else{
   84329       char *zRet = sqlite3MallocZero(p->nCol * 25);
   84330       if( zRet==0 ){
   84331         sqlite3_result_error_nomem(context);
   84332       }else{
   84333         int i;
   84334         char *z = zRet;
   84335         for(i=0; i<p->nCol; i++){
   84336           sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
   84337           z += sqlite3Strlen30(z);
   84338         }
   84339         assert( z[0]=='\0' && z>zRet );
   84340         z[-1] = '\0';
   84341         sqlite3_result_text(context, zRet, -1, sqlite3_free);
   84342       }
   84343     }
   84344   }
   84345 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
   84346 #ifndef SQLITE_DEBUG
   84347   UNUSED_PARAMETER( argc );
   84348 #endif
   84349 }
   84350 static const FuncDef statGetFuncdef = {
   84351   1+IsStat34,      /* nArg */
   84352   SQLITE_UTF8,     /* funcFlags */
   84353   0,               /* pUserData */
   84354   0,               /* pNext */
   84355   statGet,         /* xFunc */
   84356   0,               /* xStep */
   84357   0,               /* xFinalize */
   84358   "stat_get",      /* zName */
   84359   0,               /* pHash */
   84360   0                /* pDestructor */
   84361 };
   84362 
   84363 static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
   84364   assert( regOut!=regStat4 && regOut!=regStat4+1 );
   84365 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   84366   sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
   84367 #elif SQLITE_DEBUG
   84368   assert( iParam==STAT_GET_STAT1 );
   84369 #else
   84370   UNUSED_PARAMETER( iParam );
   84371 #endif
   84372   sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4, regOut);
   84373   sqlite3VdbeChangeP4(v, -1, (char*)&statGetFuncdef, P4_FUNCDEF);
   84374   sqlite3VdbeChangeP5(v, 1 + IsStat34);
   84375 }
   84376 
   84377 /*
   84378 ** Generate code to do an analysis of all indices associated with
   84379 ** a single table.
   84380 */
   84381 static void analyzeOneTable(
   84382   Parse *pParse,   /* Parser context */
   84383   Table *pTab,     /* Table whose indices are to be analyzed */
   84384   Index *pOnlyIdx, /* If not NULL, only analyze this one index */
   84385   int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
   84386   int iMem,        /* Available memory locations begin here */
   84387   int iTab         /* Next available cursor */
   84388 ){
   84389   sqlite3 *db = pParse->db;    /* Database handle */
   84390   Index *pIdx;                 /* An index to being analyzed */
   84391   int iIdxCur;                 /* Cursor open on index being analyzed */
   84392   int iTabCur;                 /* Table cursor */
   84393   Vdbe *v;                     /* The virtual machine being built up */
   84394   int i;                       /* Loop counter */
   84395   int jZeroRows = -1;          /* Jump from here if number of rows is zero */
   84396   int iDb;                     /* Index of database containing pTab */
   84397   u8 needTableCnt = 1;         /* True to count the table */
   84398   int regNewRowid = iMem++;    /* Rowid for the inserted record */
   84399   int regStat4 = iMem++;       /* Register to hold Stat4Accum object */
   84400   int regChng = iMem++;        /* Index of changed index field */
   84401 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   84402   int regRowid = iMem++;       /* Rowid argument passed to stat_push() */
   84403 #endif
   84404   int regTemp = iMem++;        /* Temporary use register */
   84405   int regTabname = iMem++;     /* Register containing table name */
   84406   int regIdxname = iMem++;     /* Register containing index name */
   84407   int regStat1 = iMem++;       /* Value for the stat column of sqlite_stat1 */
   84408   int regPrev = iMem;          /* MUST BE LAST (see below) */
   84409 
   84410   pParse->nMem = MAX(pParse->nMem, iMem);
   84411   v = sqlite3GetVdbe(pParse);
   84412   if( v==0 || NEVER(pTab==0) ){
   84413     return;
   84414   }
   84415   if( pTab->tnum==0 ){
   84416     /* Do not gather statistics on views or virtual tables */
   84417     return;
   84418   }
   84419   if( sqlite3_strnicmp(pTab->zName, "sqlite_", 7)==0 ){
   84420     /* Do not gather statistics on system tables */
   84421     return;
   84422   }
   84423   assert( sqlite3BtreeHoldsAllMutexes(db) );
   84424   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   84425   assert( iDb>=0 );
   84426   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   84427 #ifndef SQLITE_OMIT_AUTHORIZATION
   84428   if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
   84429       db->aDb[iDb].zName ) ){
   84430     return;
   84431   }
   84432 #endif
   84433 
   84434   /* Establish a read-lock on the table at the shared-cache level.
   84435   ** Open a read-only cursor on the table. Also allocate a cursor number
   84436   ** to use for scanning indexes (iIdxCur). No index cursor is opened at
   84437   ** this time though.  */
   84438   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
   84439   iTabCur = iTab++;
   84440   iIdxCur = iTab++;
   84441   pParse->nTab = MAX(pParse->nTab, iTab);
   84442   sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
   84443   sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
   84444 
   84445   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   84446     int nCol;                     /* Number of columns in pIdx. "N" */
   84447     int addrRewind;               /* Address of "OP_Rewind iIdxCur" */
   84448     int addrNextRow;              /* Address of "next_row:" */
   84449     const char *zIdxName;         /* Name of the index */
   84450     int nColTest;                 /* Number of columns to test for changes */
   84451 
   84452     if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
   84453     if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
   84454     if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){
   84455       nCol = pIdx->nKeyCol;
   84456       zIdxName = pTab->zName;
   84457       nColTest = nCol - 1;
   84458     }else{
   84459       nCol = pIdx->nColumn;
   84460       zIdxName = pIdx->zName;
   84461       nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
   84462     }
   84463 
   84464     /* Populate the register containing the index name. */
   84465     sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, zIdxName, 0);
   84466     VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
   84467 
   84468     /*
   84469     ** Pseudo-code for loop that calls stat_push():
   84470     **
   84471     **   Rewind csr
   84472     **   if eof(csr) goto end_of_scan;
   84473     **   regChng = 0
   84474     **   goto chng_addr_0;
   84475     **
   84476     **  next_row:
   84477     **   regChng = 0
   84478     **   if( idx(0) != regPrev(0) ) goto chng_addr_0
   84479     **   regChng = 1
   84480     **   if( idx(1) != regPrev(1) ) goto chng_addr_1
   84481     **   ...
   84482     **   regChng = N
   84483     **   goto chng_addr_N
   84484     **
   84485     **  chng_addr_0:
   84486     **   regPrev(0) = idx(0)
   84487     **  chng_addr_1:
   84488     **   regPrev(1) = idx(1)
   84489     **  ...
   84490     **
   84491     **  endDistinctTest:
   84492     **   regRowid = idx(rowid)
   84493     **   stat_push(P, regChng, regRowid)
   84494     **   Next csr
   84495     **   if !eof(csr) goto next_row;
   84496     **
   84497     **  end_of_scan:
   84498     */
   84499 
   84500     /* Make sure there are enough memory cells allocated to accommodate
   84501     ** the regPrev array and a trailing rowid (the rowid slot is required
   84502     ** when building a record to insert into the sample column of
   84503     ** the sqlite_stat4 table.  */
   84504     pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);
   84505 
   84506     /* Open a read-only cursor on the index being analyzed. */
   84507     assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
   84508     sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
   84509     sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
   84510     VdbeComment((v, "%s", pIdx->zName));
   84511 
   84512     /* Invoke the stat_init() function. The arguments are:
   84513     **
   84514     **    (1) the number of columns in the index including the rowid
   84515     **        (or for a WITHOUT ROWID table, the number of PK columns),
   84516     **    (2) the number of columns in the key without the rowid/pk
   84517     **    (3) the number of rows in the index,
   84518     **
   84519     **
   84520     ** The third argument is only used for STAT3 and STAT4
   84521     */
   84522 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   84523     sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+3);
   84524 #endif
   84525     sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat4+1);
   84526     sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regStat4+2);
   84527     sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4+1, regStat4);
   84528     sqlite3VdbeChangeP4(v, -1, (char*)&statInitFuncdef, P4_FUNCDEF);
   84529     sqlite3VdbeChangeP5(v, 2+IsStat34);
   84530 
   84531     /* Implementation of the following:
   84532     **
   84533     **   Rewind csr
   84534     **   if eof(csr) goto end_of_scan;
   84535     **   regChng = 0
   84536     **   goto next_push_0;
   84537     **
   84538     */
   84539     addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
   84540     VdbeCoverage(v);
   84541     sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
   84542     addrNextRow = sqlite3VdbeCurrentAddr(v);
   84543 
   84544     if( nColTest>0 ){
   84545       int endDistinctTest = sqlite3VdbeMakeLabel(v);
   84546       int *aGotoChng;               /* Array of jump instruction addresses */
   84547       aGotoChng = sqlite3DbMallocRaw(db, sizeof(int)*nColTest);
   84548       if( aGotoChng==0 ) continue;
   84549 
   84550       /*
   84551       **  next_row:
   84552       **   regChng = 0
   84553       **   if( idx(0) != regPrev(0) ) goto chng_addr_0
   84554       **   regChng = 1
   84555       **   if( idx(1) != regPrev(1) ) goto chng_addr_1
   84556       **   ...
   84557       **   regChng = N
   84558       **   goto endDistinctTest
   84559       */
   84560       sqlite3VdbeAddOp0(v, OP_Goto);
   84561       addrNextRow = sqlite3VdbeCurrentAddr(v);
   84562       if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
   84563         /* For a single-column UNIQUE index, once we have found a non-NULL
   84564         ** row, we know that all the rest will be distinct, so skip
   84565         ** subsequent distinctness tests. */
   84566         sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);
   84567         VdbeCoverage(v);
   84568       }
   84569       for(i=0; i<nColTest; i++){
   84570         char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
   84571         sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
   84572         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
   84573         aGotoChng[i] =
   84574         sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
   84575         sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
   84576         VdbeCoverage(v);
   84577       }
   84578       sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);
   84579       sqlite3VdbeAddOp2(v, OP_Goto, 0, endDistinctTest);
   84580 
   84581 
   84582       /*
   84583       **  chng_addr_0:
   84584       **   regPrev(0) = idx(0)
   84585       **  chng_addr_1:
   84586       **   regPrev(1) = idx(1)
   84587       **  ...
   84588       */
   84589       sqlite3VdbeJumpHere(v, addrNextRow-1);
   84590       for(i=0; i<nColTest; i++){
   84591         sqlite3VdbeJumpHere(v, aGotoChng[i]);
   84592         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
   84593       }
   84594       sqlite3VdbeResolveLabel(v, endDistinctTest);
   84595       sqlite3DbFree(db, aGotoChng);
   84596     }
   84597 
   84598     /*
   84599     **  chng_addr_N:
   84600     **   regRowid = idx(rowid)            // STAT34 only
   84601     **   stat_push(P, regChng, regRowid)  // 3rd parameter STAT34 only
   84602     **   Next csr
   84603     **   if !eof(csr) goto next_row;
   84604     */
   84605 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   84606     assert( regRowid==(regStat4+2) );
   84607     if( HasRowid(pTab) ){
   84608       sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
   84609     }else{
   84610       Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
   84611       int j, k, regKey;
   84612       regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
   84613       for(j=0; j<pPk->nKeyCol; j++){
   84614         k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
   84615         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
   84616         VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName));
   84617       }
   84618       sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
   84619       sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
   84620     }
   84621 #endif
   84622     assert( regChng==(regStat4+1) );
   84623     sqlite3VdbeAddOp3(v, OP_Function, 1, regStat4, regTemp);
   84624     sqlite3VdbeChangeP4(v, -1, (char*)&statPushFuncdef, P4_FUNCDEF);
   84625     sqlite3VdbeChangeP5(v, 2+IsStat34);
   84626     sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
   84627 
   84628     /* Add the entry to the stat1 table. */
   84629     callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
   84630     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "aaa", 0);
   84631     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
   84632     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
   84633     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   84634 
   84635     /* Add the entries to the stat3 or stat4 table. */
   84636 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   84637     {
   84638       int regEq = regStat1;
   84639       int regLt = regStat1+1;
   84640       int regDLt = regStat1+2;
   84641       int regSample = regStat1+3;
   84642       int regCol = regStat1+4;
   84643       int regSampleRowid = regCol + nCol;
   84644       int addrNext;
   84645       int addrIsNull;
   84646       u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
   84647 
   84648       pParse->nMem = MAX(pParse->nMem, regCol+nCol);
   84649 
   84650       addrNext = sqlite3VdbeCurrentAddr(v);
   84651       callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
   84652       addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
   84653       VdbeCoverage(v);
   84654       callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
   84655       callStatGet(v, regStat4, STAT_GET_NLT, regLt);
   84656       callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
   84657       sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
   84658       /* We know that the regSampleRowid row exists because it was read by
   84659       ** the previous loop.  Thus the not-found jump of seekOp will never
   84660       ** be taken */
   84661       VdbeCoverageNeverTaken(v);
   84662 #ifdef SQLITE_ENABLE_STAT3
   84663       sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
   84664                                       pIdx->aiColumn[0], regSample);
   84665 #else
   84666       for(i=0; i<nCol; i++){
   84667         i16 iCol = pIdx->aiColumn[i];
   84668         sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, iCol, regCol+i);
   84669       }
   84670       sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample);
   84671 #endif
   84672       sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
   84673       sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
   84674       sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
   84675       sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
   84676       sqlite3VdbeJumpHere(v, addrIsNull);
   84677     }
   84678 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
   84679 
   84680     /* End of analysis */
   84681     sqlite3VdbeJumpHere(v, addrRewind);
   84682   }
   84683 
   84684 
   84685   /* Create a single sqlite_stat1 entry containing NULL as the index
   84686   ** name and the row count as the content.
   84687   */
   84688   if( pOnlyIdx==0 && needTableCnt ){
   84689     VdbeComment((v, "%s", pTab->zName));
   84690     sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
   84691     jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
   84692     sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
   84693     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "aaa", 0);
   84694     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
   84695     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
   84696     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   84697     sqlite3VdbeJumpHere(v, jZeroRows);
   84698   }
   84699 }
   84700 
   84701 
   84702 /*
   84703 ** Generate code that will cause the most recent index analysis to
   84704 ** be loaded into internal hash tables where is can be used.
   84705 */
   84706 static void loadAnalysis(Parse *pParse, int iDb){
   84707   Vdbe *v = sqlite3GetVdbe(pParse);
   84708   if( v ){
   84709     sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
   84710   }
   84711 }
   84712 
   84713 /*
   84714 ** Generate code that will do an analysis of an entire database
   84715 */
   84716 static void analyzeDatabase(Parse *pParse, int iDb){
   84717   sqlite3 *db = pParse->db;
   84718   Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
   84719   HashElem *k;
   84720   int iStatCur;
   84721   int iMem;
   84722   int iTab;
   84723 
   84724   sqlite3BeginWriteOperation(pParse, 0, iDb);
   84725   iStatCur = pParse->nTab;
   84726   pParse->nTab += 3;
   84727   openStatTable(pParse, iDb, iStatCur, 0, 0);
   84728   iMem = pParse->nMem+1;
   84729   iTab = pParse->nTab;
   84730   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   84731   for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
   84732     Table *pTab = (Table*)sqliteHashData(k);
   84733     analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
   84734   }
   84735   loadAnalysis(pParse, iDb);
   84736 }
   84737 
   84738 /*
   84739 ** Generate code that will do an analysis of a single table in
   84740 ** a database.  If pOnlyIdx is not NULL then it is a single index
   84741 ** in pTab that should be analyzed.
   84742 */
   84743 static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
   84744   int iDb;
   84745   int iStatCur;
   84746 
   84747   assert( pTab!=0 );
   84748   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
   84749   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   84750   sqlite3BeginWriteOperation(pParse, 0, iDb);
   84751   iStatCur = pParse->nTab;
   84752   pParse->nTab += 3;
   84753   if( pOnlyIdx ){
   84754     openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
   84755   }else{
   84756     openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
   84757   }
   84758   analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
   84759   loadAnalysis(pParse, iDb);
   84760 }
   84761 
   84762 /*
   84763 ** Generate code for the ANALYZE command.  The parser calls this routine
   84764 ** when it recognizes an ANALYZE command.
   84765 **
   84766 **        ANALYZE                            -- 1
   84767 **        ANALYZE  <database>                -- 2
   84768 **        ANALYZE  ?<database>.?<tablename>  -- 3
   84769 **
   84770 ** Form 1 causes all indices in all attached databases to be analyzed.
   84771 ** Form 2 analyzes all indices the single database named.
   84772 ** Form 3 analyzes all indices associated with the named table.
   84773 */
   84774 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
   84775   sqlite3 *db = pParse->db;
   84776   int iDb;
   84777   int i;
   84778   char *z, *zDb;
   84779   Table *pTab;
   84780   Index *pIdx;
   84781   Token *pTableName;
   84782   Vdbe *v;
   84783 
   84784   /* Read the database schema. If an error occurs, leave an error message
   84785   ** and code in pParse and return NULL. */
   84786   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
   84787   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   84788     return;
   84789   }
   84790 
   84791   assert( pName2!=0 || pName1==0 );
   84792   if( pName1==0 ){
   84793     /* Form 1:  Analyze everything */
   84794     for(i=0; i<db->nDb; i++){
   84795       if( i==1 ) continue;  /* Do not analyze the TEMP database */
   84796       analyzeDatabase(pParse, i);
   84797     }
   84798   }else if( pName2->n==0 ){
   84799     /* Form 2:  Analyze the database or table named */
   84800     iDb = sqlite3FindDb(db, pName1);
   84801     if( iDb>=0 ){
   84802       analyzeDatabase(pParse, iDb);
   84803     }else{
   84804       z = sqlite3NameFromToken(db, pName1);
   84805       if( z ){
   84806         if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
   84807           analyzeTable(pParse, pIdx->pTable, pIdx);
   84808         }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
   84809           analyzeTable(pParse, pTab, 0);
   84810         }
   84811         sqlite3DbFree(db, z);
   84812       }
   84813     }
   84814   }else{
   84815     /* Form 3: Analyze the fully qualified table name */
   84816     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
   84817     if( iDb>=0 ){
   84818       zDb = db->aDb[iDb].zName;
   84819       z = sqlite3NameFromToken(db, pTableName);
   84820       if( z ){
   84821         if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
   84822           analyzeTable(pParse, pIdx->pTable, pIdx);
   84823         }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
   84824           analyzeTable(pParse, pTab, 0);
   84825         }
   84826         sqlite3DbFree(db, z);
   84827       }
   84828     }
   84829   }
   84830   v = sqlite3GetVdbe(pParse);
   84831   if( v ) sqlite3VdbeAddOp0(v, OP_Expire);
   84832 }
   84833 
   84834 /*
   84835 ** Used to pass information from the analyzer reader through to the
   84836 ** callback routine.
   84837 */
   84838 typedef struct analysisInfo analysisInfo;
   84839 struct analysisInfo {
   84840   sqlite3 *db;
   84841   const char *zDatabase;
   84842 };
   84843 
   84844 /*
   84845 ** The first argument points to a nul-terminated string containing a
   84846 ** list of space separated integers. Read the first nOut of these into
   84847 ** the array aOut[].
   84848 */
   84849 static void decodeIntArray(
   84850   char *zIntArray,       /* String containing int array to decode */
   84851   int nOut,              /* Number of slots in aOut[] */
   84852   tRowcnt *aOut,         /* Store integers here */
   84853   LogEst *aLog,          /* Or, if aOut==0, here */
   84854   Index *pIndex          /* Handle extra flags for this index, if not NULL */
   84855 ){
   84856   char *z = zIntArray;
   84857   int c;
   84858   int i;
   84859   tRowcnt v;
   84860 
   84861 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   84862   if( z==0 ) z = "";
   84863 #else
   84864   if( NEVER(z==0) ) z = "";
   84865 #endif
   84866   for(i=0; *z && i<nOut; i++){
   84867     v = 0;
   84868     while( (c=z[0])>='0' && c<='9' ){
   84869       v = v*10 + c - '0';
   84870       z++;
   84871     }
   84872 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   84873     if( aOut ){
   84874       aOut[i] = v;
   84875     }else
   84876 #else
   84877     assert( aOut==0 );
   84878     UNUSED_PARAMETER(aOut);
   84879 #endif
   84880     {
   84881       aLog[i] = sqlite3LogEst(v);
   84882     }
   84883     if( *z==' ' ) z++;
   84884   }
   84885 #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
   84886   assert( pIndex!=0 );
   84887 #else
   84888   if( pIndex )
   84889 #endif
   84890   while( z[0] ){
   84891     if( sqlite3_strglob("unordered*", z)==0 ){
   84892       pIndex->bUnordered = 1;
   84893     }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
   84894       pIndex->szIdxRow = sqlite3LogEst(sqlite3Atoi(z+3));
   84895     }
   84896 #ifdef SQLITE_ENABLE_COSTMULT
   84897     else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
   84898       pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
   84899     }
   84900 #endif
   84901     while( z[0]!=0 && z[0]!=' ' ) z++;
   84902     while( z[0]==' ' ) z++;
   84903   }
   84904 }
   84905 
   84906 /*
   84907 ** This callback is invoked once for each index when reading the
   84908 ** sqlite_stat1 table.
   84909 **
   84910 **     argv[0] = name of the table
   84911 **     argv[1] = name of the index (might be NULL)
   84912 **     argv[2] = results of analysis - on integer for each column
   84913 **
   84914 ** Entries for which argv[1]==NULL simply record the number of rows in
   84915 ** the table.
   84916 */
   84917 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
   84918   analysisInfo *pInfo = (analysisInfo*)pData;
   84919   Index *pIndex;
   84920   Table *pTable;
   84921   const char *z;
   84922 
   84923   assert( argc==3 );
   84924   UNUSED_PARAMETER2(NotUsed, argc);
   84925 
   84926   if( argv==0 || argv[0]==0 || argv[2]==0 ){
   84927     return 0;
   84928   }
   84929   pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
   84930   if( pTable==0 ){
   84931     return 0;
   84932   }
   84933   if( argv[1]==0 ){
   84934     pIndex = 0;
   84935   }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
   84936     pIndex = sqlite3PrimaryKeyIndex(pTable);
   84937   }else{
   84938     pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
   84939   }
   84940   z = argv[2];
   84941 
   84942   if( pIndex ){
   84943     pIndex->bUnordered = 0;
   84944     decodeIntArray((char*)z, pIndex->nKeyCol+1, 0, pIndex->aiRowLogEst, pIndex);
   84945     if( pIndex->pPartIdxWhere==0 ) pTable->nRowLogEst = pIndex->aiRowLogEst[0];
   84946   }else{
   84947     Index fakeIdx;
   84948     fakeIdx.szIdxRow = pTable->szTabRow;
   84949 #ifdef SQLITE_ENABLE_COSTMULT
   84950     fakeIdx.pTable = pTable;
   84951 #endif
   84952     decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
   84953     pTable->szTabRow = fakeIdx.szIdxRow;
   84954   }
   84955 
   84956   return 0;
   84957 }
   84958 
   84959 /*
   84960 ** If the Index.aSample variable is not NULL, delete the aSample[] array
   84961 ** and its contents.
   84962 */
   84963 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
   84964 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   84965   if( pIdx->aSample ){
   84966     int j;
   84967     for(j=0; j<pIdx->nSample; j++){
   84968       IndexSample *p = &pIdx->aSample[j];
   84969       sqlite3DbFree(db, p->p);
   84970     }
   84971     sqlite3DbFree(db, pIdx->aSample);
   84972   }
   84973   if( db && db->pnBytesFreed==0 ){
   84974     pIdx->nSample = 0;
   84975     pIdx->aSample = 0;
   84976   }
   84977 #else
   84978   UNUSED_PARAMETER(db);
   84979   UNUSED_PARAMETER(pIdx);
   84980 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
   84981 }
   84982 
   84983 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   84984 /*
   84985 ** Populate the pIdx->aAvgEq[] array based on the samples currently
   84986 ** stored in pIdx->aSample[].
   84987 */
   84988 static void initAvgEq(Index *pIdx){
   84989   if( pIdx ){
   84990     IndexSample *aSample = pIdx->aSample;
   84991     IndexSample *pFinal = &aSample[pIdx->nSample-1];
   84992     int iCol;
   84993     int nCol = 1;
   84994     if( pIdx->nSampleCol>1 ){
   84995       /* If this is stat4 data, then calculate aAvgEq[] values for all
   84996       ** sample columns except the last. The last is always set to 1, as
   84997       ** once the trailing PK fields are considered all index keys are
   84998       ** unique.  */
   84999       nCol = pIdx->nSampleCol-1;
   85000       pIdx->aAvgEq[nCol] = 1;
   85001     }
   85002     for(iCol=0; iCol<nCol; iCol++){
   85003       int i;                    /* Used to iterate through samples */
   85004       tRowcnt sumEq = 0;        /* Sum of the nEq values */
   85005       tRowcnt nSum = 0;         /* Number of terms contributing to sumEq */
   85006       tRowcnt avgEq = 0;
   85007       tRowcnt nDLt = pFinal->anDLt[iCol];
   85008 
   85009       /* Set nSum to the number of distinct (iCol+1) field prefixes that
   85010       ** occur in the stat4 table for this index before pFinal. Set
   85011       ** sumEq to the sum of the nEq values for column iCol for the same
   85012       ** set (adding the value only once where there exist dupicate
   85013       ** prefixes).  */
   85014       for(i=0; i<(pIdx->nSample-1); i++){
   85015         if( aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol] ){
   85016           sumEq += aSample[i].anEq[iCol];
   85017           nSum++;
   85018         }
   85019       }
   85020       if( nDLt>nSum ){
   85021         avgEq = (pFinal->anLt[iCol] - sumEq)/(nDLt - nSum);
   85022       }
   85023       if( avgEq==0 ) avgEq = 1;
   85024       pIdx->aAvgEq[iCol] = avgEq;
   85025     }
   85026   }
   85027 }
   85028 
   85029 /*
   85030 ** Look up an index by name.  Or, if the name of a WITHOUT ROWID table
   85031 ** is supplied instead, find the PRIMARY KEY index for that table.
   85032 */
   85033 static Index *findIndexOrPrimaryKey(
   85034   sqlite3 *db,
   85035   const char *zName,
   85036   const char *zDb
   85037 ){
   85038   Index *pIdx = sqlite3FindIndex(db, zName, zDb);
   85039   if( pIdx==0 ){
   85040     Table *pTab = sqlite3FindTable(db, zName, zDb);
   85041     if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
   85042   }
   85043   return pIdx;
   85044 }
   85045 
   85046 /*
   85047 ** Load the content from either the sqlite_stat4 or sqlite_stat3 table
   85048 ** into the relevant Index.aSample[] arrays.
   85049 **
   85050 ** Arguments zSql1 and zSql2 must point to SQL statements that return
   85051 ** data equivalent to the following (statements are different for stat3,
   85052 ** see the caller of this function for details):
   85053 **
   85054 **    zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
   85055 **    zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
   85056 **
   85057 ** where %Q is replaced with the database name before the SQL is executed.
   85058 */
   85059 static int loadStatTbl(
   85060   sqlite3 *db,                  /* Database handle */
   85061   int bStat3,                   /* Assume single column records only */
   85062   const char *zSql1,            /* SQL statement 1 (see above) */
   85063   const char *zSql2,            /* SQL statement 2 (see above) */
   85064   const char *zDb               /* Database name (e.g. "main") */
   85065 ){
   85066   int rc;                       /* Result codes from subroutines */
   85067   sqlite3_stmt *pStmt = 0;      /* An SQL statement being run */
   85068   char *zSql;                   /* Text of the SQL statement */
   85069   Index *pPrevIdx = 0;          /* Previous index in the loop */
   85070   IndexSample *pSample;         /* A slot in pIdx->aSample[] */
   85071 
   85072   assert( db->lookaside.bEnabled==0 );
   85073   zSql = sqlite3MPrintf(db, zSql1, zDb);
   85074   if( !zSql ){
   85075     return SQLITE_NOMEM;
   85076   }
   85077   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
   85078   sqlite3DbFree(db, zSql);
   85079   if( rc ) return rc;
   85080 
   85081   while( sqlite3_step(pStmt)==SQLITE_ROW ){
   85082     int nIdxCol = 1;              /* Number of columns in stat4 records */
   85083 
   85084     char *zIndex;   /* Index name */
   85085     Index *pIdx;    /* Pointer to the index object */
   85086     int nSample;    /* Number of samples */
   85087     int nByte;      /* Bytes of space required */
   85088     int i;          /* Bytes of space required */
   85089     tRowcnt *pSpace;
   85090 
   85091     zIndex = (char *)sqlite3_column_text(pStmt, 0);
   85092     if( zIndex==0 ) continue;
   85093     nSample = sqlite3_column_int(pStmt, 1);
   85094     pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
   85095     assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
   85096     /* Index.nSample is non-zero at this point if data has already been
   85097     ** loaded from the stat4 table. In this case ignore stat3 data.  */
   85098     if( pIdx==0 || pIdx->nSample ) continue;
   85099     if( bStat3==0 ){
   85100       assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
   85101       if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
   85102         nIdxCol = pIdx->nKeyCol;
   85103       }else{
   85104         nIdxCol = pIdx->nColumn;
   85105       }
   85106     }
   85107     pIdx->nSampleCol = nIdxCol;
   85108     nByte = sizeof(IndexSample) * nSample;
   85109     nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
   85110     nByte += nIdxCol * sizeof(tRowcnt);     /* Space for Index.aAvgEq[] */
   85111 
   85112     pIdx->aSample = sqlite3DbMallocZero(db, nByte);
   85113     if( pIdx->aSample==0 ){
   85114       sqlite3_finalize(pStmt);
   85115       return SQLITE_NOMEM;
   85116     }
   85117     pSpace = (tRowcnt*)&pIdx->aSample[nSample];
   85118     pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
   85119     for(i=0; i<nSample; i++){
   85120       pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
   85121       pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
   85122       pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
   85123     }
   85124     assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
   85125   }
   85126   rc = sqlite3_finalize(pStmt);
   85127   if( rc ) return rc;
   85128 
   85129   zSql = sqlite3MPrintf(db, zSql2, zDb);
   85130   if( !zSql ){
   85131     return SQLITE_NOMEM;
   85132   }
   85133   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
   85134   sqlite3DbFree(db, zSql);
   85135   if( rc ) return rc;
   85136 
   85137   while( sqlite3_step(pStmt)==SQLITE_ROW ){
   85138     char *zIndex;                 /* Index name */
   85139     Index *pIdx;                  /* Pointer to the index object */
   85140     int nCol = 1;                 /* Number of columns in index */
   85141 
   85142     zIndex = (char *)sqlite3_column_text(pStmt, 0);
   85143     if( zIndex==0 ) continue;
   85144     pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
   85145     if( pIdx==0 ) continue;
   85146     /* This next condition is true if data has already been loaded from
   85147     ** the sqlite_stat4 table. In this case ignore stat3 data.  */
   85148     nCol = pIdx->nSampleCol;
   85149     if( bStat3 && nCol>1 ) continue;
   85150     if( pIdx!=pPrevIdx ){
   85151       initAvgEq(pPrevIdx);
   85152       pPrevIdx = pIdx;
   85153     }
   85154     pSample = &pIdx->aSample[pIdx->nSample];
   85155     decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
   85156     decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
   85157     decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
   85158 
   85159     /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
   85160     ** This is in case the sample record is corrupted. In that case, the
   85161     ** sqlite3VdbeRecordCompare() may read up to two varints past the
   85162     ** end of the allocated buffer before it realizes it is dealing with
   85163     ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
   85164     ** a buffer overread.  */
   85165     pSample->n = sqlite3_column_bytes(pStmt, 4);
   85166     pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
   85167     if( pSample->p==0 ){
   85168       sqlite3_finalize(pStmt);
   85169       return SQLITE_NOMEM;
   85170     }
   85171     memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
   85172     pIdx->nSample++;
   85173   }
   85174   rc = sqlite3_finalize(pStmt);
   85175   if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
   85176   return rc;
   85177 }
   85178 
   85179 /*
   85180 ** Load content from the sqlite_stat4 and sqlite_stat3 tables into
   85181 ** the Index.aSample[] arrays of all indices.
   85182 */
   85183 static int loadStat4(sqlite3 *db, const char *zDb){
   85184   int rc = SQLITE_OK;             /* Result codes from subroutines */
   85185 
   85186   assert( db->lookaside.bEnabled==0 );
   85187   if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
   85188     rc = loadStatTbl(db, 0,
   85189       "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
   85190       "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
   85191       zDb
   85192     );
   85193   }
   85194 
   85195   if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
   85196     rc = loadStatTbl(db, 1,
   85197       "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx",
   85198       "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
   85199       zDb
   85200     );
   85201   }
   85202 
   85203   return rc;
   85204 }
   85205 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
   85206 
   85207 /*
   85208 ** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
   85209 ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
   85210 ** arrays. The contents of sqlite_stat3/4 are used to populate the
   85211 ** Index.aSample[] arrays.
   85212 **
   85213 ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
   85214 ** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined
   85215 ** during compilation and the sqlite_stat3/4 table is present, no data is
   85216 ** read from it.
   85217 **
   85218 ** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the
   85219 ** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
   85220 ** returned. However, in this case, data is read from the sqlite_stat1
   85221 ** table (if it is present) before returning.
   85222 **
   85223 ** If an OOM error occurs, this function always sets db->mallocFailed.
   85224 ** This means if the caller does not care about other errors, the return
   85225 ** code may be ignored.
   85226 */
   85227 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
   85228   analysisInfo sInfo;
   85229   HashElem *i;
   85230   char *zSql;
   85231   int rc;
   85232 
   85233   assert( iDb>=0 && iDb<db->nDb );
   85234   assert( db->aDb[iDb].pBt!=0 );
   85235 
   85236   /* Clear any prior statistics */
   85237   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   85238   for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
   85239     Index *pIdx = sqliteHashData(i);
   85240     sqlite3DefaultRowEst(pIdx);
   85241 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   85242     sqlite3DeleteIndexSamples(db, pIdx);
   85243     pIdx->aSample = 0;
   85244 #endif
   85245   }
   85246 
   85247   /* Check to make sure the sqlite_stat1 table exists */
   85248   sInfo.db = db;
   85249   sInfo.zDatabase = db->aDb[iDb].zName;
   85250   if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
   85251     return SQLITE_ERROR;
   85252   }
   85253 
   85254   /* Load new statistics out of the sqlite_stat1 table */
   85255   zSql = sqlite3MPrintf(db,
   85256       "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
   85257   if( zSql==0 ){
   85258     rc = SQLITE_NOMEM;
   85259   }else{
   85260     rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
   85261     sqlite3DbFree(db, zSql);
   85262   }
   85263 
   85264 
   85265   /* Load the statistics from the sqlite_stat4 table. */
   85266 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   85267   if( rc==SQLITE_OK ){
   85268     int lookasideEnabled = db->lookaside.bEnabled;
   85269     db->lookaside.bEnabled = 0;
   85270     rc = loadStat4(db, sInfo.zDatabase);
   85271     db->lookaside.bEnabled = lookasideEnabled;
   85272   }
   85273 #endif
   85274 
   85275   if( rc==SQLITE_NOMEM ){
   85276     db->mallocFailed = 1;
   85277   }
   85278   return rc;
   85279 }
   85280 
   85281 
   85282 #endif /* SQLITE_OMIT_ANALYZE */
   85283 
   85284 /************** End of analyze.c *********************************************/
   85285 /************** Begin file attach.c ******************************************/
   85286 /*
   85287 ** 2003 April 6
   85288 **
   85289 ** The author disclaims copyright to this source code.  In place of
   85290 ** a legal notice, here is a blessing:
   85291 **
   85292 **    May you do good and not evil.
   85293 **    May you find forgiveness for yourself and forgive others.
   85294 **    May you share freely, never taking more than you give.
   85295 **
   85296 *************************************************************************
   85297 ** This file contains code used to implement the ATTACH and DETACH commands.
   85298 */
   85299 
   85300 #ifndef SQLITE_OMIT_ATTACH
   85301 /*
   85302 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
   85303 ** is slightly different from resolving a normal SQL expression, because simple
   85304 ** identifiers are treated as strings, not possible column names or aliases.
   85305 **
   85306 ** i.e. if the parser sees:
   85307 **
   85308 **     ATTACH DATABASE abc AS def
   85309 **
   85310 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
   85311 ** looking for columns of the same name.
   85312 **
   85313 ** This only applies to the root node of pExpr, so the statement:
   85314 **
   85315 **     ATTACH DATABASE abc||def AS 'db2'
   85316 **
   85317 ** will fail because neither abc or def can be resolved.
   85318 */
   85319 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
   85320 {
   85321   int rc = SQLITE_OK;
   85322   if( pExpr ){
   85323     if( pExpr->op!=TK_ID ){
   85324       rc = sqlite3ResolveExprNames(pName, pExpr);
   85325     }else{
   85326       pExpr->op = TK_STRING;
   85327     }
   85328   }
   85329   return rc;
   85330 }
   85331 
   85332 /*
   85333 ** An SQL user-function registered to do the work of an ATTACH statement. The
   85334 ** three arguments to the function come directly from an attach statement:
   85335 **
   85336 **     ATTACH DATABASE x AS y KEY z
   85337 **
   85338 **     SELECT sqlite_attach(x, y, z)
   85339 **
   85340 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
   85341 ** third argument.
   85342 */
   85343 static void attachFunc(
   85344   sqlite3_context *context,
   85345   int NotUsed,
   85346   sqlite3_value **argv
   85347 ){
   85348   int i;
   85349   int rc = 0;
   85350   sqlite3 *db = sqlite3_context_db_handle(context);
   85351   const char *zName;
   85352   const char *zFile;
   85353   char *zPath = 0;
   85354   char *zErr = 0;
   85355   unsigned int flags;
   85356   Db *aNew;
   85357   char *zErrDyn = 0;
   85358   sqlite3_vfs *pVfs;
   85359 
   85360   UNUSED_PARAMETER(NotUsed);
   85361 
   85362   zFile = (const char *)sqlite3_value_text(argv[0]);
   85363   zName = (const char *)sqlite3_value_text(argv[1]);
   85364   if( zFile==0 ) zFile = "";
   85365   if( zName==0 ) zName = "";
   85366 
   85367   /* Check for the following errors:
   85368   **
   85369   **     * Too many attached databases,
   85370   **     * Transaction currently open
   85371   **     * Specified database name already being used.
   85372   */
   85373   if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
   85374     zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
   85375       db->aLimit[SQLITE_LIMIT_ATTACHED]
   85376     );
   85377     goto attach_error;
   85378   }
   85379   if( !db->autoCommit ){
   85380     zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
   85381     goto attach_error;
   85382   }
   85383   for(i=0; i<db->nDb; i++){
   85384     char *z = db->aDb[i].zName;
   85385     assert( z && zName );
   85386     if( sqlite3StrICmp(z, zName)==0 ){
   85387       zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
   85388       goto attach_error;
   85389     }
   85390   }
   85391 
   85392   /* Allocate the new entry in the db->aDb[] array and initialize the schema
   85393   ** hash tables.
   85394   */
   85395   if( db->aDb==db->aDbStatic ){
   85396     aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
   85397     if( aNew==0 ) return;
   85398     memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
   85399   }else{
   85400     aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
   85401     if( aNew==0 ) return;
   85402   }
   85403   db->aDb = aNew;
   85404   aNew = &db->aDb[db->nDb];
   85405   memset(aNew, 0, sizeof(*aNew));
   85406 
   85407   /* Open the database file. If the btree is successfully opened, use
   85408   ** it to obtain the database schema. At this point the schema may
   85409   ** or may not be initialized.
   85410   */
   85411   flags = db->openFlags;
   85412   rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
   85413   if( rc!=SQLITE_OK ){
   85414     if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
   85415     sqlite3_result_error(context, zErr, -1);
   85416     sqlite3_free(zErr);
   85417     return;
   85418   }
   85419   assert( pVfs );
   85420   flags |= SQLITE_OPEN_MAIN_DB;
   85421   rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
   85422   sqlite3_free( zPath );
   85423   db->nDb++;
   85424   if( rc==SQLITE_CONSTRAINT ){
   85425     rc = SQLITE_ERROR;
   85426     zErrDyn = sqlite3MPrintf(db, "database is already attached");
   85427   }else if( rc==SQLITE_OK ){
   85428     Pager *pPager;
   85429     aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
   85430     if( !aNew->pSchema ){
   85431       rc = SQLITE_NOMEM;
   85432     }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
   85433       zErrDyn = sqlite3MPrintf(db,
   85434         "attached databases must use the same text encoding as main database");
   85435       rc = SQLITE_ERROR;
   85436     }
   85437     pPager = sqlite3BtreePager(aNew->pBt);
   85438     sqlite3PagerLockingMode(pPager, db->dfltLockMode);
   85439     sqlite3BtreeSecureDelete(aNew->pBt,
   85440                              sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
   85441 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   85442     sqlite3BtreeSetPagerFlags(aNew->pBt, 3 | (db->flags & PAGER_FLAGS_MASK));
   85443 #endif
   85444   }
   85445   aNew->safety_level = 3;
   85446   aNew->zName = sqlite3DbStrDup(db, zName);
   85447   if( rc==SQLITE_OK && aNew->zName==0 ){
   85448     rc = SQLITE_NOMEM;
   85449   }
   85450 
   85451 
   85452 #ifdef SQLITE_HAS_CODEC
   85453   if( rc==SQLITE_OK ){
   85454     extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
   85455     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
   85456     int nKey;
   85457     char *zKey;
   85458     int t = sqlite3_value_type(argv[2]);
   85459     switch( t ){
   85460       case SQLITE_INTEGER:
   85461       case SQLITE_FLOAT:
   85462         zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
   85463         rc = SQLITE_ERROR;
   85464         break;
   85465 
   85466       case SQLITE_TEXT:
   85467       case SQLITE_BLOB:
   85468         nKey = sqlite3_value_bytes(argv[2]);
   85469         zKey = (char *)sqlite3_value_blob(argv[2]);
   85470         rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
   85471         break;
   85472 
   85473       case SQLITE_NULL:
   85474         /* No key specified.  Use the key from the main database */
   85475         sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
   85476         if( nKey>0 || sqlite3BtreeGetReserve(db->aDb[0].pBt)>0 ){
   85477           rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
   85478         }
   85479         break;
   85480     }
   85481   }
   85482 #endif
   85483 
   85484   /* If the file was opened successfully, read the schema for the new database.
   85485   ** If this fails, or if opening the file failed, then close the file and
   85486   ** remove the entry from the db->aDb[] array. i.e. put everything back the way
   85487   ** we found it.
   85488   */
   85489   if( rc==SQLITE_OK ){
   85490     sqlite3BtreeEnterAll(db);
   85491     rc = sqlite3Init(db, &zErrDyn);
   85492     sqlite3BtreeLeaveAll(db);
   85493   }
   85494   if( rc ){
   85495     int iDb = db->nDb - 1;
   85496     assert( iDb>=2 );
   85497     if( db->aDb[iDb].pBt ){
   85498       sqlite3BtreeClose(db->aDb[iDb].pBt);
   85499       db->aDb[iDb].pBt = 0;
   85500       db->aDb[iDb].pSchema = 0;
   85501     }
   85502     sqlite3ResetAllSchemasOfConnection(db);
   85503     db->nDb = iDb;
   85504     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
   85505       db->mallocFailed = 1;
   85506       sqlite3DbFree(db, zErrDyn);
   85507       zErrDyn = sqlite3MPrintf(db, "out of memory");
   85508     }else if( zErrDyn==0 ){
   85509       zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
   85510     }
   85511     goto attach_error;
   85512   }
   85513 
   85514   return;
   85515 
   85516 attach_error:
   85517   /* Return an error if we get here */
   85518   if( zErrDyn ){
   85519     sqlite3_result_error(context, zErrDyn, -1);
   85520     sqlite3DbFree(db, zErrDyn);
   85521   }
   85522   if( rc ) sqlite3_result_error_code(context, rc);
   85523 }
   85524 
   85525 /*
   85526 ** An SQL user-function registered to do the work of an DETACH statement. The
   85527 ** three arguments to the function come directly from a detach statement:
   85528 **
   85529 **     DETACH DATABASE x
   85530 **
   85531 **     SELECT sqlite_detach(x)
   85532 */
   85533 static void detachFunc(
   85534   sqlite3_context *context,
   85535   int NotUsed,
   85536   sqlite3_value **argv
   85537 ){
   85538   const char *zName = (const char *)sqlite3_value_text(argv[0]);
   85539   sqlite3 *db = sqlite3_context_db_handle(context);
   85540   int i;
   85541   Db *pDb = 0;
   85542   char zErr[128];
   85543 
   85544   UNUSED_PARAMETER(NotUsed);
   85545 
   85546   if( zName==0 ) zName = "";
   85547   for(i=0; i<db->nDb; i++){
   85548     pDb = &db->aDb[i];
   85549     if( pDb->pBt==0 ) continue;
   85550     if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
   85551   }
   85552 
   85553   if( i>=db->nDb ){
   85554     sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
   85555     goto detach_error;
   85556   }
   85557   if( i<2 ){
   85558     sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
   85559     goto detach_error;
   85560   }
   85561   if( !db->autoCommit ){
   85562     sqlite3_snprintf(sizeof(zErr), zErr,
   85563                      "cannot DETACH database within transaction");
   85564     goto detach_error;
   85565   }
   85566   if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
   85567     sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
   85568     goto detach_error;
   85569   }
   85570 
   85571   sqlite3BtreeClose(pDb->pBt);
   85572   pDb->pBt = 0;
   85573   pDb->pSchema = 0;
   85574   sqlite3ResetAllSchemasOfConnection(db);
   85575   return;
   85576 
   85577 detach_error:
   85578   sqlite3_result_error(context, zErr, -1);
   85579 }
   85580 
   85581 /*
   85582 ** This procedure generates VDBE code for a single invocation of either the
   85583 ** sqlite_detach() or sqlite_attach() SQL user functions.
   85584 */
   85585 static void codeAttach(
   85586   Parse *pParse,       /* The parser context */
   85587   int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
   85588   FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
   85589   Expr *pAuthArg,      /* Expression to pass to authorization callback */
   85590   Expr *pFilename,     /* Name of database file */
   85591   Expr *pDbname,       /* Name of the database to use internally */
   85592   Expr *pKey           /* Database key for encryption extension */
   85593 ){
   85594   int rc;
   85595   NameContext sName;
   85596   Vdbe *v;
   85597   sqlite3* db = pParse->db;
   85598   int regArgs;
   85599 
   85600   memset(&sName, 0, sizeof(NameContext));
   85601   sName.pParse = pParse;
   85602 
   85603   if(
   85604       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
   85605       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
   85606       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
   85607   ){
   85608     pParse->nErr++;
   85609     goto attach_end;
   85610   }
   85611 
   85612 #ifndef SQLITE_OMIT_AUTHORIZATION
   85613   if( pAuthArg ){
   85614     char *zAuthArg;
   85615     if( pAuthArg->op==TK_STRING ){
   85616       zAuthArg = pAuthArg->u.zToken;
   85617     }else{
   85618       zAuthArg = 0;
   85619     }
   85620     rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
   85621     if(rc!=SQLITE_OK ){
   85622       goto attach_end;
   85623     }
   85624   }
   85625 #endif /* SQLITE_OMIT_AUTHORIZATION */
   85626 
   85627 
   85628   v = sqlite3GetVdbe(pParse);
   85629   regArgs = sqlite3GetTempRange(pParse, 4);
   85630   sqlite3ExprCode(pParse, pFilename, regArgs);
   85631   sqlite3ExprCode(pParse, pDbname, regArgs+1);
   85632   sqlite3ExprCode(pParse, pKey, regArgs+2);
   85633 
   85634   assert( v || db->mallocFailed );
   85635   if( v ){
   85636     sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
   85637     assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
   85638     sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
   85639     sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
   85640 
   85641     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
   85642     ** statement only). For DETACH, set it to false (expire all existing
   85643     ** statements).
   85644     */
   85645     sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
   85646   }
   85647 
   85648 attach_end:
   85649   sqlite3ExprDelete(db, pFilename);
   85650   sqlite3ExprDelete(db, pDbname);
   85651   sqlite3ExprDelete(db, pKey);
   85652 }
   85653 
   85654 /*
   85655 ** Called by the parser to compile a DETACH statement.
   85656 **
   85657 **     DETACH pDbname
   85658 */
   85659 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
   85660   static const FuncDef detach_func = {
   85661     1,                /* nArg */
   85662     SQLITE_UTF8,      /* funcFlags */
   85663     0,                /* pUserData */
   85664     0,                /* pNext */
   85665     detachFunc,       /* xFunc */
   85666     0,                /* xStep */
   85667     0,                /* xFinalize */
   85668     "sqlite_detach",  /* zName */
   85669     0,                /* pHash */
   85670     0                 /* pDestructor */
   85671   };
   85672   codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
   85673 }
   85674 
   85675 /*
   85676 ** Called by the parser to compile an ATTACH statement.
   85677 **
   85678 **     ATTACH p AS pDbname KEY pKey
   85679 */
   85680 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
   85681   static const FuncDef attach_func = {
   85682     3,                /* nArg */
   85683     SQLITE_UTF8,      /* funcFlags */
   85684     0,                /* pUserData */
   85685     0,                /* pNext */
   85686     attachFunc,       /* xFunc */
   85687     0,                /* xStep */
   85688     0,                /* xFinalize */
   85689     "sqlite_attach",  /* zName */
   85690     0,                /* pHash */
   85691     0                 /* pDestructor */
   85692   };
   85693   codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
   85694 }
   85695 #endif /* SQLITE_OMIT_ATTACH */
   85696 
   85697 /*
   85698 ** Initialize a DbFixer structure.  This routine must be called prior
   85699 ** to passing the structure to one of the sqliteFixAAAA() routines below.
   85700 */
   85701 SQLITE_PRIVATE void sqlite3FixInit(
   85702   DbFixer *pFix,      /* The fixer to be initialized */
   85703   Parse *pParse,      /* Error messages will be written here */
   85704   int iDb,            /* This is the database that must be used */
   85705   const char *zType,  /* "view", "trigger", or "index" */
   85706   const Token *pName  /* Name of the view, trigger, or index */
   85707 ){
   85708   sqlite3 *db;
   85709 
   85710   db = pParse->db;
   85711   assert( db->nDb>iDb );
   85712   pFix->pParse = pParse;
   85713   pFix->zDb = db->aDb[iDb].zName;
   85714   pFix->pSchema = db->aDb[iDb].pSchema;
   85715   pFix->zType = zType;
   85716   pFix->pName = pName;
   85717   pFix->bVarOnly = (iDb==1);
   85718 }
   85719 
   85720 /*
   85721 ** The following set of routines walk through the parse tree and assign
   85722 ** a specific database to all table references where the database name
   85723 ** was left unspecified in the original SQL statement.  The pFix structure
   85724 ** must have been initialized by a prior call to sqlite3FixInit().
   85725 **
   85726 ** These routines are used to make sure that an index, trigger, or
   85727 ** view in one database does not refer to objects in a different database.
   85728 ** (Exception: indices, triggers, and views in the TEMP database are
   85729 ** allowed to refer to anything.)  If a reference is explicitly made
   85730 ** to an object in a different database, an error message is added to
   85731 ** pParse->zErrMsg and these routines return non-zero.  If everything
   85732 ** checks out, these routines return 0.
   85733 */
   85734 SQLITE_PRIVATE int sqlite3FixSrcList(
   85735   DbFixer *pFix,       /* Context of the fixation */
   85736   SrcList *pList       /* The Source list to check and modify */
   85737 ){
   85738   int i;
   85739   const char *zDb;
   85740   struct SrcList_item *pItem;
   85741 
   85742   if( NEVER(pList==0) ) return 0;
   85743   zDb = pFix->zDb;
   85744   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
   85745     if( pFix->bVarOnly==0 ){
   85746       if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
   85747         sqlite3ErrorMsg(pFix->pParse,
   85748             "%s %T cannot reference objects in database %s",
   85749             pFix->zType, pFix->pName, pItem->zDatabase);
   85750         return 1;
   85751       }
   85752       sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
   85753       pItem->zDatabase = 0;
   85754       pItem->pSchema = pFix->pSchema;
   85755     }
   85756 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
   85757     if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
   85758     if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
   85759 #endif
   85760   }
   85761   return 0;
   85762 }
   85763 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
   85764 SQLITE_PRIVATE int sqlite3FixSelect(
   85765   DbFixer *pFix,       /* Context of the fixation */
   85766   Select *pSelect      /* The SELECT statement to be fixed to one database */
   85767 ){
   85768   while( pSelect ){
   85769     if( sqlite3FixExprList(pFix, pSelect->pEList) ){
   85770       return 1;
   85771     }
   85772     if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
   85773       return 1;
   85774     }
   85775     if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
   85776       return 1;
   85777     }
   85778     if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
   85779       return 1;
   85780     }
   85781     if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
   85782       return 1;
   85783     }
   85784     if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
   85785       return 1;
   85786     }
   85787     if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
   85788       return 1;
   85789     }
   85790     if( sqlite3FixExpr(pFix, pSelect->pOffset) ){
   85791       return 1;
   85792     }
   85793     pSelect = pSelect->pPrior;
   85794   }
   85795   return 0;
   85796 }
   85797 SQLITE_PRIVATE int sqlite3FixExpr(
   85798   DbFixer *pFix,     /* Context of the fixation */
   85799   Expr *pExpr        /* The expression to be fixed to one database */
   85800 ){
   85801   while( pExpr ){
   85802     if( pExpr->op==TK_VARIABLE ){
   85803       if( pFix->pParse->db->init.busy ){
   85804         pExpr->op = TK_NULL;
   85805       }else{
   85806         sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
   85807         return 1;
   85808       }
   85809     }
   85810     if( ExprHasProperty(pExpr, EP_TokenOnly) ) break;
   85811     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   85812       if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
   85813     }else{
   85814       if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
   85815     }
   85816     if( sqlite3FixExpr(pFix, pExpr->pRight) ){
   85817       return 1;
   85818     }
   85819     pExpr = pExpr->pLeft;
   85820   }
   85821   return 0;
   85822 }
   85823 SQLITE_PRIVATE int sqlite3FixExprList(
   85824   DbFixer *pFix,     /* Context of the fixation */
   85825   ExprList *pList    /* The expression to be fixed to one database */
   85826 ){
   85827   int i;
   85828   struct ExprList_item *pItem;
   85829   if( pList==0 ) return 0;
   85830   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
   85831     if( sqlite3FixExpr(pFix, pItem->pExpr) ){
   85832       return 1;
   85833     }
   85834   }
   85835   return 0;
   85836 }
   85837 #endif
   85838 
   85839 #ifndef SQLITE_OMIT_TRIGGER
   85840 SQLITE_PRIVATE int sqlite3FixTriggerStep(
   85841   DbFixer *pFix,     /* Context of the fixation */
   85842   TriggerStep *pStep /* The trigger step be fixed to one database */
   85843 ){
   85844   while( pStep ){
   85845     if( sqlite3FixSelect(pFix, pStep->pSelect) ){
   85846       return 1;
   85847     }
   85848     if( sqlite3FixExpr(pFix, pStep->pWhere) ){
   85849       return 1;
   85850     }
   85851     if( sqlite3FixExprList(pFix, pStep->pExprList) ){
   85852       return 1;
   85853     }
   85854     pStep = pStep->pNext;
   85855   }
   85856   return 0;
   85857 }
   85858 #endif
   85859 
   85860 /************** End of attach.c **********************************************/
   85861 /************** Begin file auth.c ********************************************/
   85862 /*
   85863 ** 2003 January 11
   85864 **
   85865 ** The author disclaims copyright to this source code.  In place of
   85866 ** a legal notice, here is a blessing:
   85867 **
   85868 **    May you do good and not evil.
   85869 **    May you find forgiveness for yourself and forgive others.
   85870 **    May you share freely, never taking more than you give.
   85871 **
   85872 *************************************************************************
   85873 ** This file contains code used to implement the sqlite3_set_authorizer()
   85874 ** API.  This facility is an optional feature of the library.  Embedded
   85875 ** systems that do not need this facility may omit it by recompiling
   85876 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
   85877 */
   85878 
   85879 /*
   85880 ** All of the code in this file may be omitted by defining a single
   85881 ** macro.
   85882 */
   85883 #ifndef SQLITE_OMIT_AUTHORIZATION
   85884 
   85885 /*
   85886 ** Set or clear the access authorization function.
   85887 **
   85888 ** The access authorization function is be called during the compilation
   85889 ** phase to verify that the user has read and/or write access permission on
   85890 ** various fields of the database.  The first argument to the auth function
   85891 ** is a copy of the 3rd argument to this routine.  The second argument
   85892 ** to the auth function is one of these constants:
   85893 **
   85894 **       SQLITE_CREATE_INDEX
   85895 **       SQLITE_CREATE_TABLE
   85896 **       SQLITE_CREATE_TEMP_INDEX
   85897 **       SQLITE_CREATE_TEMP_TABLE
   85898 **       SQLITE_CREATE_TEMP_TRIGGER
   85899 **       SQLITE_CREATE_TEMP_VIEW
   85900 **       SQLITE_CREATE_TRIGGER
   85901 **       SQLITE_CREATE_VIEW
   85902 **       SQLITE_DELETE
   85903 **       SQLITE_DROP_INDEX
   85904 **       SQLITE_DROP_TABLE
   85905 **       SQLITE_DROP_TEMP_INDEX
   85906 **       SQLITE_DROP_TEMP_TABLE
   85907 **       SQLITE_DROP_TEMP_TRIGGER
   85908 **       SQLITE_DROP_TEMP_VIEW
   85909 **       SQLITE_DROP_TRIGGER
   85910 **       SQLITE_DROP_VIEW
   85911 **       SQLITE_INSERT
   85912 **       SQLITE_PRAGMA
   85913 **       SQLITE_READ
   85914 **       SQLITE_SELECT
   85915 **       SQLITE_TRANSACTION
   85916 **       SQLITE_UPDATE
   85917 **
   85918 ** The third and fourth arguments to the auth function are the name of
   85919 ** the table and the column that are being accessed.  The auth function
   85920 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
   85921 ** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
   85922 ** means that the SQL statement will never-run - the sqlite3_exec() call
   85923 ** will return with an error.  SQLITE_IGNORE means that the SQL statement
   85924 ** should run but attempts to read the specified column will return NULL
   85925 ** and attempts to write the column will be ignored.
   85926 **
   85927 ** Setting the auth function to NULL disables this hook.  The default
   85928 ** setting of the auth function is NULL.
   85929 */
   85930 SQLITE_API int sqlite3_set_authorizer(
   85931   sqlite3 *db,
   85932   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
   85933   void *pArg
   85934 ){
   85935   sqlite3_mutex_enter(db->mutex);
   85936   db->xAuth = xAuth;
   85937   db->pAuthArg = pArg;
   85938   sqlite3ExpirePreparedStatements(db);
   85939   sqlite3_mutex_leave(db->mutex);
   85940   return SQLITE_OK;
   85941 }
   85942 
   85943 /*
   85944 ** Write an error message into pParse->zErrMsg that explains that the
   85945 ** user-supplied authorization function returned an illegal value.
   85946 */
   85947 static void sqliteAuthBadReturnCode(Parse *pParse){
   85948   sqlite3ErrorMsg(pParse, "authorizer malfunction");
   85949   pParse->rc = SQLITE_ERROR;
   85950 }
   85951 
   85952 /*
   85953 ** Invoke the authorization callback for permission to read column zCol from
   85954 ** table zTab in database zDb. This function assumes that an authorization
   85955 ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
   85956 **
   85957 ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
   85958 ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
   85959 ** is treated as SQLITE_DENY. In this case an error is left in pParse.
   85960 */
   85961 SQLITE_PRIVATE int sqlite3AuthReadCol(
   85962   Parse *pParse,                  /* The parser context */
   85963   const char *zTab,               /* Table name */
   85964   const char *zCol,               /* Column name */
   85965   int iDb                         /* Index of containing database. */
   85966 ){
   85967   sqlite3 *db = pParse->db;       /* Database handle */
   85968   char *zDb = db->aDb[iDb].zName; /* Name of attached database */
   85969   int rc;                         /* Auth callback return code */
   85970 
   85971   rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
   85972   if( rc==SQLITE_DENY ){
   85973     if( db->nDb>2 || iDb!=0 ){
   85974       sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
   85975     }else{
   85976       sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
   85977     }
   85978     pParse->rc = SQLITE_AUTH;
   85979   }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
   85980     sqliteAuthBadReturnCode(pParse);
   85981   }
   85982   return rc;
   85983 }
   85984 
   85985 /*
   85986 ** The pExpr should be a TK_COLUMN expression.  The table referred to
   85987 ** is in pTabList or else it is the NEW or OLD table of a trigger.
   85988 ** Check to see if it is OK to read this particular column.
   85989 **
   85990 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
   85991 ** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
   85992 ** then generate an error.
   85993 */
   85994 SQLITE_PRIVATE void sqlite3AuthRead(
   85995   Parse *pParse,        /* The parser context */
   85996   Expr *pExpr,          /* The expression to check authorization on */
   85997   Schema *pSchema,      /* The schema of the expression */
   85998   SrcList *pTabList     /* All table that pExpr might refer to */
   85999 ){
   86000   sqlite3 *db = pParse->db;
   86001   Table *pTab = 0;      /* The table being read */
   86002   const char *zCol;     /* Name of the column of the table */
   86003   int iSrc;             /* Index in pTabList->a[] of table being read */
   86004   int iDb;              /* The index of the database the expression refers to */
   86005   int iCol;             /* Index of column in table */
   86006 
   86007   if( db->xAuth==0 ) return;
   86008   iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
   86009   if( iDb<0 ){
   86010     /* An attempt to read a column out of a subquery or other
   86011     ** temporary table. */
   86012     return;
   86013   }
   86014 
   86015   assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
   86016   if( pExpr->op==TK_TRIGGER ){
   86017     pTab = pParse->pTriggerTab;
   86018   }else{
   86019     assert( pTabList );
   86020     for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
   86021       if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
   86022         pTab = pTabList->a[iSrc].pTab;
   86023         break;
   86024       }
   86025     }
   86026   }
   86027   iCol = pExpr->iColumn;
   86028   if( NEVER(pTab==0) ) return;
   86029 
   86030   if( iCol>=0 ){
   86031     assert( iCol<pTab->nCol );
   86032     zCol = pTab->aCol[iCol].zName;
   86033   }else if( pTab->iPKey>=0 ){
   86034     assert( pTab->iPKey<pTab->nCol );
   86035     zCol = pTab->aCol[pTab->iPKey].zName;
   86036   }else{
   86037     zCol = "ROWID";
   86038   }
   86039   assert( iDb>=0 && iDb<db->nDb );
   86040   if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
   86041     pExpr->op = TK_NULL;
   86042   }
   86043 }
   86044 
   86045 /*
   86046 ** Do an authorization check using the code and arguments given.  Return
   86047 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
   86048 ** is returned, then the error count and error message in pParse are
   86049 ** modified appropriately.
   86050 */
   86051 SQLITE_PRIVATE int sqlite3AuthCheck(
   86052   Parse *pParse,
   86053   int code,
   86054   const char *zArg1,
   86055   const char *zArg2,
   86056   const char *zArg3
   86057 ){
   86058   sqlite3 *db = pParse->db;
   86059   int rc;
   86060 
   86061   /* Don't do any authorization checks if the database is initialising
   86062   ** or if the parser is being invoked from within sqlite3_declare_vtab.
   86063   */
   86064   if( db->init.busy || IN_DECLARE_VTAB ){
   86065     return SQLITE_OK;
   86066   }
   86067 
   86068   if( db->xAuth==0 ){
   86069     return SQLITE_OK;
   86070   }
   86071   rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
   86072   if( rc==SQLITE_DENY ){
   86073     sqlite3ErrorMsg(pParse, "not authorized");
   86074     pParse->rc = SQLITE_AUTH;
   86075   }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
   86076     rc = SQLITE_DENY;
   86077     sqliteAuthBadReturnCode(pParse);
   86078   }
   86079   return rc;
   86080 }
   86081 
   86082 /*
   86083 ** Push an authorization context.  After this routine is called, the
   86084 ** zArg3 argument to authorization callbacks will be zContext until
   86085 ** popped.  Or if pParse==0, this routine is a no-op.
   86086 */
   86087 SQLITE_PRIVATE void sqlite3AuthContextPush(
   86088   Parse *pParse,
   86089   AuthContext *pContext,
   86090   const char *zContext
   86091 ){
   86092   assert( pParse );
   86093   pContext->pParse = pParse;
   86094   pContext->zAuthContext = pParse->zAuthContext;
   86095   pParse->zAuthContext = zContext;
   86096 }
   86097 
   86098 /*
   86099 ** Pop an authorization context that was previously pushed
   86100 ** by sqlite3AuthContextPush
   86101 */
   86102 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
   86103   if( pContext->pParse ){
   86104     pContext->pParse->zAuthContext = pContext->zAuthContext;
   86105     pContext->pParse = 0;
   86106   }
   86107 }
   86108 
   86109 #endif /* SQLITE_OMIT_AUTHORIZATION */
   86110 
   86111 /************** End of auth.c ************************************************/
   86112 /************** Begin file build.c *******************************************/
   86113 /*
   86114 ** 2001 September 15
   86115 **
   86116 ** The author disclaims copyright to this source code.  In place of
   86117 ** a legal notice, here is a blessing:
   86118 **
   86119 **    May you do good and not evil.
   86120 **    May you find forgiveness for yourself and forgive others.
   86121 **    May you share freely, never taking more than you give.
   86122 **
   86123 *************************************************************************
   86124 ** This file contains C code routines that are called by the SQLite parser
   86125 ** when syntax rules are reduced.  The routines in this file handle the
   86126 ** following kinds of SQL syntax:
   86127 **
   86128 **     CREATE TABLE
   86129 **     DROP TABLE
   86130 **     CREATE INDEX
   86131 **     DROP INDEX
   86132 **     creating ID lists
   86133 **     BEGIN TRANSACTION
   86134 **     COMMIT
   86135 **     ROLLBACK
   86136 */
   86137 
   86138 /*
   86139 ** This routine is called when a new SQL statement is beginning to
   86140 ** be parsed.  Initialize the pParse structure as needed.
   86141 */
   86142 SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
   86143   pParse->explain = (u8)explainFlag;
   86144   pParse->nVar = 0;
   86145 }
   86146 
   86147 #ifndef SQLITE_OMIT_SHARED_CACHE
   86148 /*
   86149 ** The TableLock structure is only used by the sqlite3TableLock() and
   86150 ** codeTableLocks() functions.
   86151 */
   86152 struct TableLock {
   86153   int iDb;             /* The database containing the table to be locked */
   86154   int iTab;            /* The root page of the table to be locked */
   86155   u8 isWriteLock;      /* True for write lock.  False for a read lock */
   86156   const char *zName;   /* Name of the table */
   86157 };
   86158 
   86159 /*
   86160 ** Record the fact that we want to lock a table at run-time.
   86161 **
   86162 ** The table to be locked has root page iTab and is found in database iDb.
   86163 ** A read or a write lock can be taken depending on isWritelock.
   86164 **
   86165 ** This routine just records the fact that the lock is desired.  The
   86166 ** code to make the lock occur is generated by a later call to
   86167 ** codeTableLocks() which occurs during sqlite3FinishCoding().
   86168 */
   86169 SQLITE_PRIVATE void sqlite3TableLock(
   86170   Parse *pParse,     /* Parsing context */
   86171   int iDb,           /* Index of the database containing the table to lock */
   86172   int iTab,          /* Root page number of the table to be locked */
   86173   u8 isWriteLock,    /* True for a write lock */
   86174   const char *zName  /* Name of the table to be locked */
   86175 ){
   86176   Parse *pToplevel = sqlite3ParseToplevel(pParse);
   86177   int i;
   86178   int nBytes;
   86179   TableLock *p;
   86180   assert( iDb>=0 );
   86181 
   86182   for(i=0; i<pToplevel->nTableLock; i++){
   86183     p = &pToplevel->aTableLock[i];
   86184     if( p->iDb==iDb && p->iTab==iTab ){
   86185       p->isWriteLock = (p->isWriteLock || isWriteLock);
   86186       return;
   86187     }
   86188   }
   86189 
   86190   nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
   86191   pToplevel->aTableLock =
   86192       sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
   86193   if( pToplevel->aTableLock ){
   86194     p = &pToplevel->aTableLock[pToplevel->nTableLock++];
   86195     p->iDb = iDb;
   86196     p->iTab = iTab;
   86197     p->isWriteLock = isWriteLock;
   86198     p->zName = zName;
   86199   }else{
   86200     pToplevel->nTableLock = 0;
   86201     pToplevel->db->mallocFailed = 1;
   86202   }
   86203 }
   86204 
   86205 /*
   86206 ** Code an OP_TableLock instruction for each table locked by the
   86207 ** statement (configured by calls to sqlite3TableLock()).
   86208 */
   86209 static void codeTableLocks(Parse *pParse){
   86210   int i;
   86211   Vdbe *pVdbe;
   86212 
   86213   pVdbe = sqlite3GetVdbe(pParse);
   86214   assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
   86215 
   86216   for(i=0; i<pParse->nTableLock; i++){
   86217     TableLock *p = &pParse->aTableLock[i];
   86218     int p1 = p->iDb;
   86219     sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
   86220                       p->zName, P4_STATIC);
   86221   }
   86222 }
   86223 #else
   86224   #define codeTableLocks(x)
   86225 #endif
   86226 
   86227 /*
   86228 ** Return TRUE if the given yDbMask object is empty - if it contains no
   86229 ** 1 bits.  This routine is used by the DbMaskAllZero() and DbMaskNotZero()
   86230 ** macros when SQLITE_MAX_ATTACHED is greater than 30.
   86231 */
   86232 #if SQLITE_MAX_ATTACHED>30
   86233 SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){
   86234   int i;
   86235   for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
   86236   return 1;
   86237 }
   86238 #endif
   86239 
   86240 /*
   86241 ** This routine is called after a single SQL statement has been
   86242 ** parsed and a VDBE program to execute that statement has been
   86243 ** prepared.  This routine puts the finishing touches on the
   86244 ** VDBE program and resets the pParse structure for the next
   86245 ** parse.
   86246 **
   86247 ** Note that if an error occurred, it might be the case that
   86248 ** no VDBE code was generated.
   86249 */
   86250 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
   86251   sqlite3 *db;
   86252   Vdbe *v;
   86253 
   86254   assert( pParse->pToplevel==0 );
   86255   db = pParse->db;
   86256   if( db->mallocFailed ) return;
   86257   if( pParse->nested ) return;
   86258   if( pParse->nErr ) return;
   86259 
   86260   /* Begin by generating some termination code at the end of the
   86261   ** vdbe program
   86262   */
   86263   v = sqlite3GetVdbe(pParse);
   86264   assert( !pParse->isMultiWrite
   86265        || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
   86266   if( v ){
   86267     while( sqlite3VdbeDeletePriorOpcode(v, OP_Close) ){}
   86268     sqlite3VdbeAddOp0(v, OP_Halt);
   86269 
   86270     /* The cookie mask contains one bit for each database file open.
   86271     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
   86272     ** set for each database that is used.  Generate code to start a
   86273     ** transaction on each used database and to verify the schema cookie
   86274     ** on each used database.
   86275     */
   86276     if( db->mallocFailed==0
   86277      && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
   86278     ){
   86279       int iDb, i;
   86280       assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
   86281       sqlite3VdbeJumpHere(v, 0);
   86282       for(iDb=0; iDb<db->nDb; iDb++){
   86283         if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
   86284         sqlite3VdbeUsesBtree(v, iDb);
   86285         sqlite3VdbeAddOp4Int(v,
   86286           OP_Transaction,                    /* Opcode */
   86287           iDb,                               /* P1 */
   86288           DbMaskTest(pParse->writeMask,iDb), /* P2 */
   86289           pParse->cookieValue[iDb],          /* P3 */
   86290           db->aDb[iDb].pSchema->iGeneration  /* P4 */
   86291         );
   86292         if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
   86293       }
   86294 #ifndef SQLITE_OMIT_VIRTUALTABLE
   86295       for(i=0; i<pParse->nVtabLock; i++){
   86296         char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
   86297         sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
   86298       }
   86299       pParse->nVtabLock = 0;
   86300 #endif
   86301 
   86302       /* Once all the cookies have been verified and transactions opened,
   86303       ** obtain the required table-locks. This is a no-op unless the
   86304       ** shared-cache feature is enabled.
   86305       */
   86306       codeTableLocks(pParse);
   86307 
   86308       /* Initialize any AUTOINCREMENT data structures required.
   86309       */
   86310       sqlite3AutoincrementBegin(pParse);
   86311 
   86312       /* Code constant expressions that where factored out of inner loops */
   86313       if( pParse->pConstExpr ){
   86314         ExprList *pEL = pParse->pConstExpr;
   86315         pParse->okConstFactor = 0;
   86316         for(i=0; i<pEL->nExpr; i++){
   86317           sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
   86318         }
   86319       }
   86320 
   86321       /* Finally, jump back to the beginning of the executable code. */
   86322       sqlite3VdbeAddOp2(v, OP_Goto, 0, 1);
   86323     }
   86324   }
   86325 
   86326 
   86327   /* Get the VDBE program ready for execution
   86328   */
   86329   if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
   86330     assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
   86331     /* A minimum of one cursor is required if autoincrement is used
   86332     *  See ticket [a696379c1f08866] */
   86333     if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
   86334     sqlite3VdbeMakeReady(v, pParse);
   86335     pParse->rc = SQLITE_DONE;
   86336     pParse->colNamesSet = 0;
   86337   }else{
   86338     pParse->rc = SQLITE_ERROR;
   86339   }
   86340   pParse->nTab = 0;
   86341   pParse->nMem = 0;
   86342   pParse->nSet = 0;
   86343   pParse->nVar = 0;
   86344   DbMaskZero(pParse->cookieMask);
   86345 }
   86346 
   86347 /*
   86348 ** Run the parser and code generator recursively in order to generate
   86349 ** code for the SQL statement given onto the end of the pParse context
   86350 ** currently under construction.  When the parser is run recursively
   86351 ** this way, the final OP_Halt is not appended and other initialization
   86352 ** and finalization steps are omitted because those are handling by the
   86353 ** outermost parser.
   86354 **
   86355 ** Not everything is nestable.  This facility is designed to permit
   86356 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
   86357 ** care if you decide to try to use this routine for some other purposes.
   86358 */
   86359 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
   86360   va_list ap;
   86361   char *zSql;
   86362   char *zErrMsg = 0;
   86363   sqlite3 *db = pParse->db;
   86364 # define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
   86365   char saveBuf[SAVE_SZ];
   86366 
   86367   if( pParse->nErr ) return;
   86368   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
   86369   va_start(ap, zFormat);
   86370   zSql = sqlite3VMPrintf(db, zFormat, ap);
   86371   va_end(ap);
   86372   if( zSql==0 ){
   86373     return;   /* A malloc must have failed */
   86374   }
   86375   pParse->nested++;
   86376   memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
   86377   memset(&pParse->nVar, 0, SAVE_SZ);
   86378   sqlite3RunParser(pParse, zSql, &zErrMsg);
   86379   sqlite3DbFree(db, zErrMsg);
   86380   sqlite3DbFree(db, zSql);
   86381   memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
   86382   pParse->nested--;
   86383 }
   86384 
   86385 /*
   86386 ** Locate the in-memory structure that describes a particular database
   86387 ** table given the name of that table and (optionally) the name of the
   86388 ** database containing the table.  Return NULL if not found.
   86389 **
   86390 ** If zDatabase is 0, all databases are searched for the table and the
   86391 ** first matching table is returned.  (No checking for duplicate table
   86392 ** names is done.)  The search order is TEMP first, then MAIN, then any
   86393 ** auxiliary databases added using the ATTACH command.
   86394 **
   86395 ** See also sqlite3LocateTable().
   86396 */
   86397 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
   86398   Table *p = 0;
   86399   int i;
   86400   int nName;
   86401   assert( zName!=0 );
   86402   nName = sqlite3Strlen30(zName);
   86403   /* All mutexes are required for schema access.  Make sure we hold them. */
   86404   assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
   86405   for(i=OMIT_TEMPDB; i<db->nDb; i++){
   86406     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
   86407     if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
   86408     assert( sqlite3SchemaMutexHeld(db, j, 0) );
   86409     p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
   86410     if( p ) break;
   86411   }
   86412   return p;
   86413 }
   86414 
   86415 /*
   86416 ** Locate the in-memory structure that describes a particular database
   86417 ** table given the name of that table and (optionally) the name of the
   86418 ** database containing the table.  Return NULL if not found.  Also leave an
   86419 ** error message in pParse->zErrMsg.
   86420 **
   86421 ** The difference between this routine and sqlite3FindTable() is that this
   86422 ** routine leaves an error message in pParse->zErrMsg where
   86423 ** sqlite3FindTable() does not.
   86424 */
   86425 SQLITE_PRIVATE Table *sqlite3LocateTable(
   86426   Parse *pParse,         /* context in which to report errors */
   86427   int isView,            /* True if looking for a VIEW rather than a TABLE */
   86428   const char *zName,     /* Name of the table we are looking for */
   86429   const char *zDbase     /* Name of the database.  Might be NULL */
   86430 ){
   86431   Table *p;
   86432 
   86433   /* Read the database schema. If an error occurs, leave an error message
   86434   ** and code in pParse and return NULL. */
   86435   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   86436     return 0;
   86437   }
   86438 
   86439   p = sqlite3FindTable(pParse->db, zName, zDbase);
   86440   if( p==0 ){
   86441     const char *zMsg = isView ? "no such view" : "no such table";
   86442     if( zDbase ){
   86443       sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
   86444     }else{
   86445       sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
   86446     }
   86447     pParse->checkSchema = 1;
   86448   }
   86449   return p;
   86450 }
   86451 
   86452 /*
   86453 ** Locate the table identified by *p.
   86454 **
   86455 ** This is a wrapper around sqlite3LocateTable(). The difference between
   86456 ** sqlite3LocateTable() and this function is that this function restricts
   86457 ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
   86458 ** non-NULL if it is part of a view or trigger program definition. See
   86459 ** sqlite3FixSrcList() for details.
   86460 */
   86461 SQLITE_PRIVATE Table *sqlite3LocateTableItem(
   86462   Parse *pParse,
   86463   int isView,
   86464   struct SrcList_item *p
   86465 ){
   86466   const char *zDb;
   86467   assert( p->pSchema==0 || p->zDatabase==0 );
   86468   if( p->pSchema ){
   86469     int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
   86470     zDb = pParse->db->aDb[iDb].zName;
   86471   }else{
   86472     zDb = p->zDatabase;
   86473   }
   86474   return sqlite3LocateTable(pParse, isView, p->zName, zDb);
   86475 }
   86476 
   86477 /*
   86478 ** Locate the in-memory structure that describes
   86479 ** a particular index given the name of that index
   86480 ** and the name of the database that contains the index.
   86481 ** Return NULL if not found.
   86482 **
   86483 ** If zDatabase is 0, all databases are searched for the
   86484 ** table and the first matching index is returned.  (No checking
   86485 ** for duplicate index names is done.)  The search order is
   86486 ** TEMP first, then MAIN, then any auxiliary databases added
   86487 ** using the ATTACH command.
   86488 */
   86489 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
   86490   Index *p = 0;
   86491   int i;
   86492   int nName = sqlite3Strlen30(zName);
   86493   /* All mutexes are required for schema access.  Make sure we hold them. */
   86494   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
   86495   for(i=OMIT_TEMPDB; i<db->nDb; i++){
   86496     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
   86497     Schema *pSchema = db->aDb[j].pSchema;
   86498     assert( pSchema );
   86499     if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
   86500     assert( sqlite3SchemaMutexHeld(db, j, 0) );
   86501     p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
   86502     if( p ) break;
   86503   }
   86504   return p;
   86505 }
   86506 
   86507 /*
   86508 ** Reclaim the memory used by an index
   86509 */
   86510 static void freeIndex(sqlite3 *db, Index *p){
   86511 #ifndef SQLITE_OMIT_ANALYZE
   86512   sqlite3DeleteIndexSamples(db, p);
   86513 #endif
   86514   if( db==0 || db->pnBytesFreed==0 ) sqlite3KeyInfoUnref(p->pKeyInfo);
   86515   sqlite3ExprDelete(db, p->pPartIdxWhere);
   86516   sqlite3DbFree(db, p->zColAff);
   86517   if( p->isResized ) sqlite3DbFree(db, p->azColl);
   86518   sqlite3DbFree(db, p);
   86519 }
   86520 
   86521 /*
   86522 ** For the index called zIdxName which is found in the database iDb,
   86523 ** unlike that index from its Table then remove the index from
   86524 ** the index hash table and free all memory structures associated
   86525 ** with the index.
   86526 */
   86527 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
   86528   Index *pIndex;
   86529   int len;
   86530   Hash *pHash;
   86531 
   86532   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   86533   pHash = &db->aDb[iDb].pSchema->idxHash;
   86534   len = sqlite3Strlen30(zIdxName);
   86535   pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
   86536   if( ALWAYS(pIndex) ){
   86537     if( pIndex->pTable->pIndex==pIndex ){
   86538       pIndex->pTable->pIndex = pIndex->pNext;
   86539     }else{
   86540       Index *p;
   86541       /* Justification of ALWAYS();  The index must be on the list of
   86542       ** indices. */
   86543       p = pIndex->pTable->pIndex;
   86544       while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
   86545       if( ALWAYS(p && p->pNext==pIndex) ){
   86546         p->pNext = pIndex->pNext;
   86547       }
   86548     }
   86549     freeIndex(db, pIndex);
   86550   }
   86551   db->flags |= SQLITE_InternChanges;
   86552 }
   86553 
   86554 /*
   86555 ** Look through the list of open database files in db->aDb[] and if
   86556 ** any have been closed, remove them from the list.  Reallocate the
   86557 ** db->aDb[] structure to a smaller size, if possible.
   86558 **
   86559 ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
   86560 ** are never candidates for being collapsed.
   86561 */
   86562 SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
   86563   int i, j;
   86564   for(i=j=2; i<db->nDb; i++){
   86565     struct Db *pDb = &db->aDb[i];
   86566     if( pDb->pBt==0 ){
   86567       sqlite3DbFree(db, pDb->zName);
   86568       pDb->zName = 0;
   86569       continue;
   86570     }
   86571     if( j<i ){
   86572       db->aDb[j] = db->aDb[i];
   86573     }
   86574     j++;
   86575   }
   86576   memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
   86577   db->nDb = j;
   86578   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
   86579     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
   86580     sqlite3DbFree(db, db->aDb);
   86581     db->aDb = db->aDbStatic;
   86582   }
   86583 }
   86584 
   86585 /*
   86586 ** Reset the schema for the database at index iDb.  Also reset the
   86587 ** TEMP schema.
   86588 */
   86589 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
   86590   Db *pDb;
   86591   assert( iDb<db->nDb );
   86592 
   86593   /* Case 1:  Reset the single schema identified by iDb */
   86594   pDb = &db->aDb[iDb];
   86595   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   86596   assert( pDb->pSchema!=0 );
   86597   sqlite3SchemaClear(pDb->pSchema);
   86598 
   86599   /* If any database other than TEMP is reset, then also reset TEMP
   86600   ** since TEMP might be holding triggers that reference tables in the
   86601   ** other database.
   86602   */
   86603   if( iDb!=1 ){
   86604     pDb = &db->aDb[1];
   86605     assert( pDb->pSchema!=0 );
   86606     sqlite3SchemaClear(pDb->pSchema);
   86607   }
   86608   return;
   86609 }
   86610 
   86611 /*
   86612 ** Erase all schema information from all attached databases (including
   86613 ** "main" and "temp") for a single database connection.
   86614 */
   86615 SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
   86616   int i;
   86617   sqlite3BtreeEnterAll(db);
   86618   for(i=0; i<db->nDb; i++){
   86619     Db *pDb = &db->aDb[i];
   86620     if( pDb->pSchema ){
   86621       sqlite3SchemaClear(pDb->pSchema);
   86622     }
   86623   }
   86624   db->flags &= ~SQLITE_InternChanges;
   86625   sqlite3VtabUnlockList(db);
   86626   sqlite3BtreeLeaveAll(db);
   86627   sqlite3CollapseDatabaseArray(db);
   86628 }
   86629 
   86630 /*
   86631 ** This routine is called when a commit occurs.
   86632 */
   86633 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
   86634   db->flags &= ~SQLITE_InternChanges;
   86635 }
   86636 
   86637 /*
   86638 ** Delete memory allocated for the column names of a table or view (the
   86639 ** Table.aCol[] array).
   86640 */
   86641 static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
   86642   int i;
   86643   Column *pCol;
   86644   assert( pTable!=0 );
   86645   if( (pCol = pTable->aCol)!=0 ){
   86646     for(i=0; i<pTable->nCol; i++, pCol++){
   86647       sqlite3DbFree(db, pCol->zName);
   86648       sqlite3ExprDelete(db, pCol->pDflt);
   86649       sqlite3DbFree(db, pCol->zDflt);
   86650       sqlite3DbFree(db, pCol->zType);
   86651       sqlite3DbFree(db, pCol->zColl);
   86652     }
   86653     sqlite3DbFree(db, pTable->aCol);
   86654   }
   86655 }
   86656 
   86657 /*
   86658 ** Remove the memory data structures associated with the given
   86659 ** Table.  No changes are made to disk by this routine.
   86660 **
   86661 ** This routine just deletes the data structure.  It does not unlink
   86662 ** the table data structure from the hash table.  But it does destroy
   86663 ** memory structures of the indices and foreign keys associated with
   86664 ** the table.
   86665 **
   86666 ** The db parameter is optional.  It is needed if the Table object
   86667 ** contains lookaside memory.  (Table objects in the schema do not use
   86668 ** lookaside memory, but some ephemeral Table objects do.)  Or the
   86669 ** db parameter can be used with db->pnBytesFreed to measure the memory
   86670 ** used by the Table object.
   86671 */
   86672 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
   86673   Index *pIndex, *pNext;
   86674   TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
   86675 
   86676   assert( !pTable || pTable->nRef>0 );
   86677 
   86678   /* Do not delete the table until the reference count reaches zero. */
   86679   if( !pTable ) return;
   86680   if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
   86681 
   86682   /* Record the number of outstanding lookaside allocations in schema Tables
   86683   ** prior to doing any free() operations.  Since schema Tables do not use
   86684   ** lookaside, this number should not change. */
   86685   TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
   86686                          db->lookaside.nOut : 0 );
   86687 
   86688   /* Delete all indices associated with this table. */
   86689   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
   86690     pNext = pIndex->pNext;
   86691     assert( pIndex->pSchema==pTable->pSchema );
   86692     if( !db || db->pnBytesFreed==0 ){
   86693       char *zName = pIndex->zName;
   86694       TESTONLY ( Index *pOld = ) sqlite3HashInsert(
   86695          &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
   86696       );
   86697       assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
   86698       assert( pOld==pIndex || pOld==0 );
   86699     }
   86700     freeIndex(db, pIndex);
   86701   }
   86702 
   86703   /* Delete any foreign keys attached to this table. */
   86704   sqlite3FkDelete(db, pTable);
   86705 
   86706   /* Delete the Table structure itself.
   86707   */
   86708   sqliteDeleteColumnNames(db, pTable);
   86709   sqlite3DbFree(db, pTable->zName);
   86710   sqlite3DbFree(db, pTable->zColAff);
   86711   sqlite3SelectDelete(db, pTable->pSelect);
   86712 #ifndef SQLITE_OMIT_CHECK
   86713   sqlite3ExprListDelete(db, pTable->pCheck);
   86714 #endif
   86715 #ifndef SQLITE_OMIT_VIRTUALTABLE
   86716   sqlite3VtabClear(db, pTable);
   86717 #endif
   86718   sqlite3DbFree(db, pTable);
   86719 
   86720   /* Verify that no lookaside memory was used by schema tables */
   86721   assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
   86722 }
   86723 
   86724 /*
   86725 ** Unlink the given table from the hash tables and the delete the
   86726 ** table structure with all its indices and foreign keys.
   86727 */
   86728 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
   86729   Table *p;
   86730   Db *pDb;
   86731 
   86732   assert( db!=0 );
   86733   assert( iDb>=0 && iDb<db->nDb );
   86734   assert( zTabName );
   86735   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   86736   testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
   86737   pDb = &db->aDb[iDb];
   86738   p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
   86739                         sqlite3Strlen30(zTabName),0);
   86740   sqlite3DeleteTable(db, p);
   86741   db->flags |= SQLITE_InternChanges;
   86742 }
   86743 
   86744 /*
   86745 ** Given a token, return a string that consists of the text of that
   86746 ** token.  Space to hold the returned string
   86747 ** is obtained from sqliteMalloc() and must be freed by the calling
   86748 ** function.
   86749 **
   86750 ** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
   86751 ** surround the body of the token are removed.
   86752 **
   86753 ** Tokens are often just pointers into the original SQL text and so
   86754 ** are not \000 terminated and are not persistent.  The returned string
   86755 ** is \000 terminated and is persistent.
   86756 */
   86757 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
   86758   char *zName;
   86759   if( pName ){
   86760     zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
   86761     sqlite3Dequote(zName);
   86762   }else{
   86763     zName = 0;
   86764   }
   86765   return zName;
   86766 }
   86767 
   86768 /*
   86769 ** Open the sqlite_master table stored in database number iDb for
   86770 ** writing. The table is opened using cursor 0.
   86771 */
   86772 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
   86773   Vdbe *v = sqlite3GetVdbe(p);
   86774   sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
   86775   sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
   86776   if( p->nTab==0 ){
   86777     p->nTab = 1;
   86778   }
   86779 }
   86780 
   86781 /*
   86782 ** Parameter zName points to a nul-terminated buffer containing the name
   86783 ** of a database ("main", "temp" or the name of an attached db). This
   86784 ** function returns the index of the named database in db->aDb[], or
   86785 ** -1 if the named db cannot be found.
   86786 */
   86787 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
   86788   int i = -1;         /* Database number */
   86789   if( zName ){
   86790     Db *pDb;
   86791     int n = sqlite3Strlen30(zName);
   86792     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
   86793       if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
   86794           0==sqlite3StrICmp(pDb->zName, zName) ){
   86795         break;
   86796       }
   86797     }
   86798   }
   86799   return i;
   86800 }
   86801 
   86802 /*
   86803 ** The token *pName contains the name of a database (either "main" or
   86804 ** "temp" or the name of an attached db). This routine returns the
   86805 ** index of the named database in db->aDb[], or -1 if the named db
   86806 ** does not exist.
   86807 */
   86808 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
   86809   int i;                               /* Database number */
   86810   char *zName;                         /* Name we are searching for */
   86811   zName = sqlite3NameFromToken(db, pName);
   86812   i = sqlite3FindDbName(db, zName);
   86813   sqlite3DbFree(db, zName);
   86814   return i;
   86815 }
   86816 
   86817 /* The table or view or trigger name is passed to this routine via tokens
   86818 ** pName1 and pName2. If the table name was fully qualified, for example:
   86819 **
   86820 ** CREATE TABLE xxx.yyy (...);
   86821 **
   86822 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
   86823 ** the table name is not fully qualified, i.e.:
   86824 **
   86825 ** CREATE TABLE yyy(...);
   86826 **
   86827 ** Then pName1 is set to "yyy" and pName2 is "".
   86828 **
   86829 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
   86830 ** pName2) that stores the unqualified table name.  The index of the
   86831 ** database "xxx" is returned.
   86832 */
   86833 SQLITE_PRIVATE int sqlite3TwoPartName(
   86834   Parse *pParse,      /* Parsing and code generating context */
   86835   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
   86836   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
   86837   Token **pUnqual     /* Write the unqualified object name here */
   86838 ){
   86839   int iDb;                    /* Database holding the object */
   86840   sqlite3 *db = pParse->db;
   86841 
   86842   if( ALWAYS(pName2!=0) && pName2->n>0 ){
   86843     if( db->init.busy ) {
   86844       sqlite3ErrorMsg(pParse, "corrupt database");
   86845       pParse->nErr++;
   86846       return -1;
   86847     }
   86848     *pUnqual = pName2;
   86849     iDb = sqlite3FindDb(db, pName1);
   86850     if( iDb<0 ){
   86851       sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
   86852       pParse->nErr++;
   86853       return -1;
   86854     }
   86855   }else{
   86856     assert( db->init.iDb==0 || db->init.busy );
   86857     iDb = db->init.iDb;
   86858     *pUnqual = pName1;
   86859   }
   86860   return iDb;
   86861 }
   86862 
   86863 /*
   86864 ** This routine is used to check if the UTF-8 string zName is a legal
   86865 ** unqualified name for a new schema object (table, index, view or
   86866 ** trigger). All names are legal except those that begin with the string
   86867 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
   86868 ** is reserved for internal use.
   86869 */
   86870 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
   86871   if( !pParse->db->init.busy && pParse->nested==0
   86872           && (pParse->db->flags & SQLITE_WriteSchema)==0
   86873           && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
   86874     sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
   86875     return SQLITE_ERROR;
   86876   }
   86877   return SQLITE_OK;
   86878 }
   86879 
   86880 /*
   86881 ** Return the PRIMARY KEY index of a table
   86882 */
   86883 SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){
   86884   Index *p;
   86885   for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
   86886   return p;
   86887 }
   86888 
   86889 /*
   86890 ** Return the column of index pIdx that corresponds to table
   86891 ** column iCol.  Return -1 if not found.
   86892 */
   86893 SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
   86894   int i;
   86895   for(i=0; i<pIdx->nColumn; i++){
   86896     if( iCol==pIdx->aiColumn[i] ) return i;
   86897   }
   86898   return -1;
   86899 }
   86900 
   86901 /*
   86902 ** Begin constructing a new table representation in memory.  This is
   86903 ** the first of several action routines that get called in response
   86904 ** to a CREATE TABLE statement.  In particular, this routine is called
   86905 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
   86906 ** flag is true if the table should be stored in the auxiliary database
   86907 ** file instead of in the main database file.  This is normally the case
   86908 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
   86909 ** CREATE and TABLE.
   86910 **
   86911 ** The new table record is initialized and put in pParse->pNewTable.
   86912 ** As more of the CREATE TABLE statement is parsed, additional action
   86913 ** routines will be called to add more information to this record.
   86914 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
   86915 ** is called to complete the construction of the new table record.
   86916 */
   86917 SQLITE_PRIVATE void sqlite3StartTable(
   86918   Parse *pParse,   /* Parser context */
   86919   Token *pName1,   /* First part of the name of the table or view */
   86920   Token *pName2,   /* Second part of the name of the table or view */
   86921   int isTemp,      /* True if this is a TEMP table */
   86922   int isView,      /* True if this is a VIEW */
   86923   int isVirtual,   /* True if this is a VIRTUAL table */
   86924   int noErr        /* Do nothing if table already exists */
   86925 ){
   86926   Table *pTable;
   86927   char *zName = 0; /* The name of the new table */
   86928   sqlite3 *db = pParse->db;
   86929   Vdbe *v;
   86930   int iDb;         /* Database number to create the table in */
   86931   Token *pName;    /* Unqualified name of the table to create */
   86932 
   86933   /* The table or view name to create is passed to this routine via tokens
   86934   ** pName1 and pName2. If the table name was fully qualified, for example:
   86935   **
   86936   ** CREATE TABLE xxx.yyy (...);
   86937   **
   86938   ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
   86939   ** the table name is not fully qualified, i.e.:
   86940   **
   86941   ** CREATE TABLE yyy(...);
   86942   **
   86943   ** Then pName1 is set to "yyy" and pName2 is "".
   86944   **
   86945   ** The call below sets the pName pointer to point at the token (pName1 or
   86946   ** pName2) that stores the unqualified table name. The variable iDb is
   86947   ** set to the index of the database that the table or view is to be
   86948   ** created in.
   86949   */
   86950   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
   86951   if( iDb<0 ) return;
   86952   if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
   86953     /* If creating a temp table, the name may not be qualified. Unless
   86954     ** the database name is "temp" anyway.  */
   86955     sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
   86956     return;
   86957   }
   86958   if( !OMIT_TEMPDB && isTemp ) iDb = 1;
   86959 
   86960   pParse->sNameToken = *pName;
   86961   zName = sqlite3NameFromToken(db, pName);
   86962   if( zName==0 ) return;
   86963   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
   86964     goto begin_table_error;
   86965   }
   86966   if( db->init.iDb==1 ) isTemp = 1;
   86967 #ifndef SQLITE_OMIT_AUTHORIZATION
   86968   assert( (isTemp & 1)==isTemp );
   86969   {
   86970     int code;
   86971     char *zDb = db->aDb[iDb].zName;
   86972     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
   86973       goto begin_table_error;
   86974     }
   86975     if( isView ){
   86976       if( !OMIT_TEMPDB && isTemp ){
   86977         code = SQLITE_CREATE_TEMP_VIEW;
   86978       }else{
   86979         code = SQLITE_CREATE_VIEW;
   86980       }
   86981     }else{
   86982       if( !OMIT_TEMPDB && isTemp ){
   86983         code = SQLITE_CREATE_TEMP_TABLE;
   86984       }else{
   86985         code = SQLITE_CREATE_TABLE;
   86986       }
   86987     }
   86988     if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
   86989       goto begin_table_error;
   86990     }
   86991   }
   86992 #endif
   86993 
   86994   /* Make sure the new table name does not collide with an existing
   86995   ** index or table name in the same database.  Issue an error message if
   86996   ** it does. The exception is if the statement being parsed was passed
   86997   ** to an sqlite3_declare_vtab() call. In that case only the column names
   86998   ** and types will be used, so there is no need to test for namespace
   86999   ** collisions.
   87000   */
   87001   if( !IN_DECLARE_VTAB ){
   87002     char *zDb = db->aDb[iDb].zName;
   87003     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   87004       goto begin_table_error;
   87005     }
   87006     pTable = sqlite3FindTable(db, zName, zDb);
   87007     if( pTable ){
   87008       if( !noErr ){
   87009         sqlite3ErrorMsg(pParse, "table %T already exists", pName);
   87010       }else{
   87011         assert( !db->init.busy );
   87012         sqlite3CodeVerifySchema(pParse, iDb);
   87013       }
   87014       goto begin_table_error;
   87015     }
   87016     if( sqlite3FindIndex(db, zName, zDb)!=0 ){
   87017       sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
   87018       goto begin_table_error;
   87019     }
   87020   }
   87021 
   87022   pTable = sqlite3DbMallocZero(db, sizeof(Table));
   87023   if( pTable==0 ){
   87024     db->mallocFailed = 1;
   87025     pParse->rc = SQLITE_NOMEM;
   87026     pParse->nErr++;
   87027     goto begin_table_error;
   87028   }
   87029   pTable->zName = zName;
   87030   pTable->iPKey = -1;
   87031   pTable->pSchema = db->aDb[iDb].pSchema;
   87032   pTable->nRef = 1;
   87033   pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
   87034   assert( pParse->pNewTable==0 );
   87035   pParse->pNewTable = pTable;
   87036 
   87037   /* If this is the magic sqlite_sequence table used by autoincrement,
   87038   ** then record a pointer to this table in the main database structure
   87039   ** so that INSERT can find the table easily.
   87040   */
   87041 #ifndef SQLITE_OMIT_AUTOINCREMENT
   87042   if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
   87043     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   87044     pTable->pSchema->pSeqTab = pTable;
   87045   }
   87046 #endif
   87047 
   87048   /* Begin generating the code that will insert the table record into
   87049   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
   87050   ** and allocate the record number for the table entry now.  Before any
   87051   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
   87052   ** indices to be created and the table record must come before the
   87053   ** indices.  Hence, the record number for the table must be allocated
   87054   ** now.
   87055   */
   87056   if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
   87057     int j1;
   87058     int fileFormat;
   87059     int reg1, reg2, reg3;
   87060     sqlite3BeginWriteOperation(pParse, 0, iDb);
   87061 
   87062 #ifndef SQLITE_OMIT_VIRTUALTABLE
   87063     if( isVirtual ){
   87064       sqlite3VdbeAddOp0(v, OP_VBegin);
   87065     }
   87066 #endif
   87067 
   87068     /* If the file format and encoding in the database have not been set,
   87069     ** set them now.
   87070     */
   87071     reg1 = pParse->regRowid = ++pParse->nMem;
   87072     reg2 = pParse->regRoot = ++pParse->nMem;
   87073     reg3 = ++pParse->nMem;
   87074     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
   87075     sqlite3VdbeUsesBtree(v, iDb);
   87076     j1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
   87077     fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
   87078                   1 : SQLITE_MAX_FILE_FORMAT;
   87079     sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
   87080     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
   87081     sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
   87082     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
   87083     sqlite3VdbeJumpHere(v, j1);
   87084 
   87085     /* This just creates a place-holder record in the sqlite_master table.
   87086     ** The record created does not contain anything yet.  It will be replaced
   87087     ** by the real entry in code generated at sqlite3EndTable().
   87088     **
   87089     ** The rowid for the new entry is left in register pParse->regRowid.
   87090     ** The root page number of the new table is left in reg pParse->regRoot.
   87091     ** The rowid and root page number values are needed by the code that
   87092     ** sqlite3EndTable will generate.
   87093     */
   87094 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
   87095     if( isView || isVirtual ){
   87096       sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
   87097     }else
   87098 #endif
   87099     {
   87100       pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
   87101     }
   87102     sqlite3OpenMasterTable(pParse, iDb);
   87103     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
   87104     sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
   87105     sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
   87106     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   87107     sqlite3VdbeAddOp0(v, OP_Close);
   87108   }
   87109 
   87110   /* Normal (non-error) return. */
   87111   return;
   87112 
   87113   /* If an error occurs, we jump here */
   87114 begin_table_error:
   87115   sqlite3DbFree(db, zName);
   87116   return;
   87117 }
   87118 
   87119 /*
   87120 ** This macro is used to compare two strings in a case-insensitive manner.
   87121 ** It is slightly faster than calling sqlite3StrICmp() directly, but
   87122 ** produces larger code.
   87123 **
   87124 ** WARNING: This macro is not compatible with the strcmp() family. It
   87125 ** returns true if the two strings are equal, otherwise false.
   87126 */
   87127 #define STRICMP(x, y) (\
   87128 sqlite3UpperToLower[*(unsigned char *)(x)]==   \
   87129 sqlite3UpperToLower[*(unsigned char *)(y)]     \
   87130 && sqlite3StrICmp((x)+1,(y)+1)==0 )
   87131 
   87132 /*
   87133 ** Add a new column to the table currently being constructed.
   87134 **
   87135 ** The parser calls this routine once for each column declaration
   87136 ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
   87137 ** first to get things going.  Then this routine is called for each
   87138 ** column.
   87139 */
   87140 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
   87141   Table *p;
   87142   int i;
   87143   char *z;
   87144   Column *pCol;
   87145   sqlite3 *db = pParse->db;
   87146   if( (p = pParse->pNewTable)==0 ) return;
   87147 #if SQLITE_MAX_COLUMN
   87148   if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
   87149     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
   87150     return;
   87151   }
   87152 #endif
   87153   z = sqlite3NameFromToken(db, pName);
   87154   if( z==0 ) return;
   87155   for(i=0; i<p->nCol; i++){
   87156     if( STRICMP(z, p->aCol[i].zName) ){
   87157       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
   87158       sqlite3DbFree(db, z);
   87159       return;
   87160     }
   87161   }
   87162   if( (p->nCol & 0x7)==0 ){
   87163     Column *aNew;
   87164     aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
   87165     if( aNew==0 ){
   87166       sqlite3DbFree(db, z);
   87167       return;
   87168     }
   87169     p->aCol = aNew;
   87170   }
   87171   pCol = &p->aCol[p->nCol];
   87172   memset(pCol, 0, sizeof(p->aCol[0]));
   87173   pCol->zName = z;
   87174 
   87175   /* If there is no type specified, columns have the default affinity
   87176   ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
   87177   ** be called next to set pCol->affinity correctly.
   87178   */
   87179   pCol->affinity = SQLITE_AFF_NONE;
   87180   pCol->szEst = 1;
   87181   p->nCol++;
   87182 }
   87183 
   87184 /*
   87185 ** This routine is called by the parser while in the middle of
   87186 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
   87187 ** been seen on a column.  This routine sets the notNull flag on
   87188 ** the column currently under construction.
   87189 */
   87190 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
   87191   Table *p;
   87192   p = pParse->pNewTable;
   87193   if( p==0 || NEVER(p->nCol<1) ) return;
   87194   p->aCol[p->nCol-1].notNull = (u8)onError;
   87195 }
   87196 
   87197 /*
   87198 ** Scan the column type name zType (length nType) and return the
   87199 ** associated affinity type.
   87200 **
   87201 ** This routine does a case-independent search of zType for the
   87202 ** substrings in the following table. If one of the substrings is
   87203 ** found, the corresponding affinity is returned. If zType contains
   87204 ** more than one of the substrings, entries toward the top of
   87205 ** the table take priority. For example, if zType is 'BLOBINT',
   87206 ** SQLITE_AFF_INTEGER is returned.
   87207 **
   87208 ** Substring     | Affinity
   87209 ** --------------------------------
   87210 ** 'INT'         | SQLITE_AFF_INTEGER
   87211 ** 'CHAR'        | SQLITE_AFF_TEXT
   87212 ** 'CLOB'        | SQLITE_AFF_TEXT
   87213 ** 'TEXT'        | SQLITE_AFF_TEXT
   87214 ** 'BLOB'        | SQLITE_AFF_NONE
   87215 ** 'REAL'        | SQLITE_AFF_REAL
   87216 ** 'FLOA'        | SQLITE_AFF_REAL
   87217 ** 'DOUB'        | SQLITE_AFF_REAL
   87218 **
   87219 ** If none of the substrings in the above table are found,
   87220 ** SQLITE_AFF_NUMERIC is returned.
   87221 */
   87222 SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){
   87223   u32 h = 0;
   87224   char aff = SQLITE_AFF_NUMERIC;
   87225   const char *zChar = 0;
   87226 
   87227   if( zIn==0 ) return aff;
   87228   while( zIn[0] ){
   87229     h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
   87230     zIn++;
   87231     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
   87232       aff = SQLITE_AFF_TEXT;
   87233       zChar = zIn;
   87234     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
   87235       aff = SQLITE_AFF_TEXT;
   87236     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
   87237       aff = SQLITE_AFF_TEXT;
   87238     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
   87239         && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
   87240       aff = SQLITE_AFF_NONE;
   87241       if( zIn[0]=='(' ) zChar = zIn;
   87242 #ifndef SQLITE_OMIT_FLOATING_POINT
   87243     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
   87244         && aff==SQLITE_AFF_NUMERIC ){
   87245       aff = SQLITE_AFF_REAL;
   87246     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
   87247         && aff==SQLITE_AFF_NUMERIC ){
   87248       aff = SQLITE_AFF_REAL;
   87249     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
   87250         && aff==SQLITE_AFF_NUMERIC ){
   87251       aff = SQLITE_AFF_REAL;
   87252 #endif
   87253     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
   87254       aff = SQLITE_AFF_INTEGER;
   87255       break;
   87256     }
   87257   }
   87258 
   87259   /* If pszEst is not NULL, store an estimate of the field size.  The
   87260   ** estimate is scaled so that the size of an integer is 1.  */
   87261   if( pszEst ){
   87262     *pszEst = 1;   /* default size is approx 4 bytes */
   87263     if( aff<=SQLITE_AFF_NONE ){
   87264       if( zChar ){
   87265         while( zChar[0] ){
   87266           if( sqlite3Isdigit(zChar[0]) ){
   87267             int v = 0;
   87268             sqlite3GetInt32(zChar, &v);
   87269             v = v/4 + 1;
   87270             if( v>255 ) v = 255;
   87271             *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
   87272             break;
   87273           }
   87274           zChar++;
   87275         }
   87276       }else{
   87277         *pszEst = 5;   /* BLOB, TEXT, CLOB -> r=5  (approx 20 bytes)*/
   87278       }
   87279     }
   87280   }
   87281   return aff;
   87282 }
   87283 
   87284 /*
   87285 ** This routine is called by the parser while in the middle of
   87286 ** parsing a CREATE TABLE statement.  The pFirst token is the first
   87287 ** token in the sequence of tokens that describe the type of the
   87288 ** column currently under construction.   pLast is the last token
   87289 ** in the sequence.  Use this information to construct a string
   87290 ** that contains the typename of the column and store that string
   87291 ** in zType.
   87292 */
   87293 SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
   87294   Table *p;
   87295   Column *pCol;
   87296 
   87297   p = pParse->pNewTable;
   87298   if( p==0 || NEVER(p->nCol<1) ) return;
   87299   pCol = &p->aCol[p->nCol-1];
   87300   assert( pCol->zType==0 );
   87301   pCol->zType = sqlite3NameFromToken(pParse->db, pType);
   87302   pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst);
   87303 }
   87304 
   87305 /*
   87306 ** The expression is the default value for the most recently added column
   87307 ** of the table currently under construction.
   87308 **
   87309 ** Default value expressions must be constant.  Raise an exception if this
   87310 ** is not the case.
   87311 **
   87312 ** This routine is called by the parser while in the middle of
   87313 ** parsing a CREATE TABLE statement.
   87314 */
   87315 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
   87316   Table *p;
   87317   Column *pCol;
   87318   sqlite3 *db = pParse->db;
   87319   p = pParse->pNewTable;
   87320   if( p!=0 ){
   87321     pCol = &(p->aCol[p->nCol-1]);
   87322     if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
   87323       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
   87324           pCol->zName);
   87325     }else{
   87326       /* A copy of pExpr is used instead of the original, as pExpr contains
   87327       ** tokens that point to volatile memory. The 'span' of the expression
   87328       ** is required by pragma table_info.
   87329       */
   87330       sqlite3ExprDelete(db, pCol->pDflt);
   87331       pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
   87332       sqlite3DbFree(db, pCol->zDflt);
   87333       pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
   87334                                      (int)(pSpan->zEnd - pSpan->zStart));
   87335     }
   87336   }
   87337   sqlite3ExprDelete(db, pSpan->pExpr);
   87338 }
   87339 
   87340 /*
   87341 ** Designate the PRIMARY KEY for the table.  pList is a list of names
   87342 ** of columns that form the primary key.  If pList is NULL, then the
   87343 ** most recently added column of the table is the primary key.
   87344 **
   87345 ** A table can have at most one primary key.  If the table already has
   87346 ** a primary key (and this is the second primary key) then create an
   87347 ** error.
   87348 **
   87349 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
   87350 ** then we will try to use that column as the rowid.  Set the Table.iPKey
   87351 ** field of the table under construction to be the index of the
   87352 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
   87353 ** no INTEGER PRIMARY KEY.
   87354 **
   87355 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
   87356 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
   87357 */
   87358 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
   87359   Parse *pParse,    /* Parsing context */
   87360   ExprList *pList,  /* List of field names to be indexed */
   87361   int onError,      /* What to do with a uniqueness conflict */
   87362   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
   87363   int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
   87364 ){
   87365   Table *pTab = pParse->pNewTable;
   87366   char *zType = 0;
   87367   int iCol = -1, i;
   87368   int nTerm;
   87369   if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
   87370   if( pTab->tabFlags & TF_HasPrimaryKey ){
   87371     sqlite3ErrorMsg(pParse,
   87372       "table \"%s\" has more than one primary key", pTab->zName);
   87373     goto primary_key_exit;
   87374   }
   87375   pTab->tabFlags |= TF_HasPrimaryKey;
   87376   if( pList==0 ){
   87377     iCol = pTab->nCol - 1;
   87378     pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
   87379     zType = pTab->aCol[iCol].zType;
   87380     nTerm = 1;
   87381   }else{
   87382     nTerm = pList->nExpr;
   87383     for(i=0; i<nTerm; i++){
   87384       for(iCol=0; iCol<pTab->nCol; iCol++){
   87385         if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
   87386           pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
   87387           zType = pTab->aCol[iCol].zType;
   87388           break;
   87389         }
   87390       }
   87391     }
   87392   }
   87393   if( nTerm==1
   87394    && zType && sqlite3StrICmp(zType, "INTEGER")==0
   87395    && sortOrder==SQLITE_SO_ASC
   87396   ){
   87397     pTab->iPKey = iCol;
   87398     pTab->keyConf = (u8)onError;
   87399     assert( autoInc==0 || autoInc==1 );
   87400     pTab->tabFlags |= autoInc*TF_Autoincrement;
   87401     if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
   87402   }else if( autoInc ){
   87403 #ifndef SQLITE_OMIT_AUTOINCREMENT
   87404     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
   87405        "INTEGER PRIMARY KEY");
   87406 #endif
   87407   }else{
   87408     Vdbe *v = pParse->pVdbe;
   87409     Index *p;
   87410     if( v ) pParse->addrSkipPK = sqlite3VdbeAddOp0(v, OP_Noop);
   87411     p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
   87412                            0, sortOrder, 0);
   87413     if( p ){
   87414       p->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
   87415       if( v ) sqlite3VdbeJumpHere(v, pParse->addrSkipPK);
   87416     }
   87417     pList = 0;
   87418   }
   87419 
   87420 primary_key_exit:
   87421   sqlite3ExprListDelete(pParse->db, pList);
   87422   return;
   87423 }
   87424 
   87425 /*
   87426 ** Add a new CHECK constraint to the table currently under construction.
   87427 */
   87428 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
   87429   Parse *pParse,    /* Parsing context */
   87430   Expr *pCheckExpr  /* The check expression */
   87431 ){
   87432 #ifndef SQLITE_OMIT_CHECK
   87433   Table *pTab = pParse->pNewTable;
   87434   sqlite3 *db = pParse->db;
   87435   if( pTab && !IN_DECLARE_VTAB
   87436    && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
   87437   ){
   87438     pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
   87439     if( pParse->constraintName.n ){
   87440       sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
   87441     }
   87442   }else
   87443 #endif
   87444   {
   87445     sqlite3ExprDelete(pParse->db, pCheckExpr);
   87446   }
   87447 }
   87448 
   87449 /*
   87450 ** Set the collation function of the most recently parsed table column
   87451 ** to the CollSeq given.
   87452 */
   87453 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
   87454   Table *p;
   87455   int i;
   87456   char *zColl;              /* Dequoted name of collation sequence */
   87457   sqlite3 *db;
   87458 
   87459   if( (p = pParse->pNewTable)==0 ) return;
   87460   i = p->nCol-1;
   87461   db = pParse->db;
   87462   zColl = sqlite3NameFromToken(db, pToken);
   87463   if( !zColl ) return;
   87464 
   87465   if( sqlite3LocateCollSeq(pParse, zColl) ){
   87466     Index *pIdx;
   87467     sqlite3DbFree(db, p->aCol[i].zColl);
   87468     p->aCol[i].zColl = zColl;
   87469 
   87470     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
   87471     ** then an index may have been created on this column before the
   87472     ** collation type was added. Correct this if it is the case.
   87473     */
   87474     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
   87475       assert( pIdx->nKeyCol==1 );
   87476       if( pIdx->aiColumn[0]==i ){
   87477         pIdx->azColl[0] = p->aCol[i].zColl;
   87478       }
   87479     }
   87480   }else{
   87481     sqlite3DbFree(db, zColl);
   87482   }
   87483 }
   87484 
   87485 /*
   87486 ** This function returns the collation sequence for database native text
   87487 ** encoding identified by the string zName, length nName.
   87488 **
   87489 ** If the requested collation sequence is not available, or not available
   87490 ** in the database native encoding, the collation factory is invoked to
   87491 ** request it. If the collation factory does not supply such a sequence,
   87492 ** and the sequence is available in another text encoding, then that is
   87493 ** returned instead.
   87494 **
   87495 ** If no versions of the requested collations sequence are available, or
   87496 ** another error occurs, NULL is returned and an error message written into
   87497 ** pParse.
   87498 **
   87499 ** This routine is a wrapper around sqlite3FindCollSeq().  This routine
   87500 ** invokes the collation factory if the named collation cannot be found
   87501 ** and generates an error message.
   87502 **
   87503 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
   87504 */
   87505 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
   87506   sqlite3 *db = pParse->db;
   87507   u8 enc = ENC(db);
   87508   u8 initbusy = db->init.busy;
   87509   CollSeq *pColl;
   87510 
   87511   pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
   87512   if( !initbusy && (!pColl || !pColl->xCmp) ){
   87513     pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
   87514   }
   87515 
   87516   return pColl;
   87517 }
   87518 
   87519 
   87520 /*
   87521 ** Generate code that will increment the schema cookie.
   87522 **
   87523 ** The schema cookie is used to determine when the schema for the
   87524 ** database changes.  After each schema change, the cookie value
   87525 ** changes.  When a process first reads the schema it records the
   87526 ** cookie.  Thereafter, whenever it goes to access the database,
   87527 ** it checks the cookie to make sure the schema has not changed
   87528 ** since it was last read.
   87529 **
   87530 ** This plan is not completely bullet-proof.  It is possible for
   87531 ** the schema to change multiple times and for the cookie to be
   87532 ** set back to prior value.  But schema changes are infrequent
   87533 ** and the probability of hitting the same cookie value is only
   87534 ** 1 chance in 2^32.  So we're safe enough.
   87535 */
   87536 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
   87537   int r1 = sqlite3GetTempReg(pParse);
   87538   sqlite3 *db = pParse->db;
   87539   Vdbe *v = pParse->pVdbe;
   87540   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   87541   sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
   87542   sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
   87543   sqlite3ReleaseTempReg(pParse, r1);
   87544 }
   87545 
   87546 /*
   87547 ** Measure the number of characters needed to output the given
   87548 ** identifier.  The number returned includes any quotes used
   87549 ** but does not include the null terminator.
   87550 **
   87551 ** The estimate is conservative.  It might be larger that what is
   87552 ** really needed.
   87553 */
   87554 static int identLength(const char *z){
   87555   int n;
   87556   for(n=0; *z; n++, z++){
   87557     if( *z=='"' ){ n++; }
   87558   }
   87559   return n + 2;
   87560 }
   87561 
   87562 /*
   87563 ** The first parameter is a pointer to an output buffer. The second
   87564 ** parameter is a pointer to an integer that contains the offset at
   87565 ** which to write into the output buffer. This function copies the
   87566 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
   87567 ** to the specified offset in the buffer and updates *pIdx to refer
   87568 ** to the first byte after the last byte written before returning.
   87569 **
   87570 ** If the string zSignedIdent consists entirely of alpha-numeric
   87571 ** characters, does not begin with a digit and is not an SQL keyword,
   87572 ** then it is copied to the output buffer exactly as it is. Otherwise,
   87573 ** it is quoted using double-quotes.
   87574 */
   87575 static void identPut(char *z, int *pIdx, char *zSignedIdent){
   87576   unsigned char *zIdent = (unsigned char*)zSignedIdent;
   87577   int i, j, needQuote;
   87578   i = *pIdx;
   87579 
   87580   for(j=0; zIdent[j]; j++){
   87581     if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
   87582   }
   87583   needQuote = sqlite3Isdigit(zIdent[0])
   87584             || sqlite3KeywordCode(zIdent, j)!=TK_ID
   87585             || zIdent[j]!=0
   87586             || j==0;
   87587 
   87588   if( needQuote ) z[i++] = '"';
   87589   for(j=0; zIdent[j]; j++){
   87590     z[i++] = zIdent[j];
   87591     if( zIdent[j]=='"' ) z[i++] = '"';
   87592   }
   87593   if( needQuote ) z[i++] = '"';
   87594   z[i] = 0;
   87595   *pIdx = i;
   87596 }
   87597 
   87598 /*
   87599 ** Generate a CREATE TABLE statement appropriate for the given
   87600 ** table.  Memory to hold the text of the statement is obtained
   87601 ** from sqliteMalloc() and must be freed by the calling function.
   87602 */
   87603 static char *createTableStmt(sqlite3 *db, Table *p){
   87604   int i, k, n;
   87605   char *zStmt;
   87606   char *zSep, *zSep2, *zEnd;
   87607   Column *pCol;
   87608   n = 0;
   87609   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
   87610     n += identLength(pCol->zName) + 5;
   87611   }
   87612   n += identLength(p->zName);
   87613   if( n<50 ){
   87614     zSep = "";
   87615     zSep2 = ",";
   87616     zEnd = ")";
   87617   }else{
   87618     zSep = "\n  ";
   87619     zSep2 = ",\n  ";
   87620     zEnd = "\n)";
   87621   }
   87622   n += 35 + 6*p->nCol;
   87623   zStmt = sqlite3DbMallocRaw(0, n);
   87624   if( zStmt==0 ){
   87625     db->mallocFailed = 1;
   87626     return 0;
   87627   }
   87628   sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
   87629   k = sqlite3Strlen30(zStmt);
   87630   identPut(zStmt, &k, p->zName);
   87631   zStmt[k++] = '(';
   87632   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
   87633     static const char * const azType[] = {
   87634         /* SQLITE_AFF_TEXT    */ " TEXT",
   87635         /* SQLITE_AFF_NONE    */ "",
   87636         /* SQLITE_AFF_NUMERIC */ " NUM",
   87637         /* SQLITE_AFF_INTEGER */ " INT",
   87638         /* SQLITE_AFF_REAL    */ " REAL"
   87639     };
   87640     int len;
   87641     const char *zType;
   87642 
   87643     sqlite3_snprintf(n-k, &zStmt[k], zSep);
   87644     k += sqlite3Strlen30(&zStmt[k]);
   87645     zSep = zSep2;
   87646     identPut(zStmt, &k, pCol->zName);
   87647     assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
   87648     assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
   87649     testcase( pCol->affinity==SQLITE_AFF_TEXT );
   87650     testcase( pCol->affinity==SQLITE_AFF_NONE );
   87651     testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
   87652     testcase( pCol->affinity==SQLITE_AFF_INTEGER );
   87653     testcase( pCol->affinity==SQLITE_AFF_REAL );
   87654 
   87655     zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
   87656     len = sqlite3Strlen30(zType);
   87657     assert( pCol->affinity==SQLITE_AFF_NONE
   87658             || pCol->affinity==sqlite3AffinityType(zType, 0) );
   87659     memcpy(&zStmt[k], zType, len);
   87660     k += len;
   87661     assert( k<=n );
   87662   }
   87663   sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
   87664   return zStmt;
   87665 }
   87666 
   87667 /*
   87668 ** Resize an Index object to hold N columns total.  Return SQLITE_OK
   87669 ** on success and SQLITE_NOMEM on an OOM error.
   87670 */
   87671 static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
   87672   char *zExtra;
   87673   int nByte;
   87674   if( pIdx->nColumn>=N ) return SQLITE_OK;
   87675   assert( pIdx->isResized==0 );
   87676   nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
   87677   zExtra = sqlite3DbMallocZero(db, nByte);
   87678   if( zExtra==0 ) return SQLITE_NOMEM;
   87679   memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
   87680   pIdx->azColl = (char**)zExtra;
   87681   zExtra += sizeof(char*)*N;
   87682   memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
   87683   pIdx->aiColumn = (i16*)zExtra;
   87684   zExtra += sizeof(i16)*N;
   87685   memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
   87686   pIdx->aSortOrder = (u8*)zExtra;
   87687   pIdx->nColumn = N;
   87688   pIdx->isResized = 1;
   87689   return SQLITE_OK;
   87690 }
   87691 
   87692 /*
   87693 ** Estimate the total row width for a table.
   87694 */
   87695 static void estimateTableWidth(Table *pTab){
   87696   unsigned wTable = 0;
   87697   const Column *pTabCol;
   87698   int i;
   87699   for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
   87700     wTable += pTabCol->szEst;
   87701   }
   87702   if( pTab->iPKey<0 ) wTable++;
   87703   pTab->szTabRow = sqlite3LogEst(wTable*4);
   87704 }
   87705 
   87706 /*
   87707 ** Estimate the average size of a row for an index.
   87708 */
   87709 static void estimateIndexWidth(Index *pIdx){
   87710   unsigned wIndex = 0;
   87711   int i;
   87712   const Column *aCol = pIdx->pTable->aCol;
   87713   for(i=0; i<pIdx->nColumn; i++){
   87714     i16 x = pIdx->aiColumn[i];
   87715     assert( x<pIdx->pTable->nCol );
   87716     wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
   87717   }
   87718   pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
   87719 }
   87720 
   87721 /* Return true if value x is found any of the first nCol entries of aiCol[]
   87722 */
   87723 static int hasColumn(const i16 *aiCol, int nCol, int x){
   87724   while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
   87725   return 0;
   87726 }
   87727 
   87728 /*
   87729 ** This routine runs at the end of parsing a CREATE TABLE statement that
   87730 ** has a WITHOUT ROWID clause.  The job of this routine is to convert both
   87731 ** internal schema data structures and the generated VDBE code so that they
   87732 ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
   87733 ** Changes include:
   87734 **
   87735 **     (1)  Convert the OP_CreateTable into an OP_CreateIndex.  There is
   87736 **          no rowid btree for a WITHOUT ROWID.  Instead, the canonical
   87737 **          data storage is a covering index btree.
   87738 **     (2)  Bypass the creation of the sqlite_master table entry
   87739 **          for the PRIMARY KEY as the the primary key index is now
   87740 **          identified by the sqlite_master table entry of the table itself.
   87741 **     (3)  Set the Index.tnum of the PRIMARY KEY Index object in the
   87742 **          schema to the rootpage from the main table.
   87743 **     (4)  Set all columns of the PRIMARY KEY schema object to be NOT NULL.
   87744 **     (5)  Add all table columns to the PRIMARY KEY Index object
   87745 **          so that the PRIMARY KEY is a covering index.  The surplus
   87746 **          columns are part of KeyInfo.nXField and are not used for
   87747 **          sorting or lookup or uniqueness checks.
   87748 **     (6)  Replace the rowid tail on all automatically generated UNIQUE
   87749 **          indices with the PRIMARY KEY columns.
   87750 */
   87751 static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
   87752   Index *pIdx;
   87753   Index *pPk;
   87754   int nPk;
   87755   int i, j;
   87756   sqlite3 *db = pParse->db;
   87757   Vdbe *v = pParse->pVdbe;
   87758 
   87759   /* Convert the OP_CreateTable opcode that would normally create the
   87760   ** root-page for the table into a OP_CreateIndex opcode.  The index
   87761   ** created will become the PRIMARY KEY index.
   87762   */
   87763   if( pParse->addrCrTab ){
   87764     assert( v );
   87765     sqlite3VdbeGetOp(v, pParse->addrCrTab)->opcode = OP_CreateIndex;
   87766   }
   87767 
   87768   /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
   87769   ** table entry.
   87770   */
   87771   if( pParse->addrSkipPK ){
   87772     assert( v );
   87773     sqlite3VdbeGetOp(v, pParse->addrSkipPK)->opcode = OP_Goto;
   87774   }
   87775 
   87776   /* Locate the PRIMARY KEY index.  Or, if this table was originally
   87777   ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
   87778   */
   87779   if( pTab->iPKey>=0 ){
   87780     ExprList *pList;
   87781     pList = sqlite3ExprListAppend(pParse, 0, 0);
   87782     if( pList==0 ) return;
   87783     pList->a[0].zName = sqlite3DbStrDup(pParse->db,
   87784                                         pTab->aCol[pTab->iPKey].zName);
   87785     pList->a[0].sortOrder = pParse->iPkSortOrder;
   87786     assert( pParse->pNewTable==pTab );
   87787     pPk = sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0);
   87788     if( pPk==0 ) return;
   87789     pPk->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
   87790     pTab->iPKey = -1;
   87791   }else{
   87792     pPk = sqlite3PrimaryKeyIndex(pTab);
   87793   }
   87794   pPk->isCovering = 1;
   87795   assert( pPk!=0 );
   87796   nPk = pPk->nKeyCol;
   87797 
   87798   /* Make sure every column of the PRIMARY KEY is NOT NULL */
   87799   for(i=0; i<nPk; i++){
   87800     pTab->aCol[pPk->aiColumn[i]].notNull = 1;
   87801   }
   87802   pPk->uniqNotNull = 1;
   87803 
   87804   /* The root page of the PRIMARY KEY is the table root page */
   87805   pPk->tnum = pTab->tnum;
   87806 
   87807   /* Update the in-memory representation of all UNIQUE indices by converting
   87808   ** the final rowid column into one or more columns of the PRIMARY KEY.
   87809   */
   87810   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   87811     int n;
   87812     if( IsPrimaryKeyIndex(pIdx) ) continue;
   87813     for(i=n=0; i<nPk; i++){
   87814       if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
   87815     }
   87816     if( n==0 ){
   87817       /* This index is a superset of the primary key */
   87818       pIdx->nColumn = pIdx->nKeyCol;
   87819       continue;
   87820     }
   87821     if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
   87822     for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
   87823       if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
   87824         pIdx->aiColumn[j] = pPk->aiColumn[i];
   87825         pIdx->azColl[j] = pPk->azColl[i];
   87826         j++;
   87827       }
   87828     }
   87829     assert( pIdx->nColumn>=pIdx->nKeyCol+n );
   87830     assert( pIdx->nColumn>=j );
   87831   }
   87832 
   87833   /* Add all table columns to the PRIMARY KEY index
   87834   */
   87835   if( nPk<pTab->nCol ){
   87836     if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
   87837     for(i=0, j=nPk; i<pTab->nCol; i++){
   87838       if( !hasColumn(pPk->aiColumn, j, i) ){
   87839         assert( j<pPk->nColumn );
   87840         pPk->aiColumn[j] = i;
   87841         pPk->azColl[j] = "BINARY";
   87842         j++;
   87843       }
   87844     }
   87845     assert( pPk->nColumn==j );
   87846     assert( pTab->nCol==j );
   87847   }else{
   87848     pPk->nColumn = pTab->nCol;
   87849   }
   87850 }
   87851 
   87852 /*
   87853 ** This routine is called to report the final ")" that terminates
   87854 ** a CREATE TABLE statement.
   87855 **
   87856 ** The table structure that other action routines have been building
   87857 ** is added to the internal hash tables, assuming no errors have
   87858 ** occurred.
   87859 **
   87860 ** An entry for the table is made in the master table on disk, unless
   87861 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
   87862 ** it means we are reading the sqlite_master table because we just
   87863 ** connected to the database or because the sqlite_master table has
   87864 ** recently changed, so the entry for this table already exists in
   87865 ** the sqlite_master table.  We do not want to create it again.
   87866 **
   87867 ** If the pSelect argument is not NULL, it means that this routine
   87868 ** was called to create a table generated from a
   87869 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
   87870 ** the new table will match the result set of the SELECT.
   87871 */
   87872 SQLITE_PRIVATE void sqlite3EndTable(
   87873   Parse *pParse,          /* Parse context */
   87874   Token *pCons,           /* The ',' token after the last column defn. */
   87875   Token *pEnd,            /* The ')' before options in the CREATE TABLE */
   87876   u8 tabOpts,             /* Extra table options. Usually 0. */
   87877   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
   87878 ){
   87879   Table *p;                 /* The new table */
   87880   sqlite3 *db = pParse->db; /* The database connection */
   87881   int iDb;                  /* Database in which the table lives */
   87882   Index *pIdx;              /* An implied index of the table */
   87883 
   87884   if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
   87885     return;
   87886   }
   87887   p = pParse->pNewTable;
   87888   if( p==0 ) return;
   87889 
   87890   assert( !db->init.busy || !pSelect );
   87891 
   87892   /* If the db->init.busy is 1 it means we are reading the SQL off the
   87893   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
   87894   ** So do not write to the disk again.  Extract the root page number
   87895   ** for the table from the db->init.newTnum field.  (The page number
   87896   ** should have been put there by the sqliteOpenCb routine.)
   87897   */
   87898   if( db->init.busy ){
   87899     p->tnum = db->init.newTnum;
   87900   }
   87901 
   87902   /* Special processing for WITHOUT ROWID Tables */
   87903   if( tabOpts & TF_WithoutRowid ){
   87904     if( (p->tabFlags & TF_Autoincrement) ){
   87905       sqlite3ErrorMsg(pParse,
   87906           "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
   87907       return;
   87908     }
   87909     if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
   87910       sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
   87911     }else{
   87912       p->tabFlags |= TF_WithoutRowid;
   87913       convertToWithoutRowidTable(pParse, p);
   87914     }
   87915   }
   87916 
   87917   iDb = sqlite3SchemaToIndex(db, p->pSchema);
   87918 
   87919 #ifndef SQLITE_OMIT_CHECK
   87920   /* Resolve names in all CHECK constraint expressions.
   87921   */
   87922   if( p->pCheck ){
   87923     sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
   87924   }
   87925 #endif /* !defined(SQLITE_OMIT_CHECK) */
   87926 
   87927   /* Estimate the average row size for the table and for all implied indices */
   87928   estimateTableWidth(p);
   87929   for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
   87930     estimateIndexWidth(pIdx);
   87931   }
   87932 
   87933   /* If not initializing, then create a record for the new table
   87934   ** in the SQLITE_MASTER table of the database.
   87935   **
   87936   ** If this is a TEMPORARY table, write the entry into the auxiliary
   87937   ** file instead of into the main database file.
   87938   */
   87939   if( !db->init.busy ){
   87940     int n;
   87941     Vdbe *v;
   87942     char *zType;    /* "view" or "table" */
   87943     char *zType2;   /* "VIEW" or "TABLE" */
   87944     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
   87945 
   87946     v = sqlite3GetVdbe(pParse);
   87947     if( NEVER(v==0) ) return;
   87948 
   87949     sqlite3VdbeAddOp1(v, OP_Close, 0);
   87950 
   87951     /*
   87952     ** Initialize zType for the new view or table.
   87953     */
   87954     if( p->pSelect==0 ){
   87955       /* A regular table */
   87956       zType = "table";
   87957       zType2 = "TABLE";
   87958 #ifndef SQLITE_OMIT_VIEW
   87959     }else{
   87960       /* A view */
   87961       zType = "view";
   87962       zType2 = "VIEW";
   87963 #endif
   87964     }
   87965 
   87966     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
   87967     ** statement to populate the new table. The root-page number for the
   87968     ** new table is in register pParse->regRoot.
   87969     **
   87970     ** Once the SELECT has been coded by sqlite3Select(), it is in a
   87971     ** suitable state to query for the column names and types to be used
   87972     ** by the new table.
   87973     **
   87974     ** A shared-cache write-lock is not required to write to the new table,
   87975     ** as a schema-lock must have already been obtained to create it. Since
   87976     ** a schema-lock excludes all other database users, the write-lock would
   87977     ** be redundant.
   87978     */
   87979     if( pSelect ){
   87980       SelectDest dest;
   87981       Table *pSelTab;
   87982 
   87983       assert(pParse->nTab==1);
   87984       sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
   87985       sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
   87986       pParse->nTab = 2;
   87987       sqlite3SelectDestInit(&dest, SRT_Table, 1);
   87988       sqlite3Select(pParse, pSelect, &dest);
   87989       sqlite3VdbeAddOp1(v, OP_Close, 1);
   87990       if( pParse->nErr==0 ){
   87991         pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
   87992         if( pSelTab==0 ) return;
   87993         assert( p->aCol==0 );
   87994         p->nCol = pSelTab->nCol;
   87995         p->aCol = pSelTab->aCol;
   87996         pSelTab->nCol = 0;
   87997         pSelTab->aCol = 0;
   87998         sqlite3DeleteTable(db, pSelTab);
   87999       }
   88000     }
   88001 
   88002     /* Compute the complete text of the CREATE statement */
   88003     if( pSelect ){
   88004       zStmt = createTableStmt(db, p);
   88005     }else{
   88006       Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
   88007       n = (int)(pEnd2->z - pParse->sNameToken.z);
   88008       if( pEnd2->z[0]!=';' ) n += pEnd2->n;
   88009       zStmt = sqlite3MPrintf(db,
   88010           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
   88011       );
   88012     }
   88013 
   88014     /* A slot for the record has already been allocated in the
   88015     ** SQLITE_MASTER table.  We just need to update that slot with all
   88016     ** the information we've collected.
   88017     */
   88018     sqlite3NestedParse(pParse,
   88019       "UPDATE %Q.%s "
   88020          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
   88021        "WHERE rowid=#%d",
   88022       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
   88023       zType,
   88024       p->zName,
   88025       p->zName,
   88026       pParse->regRoot,
   88027       zStmt,
   88028       pParse->regRowid
   88029     );
   88030     sqlite3DbFree(db, zStmt);
   88031     sqlite3ChangeCookie(pParse, iDb);
   88032 
   88033 #ifndef SQLITE_OMIT_AUTOINCREMENT
   88034     /* Check to see if we need to create an sqlite_sequence table for
   88035     ** keeping track of autoincrement keys.
   88036     */
   88037     if( p->tabFlags & TF_Autoincrement ){
   88038       Db *pDb = &db->aDb[iDb];
   88039       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   88040       if( pDb->pSchema->pSeqTab==0 ){
   88041         sqlite3NestedParse(pParse,
   88042           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
   88043           pDb->zName
   88044         );
   88045       }
   88046     }
   88047 #endif
   88048 
   88049     /* Reparse everything to update our internal data structures */
   88050     sqlite3VdbeAddParseSchemaOp(v, iDb,
   88051            sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
   88052   }
   88053 
   88054 
   88055   /* Add the table to the in-memory representation of the database.
   88056   */
   88057   if( db->init.busy ){
   88058     Table *pOld;
   88059     Schema *pSchema = p->pSchema;
   88060     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   88061     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
   88062                              sqlite3Strlen30(p->zName),p);
   88063     if( pOld ){
   88064       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
   88065       db->mallocFailed = 1;
   88066       return;
   88067     }
   88068     pParse->pNewTable = 0;
   88069     db->flags |= SQLITE_InternChanges;
   88070 
   88071 #ifndef SQLITE_OMIT_ALTERTABLE
   88072     if( !p->pSelect ){
   88073       const char *zName = (const char *)pParse->sNameToken.z;
   88074       int nName;
   88075       assert( !pSelect && pCons && pEnd );
   88076       if( pCons->z==0 ){
   88077         pCons = pEnd;
   88078       }
   88079       nName = (int)((const char *)pCons->z - zName);
   88080       p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
   88081     }
   88082 #endif
   88083   }
   88084 }
   88085 
   88086 #ifndef SQLITE_OMIT_VIEW
   88087 /*
   88088 ** The parser calls this routine in order to create a new VIEW
   88089 */
   88090 SQLITE_PRIVATE void sqlite3CreateView(
   88091   Parse *pParse,     /* The parsing context */
   88092   Token *pBegin,     /* The CREATE token that begins the statement */
   88093   Token *pName1,     /* The token that holds the name of the view */
   88094   Token *pName2,     /* The token that holds the name of the view */
   88095   Select *pSelect,   /* A SELECT statement that will become the new view */
   88096   int isTemp,        /* TRUE for a TEMPORARY view */
   88097   int noErr          /* Suppress error messages if VIEW already exists */
   88098 ){
   88099   Table *p;
   88100   int n;
   88101   const char *z;
   88102   Token sEnd;
   88103   DbFixer sFix;
   88104   Token *pName = 0;
   88105   int iDb;
   88106   sqlite3 *db = pParse->db;
   88107 
   88108   if( pParse->nVar>0 ){
   88109     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
   88110     sqlite3SelectDelete(db, pSelect);
   88111     return;
   88112   }
   88113   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
   88114   p = pParse->pNewTable;
   88115   if( p==0 || pParse->nErr ){
   88116     sqlite3SelectDelete(db, pSelect);
   88117     return;
   88118   }
   88119   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
   88120   iDb = sqlite3SchemaToIndex(db, p->pSchema);
   88121   sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
   88122   if( sqlite3FixSelect(&sFix, pSelect) ){
   88123     sqlite3SelectDelete(db, pSelect);
   88124     return;
   88125   }
   88126 
   88127   /* Make a copy of the entire SELECT statement that defines the view.
   88128   ** This will force all the Expr.token.z values to be dynamically
   88129   ** allocated rather than point to the input string - which means that
   88130   ** they will persist after the current sqlite3_exec() call returns.
   88131   */
   88132   p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
   88133   sqlite3SelectDelete(db, pSelect);
   88134   if( db->mallocFailed ){
   88135     return;
   88136   }
   88137   if( !db->init.busy ){
   88138     sqlite3ViewGetColumnNames(pParse, p);
   88139   }
   88140 
   88141   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
   88142   ** the end.
   88143   */
   88144   sEnd = pParse->sLastToken;
   88145   if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
   88146     sEnd.z += sEnd.n;
   88147   }
   88148   sEnd.n = 0;
   88149   n = (int)(sEnd.z - pBegin->z);
   88150   z = pBegin->z;
   88151   while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
   88152   sEnd.z = &z[n-1];
   88153   sEnd.n = 1;
   88154 
   88155   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
   88156   sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
   88157   return;
   88158 }
   88159 #endif /* SQLITE_OMIT_VIEW */
   88160 
   88161 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
   88162 /*
   88163 ** The Table structure pTable is really a VIEW.  Fill in the names of
   88164 ** the columns of the view in the pTable structure.  Return the number
   88165 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
   88166 */
   88167 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
   88168   Table *pSelTab;   /* A fake table from which we get the result set */
   88169   Select *pSel;     /* Copy of the SELECT that implements the view */
   88170   int nErr = 0;     /* Number of errors encountered */
   88171   int n;            /* Temporarily holds the number of cursors assigned */
   88172   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
   88173   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
   88174 
   88175   assert( pTable );
   88176 
   88177 #ifndef SQLITE_OMIT_VIRTUALTABLE
   88178   if( sqlite3VtabCallConnect(pParse, pTable) ){
   88179     return SQLITE_ERROR;
   88180   }
   88181   if( IsVirtual(pTable) ) return 0;
   88182 #endif
   88183 
   88184 #ifndef SQLITE_OMIT_VIEW
   88185   /* A positive nCol means the columns names for this view are
   88186   ** already known.
   88187   */
   88188   if( pTable->nCol>0 ) return 0;
   88189 
   88190   /* A negative nCol is a special marker meaning that we are currently
   88191   ** trying to compute the column names.  If we enter this routine with
   88192   ** a negative nCol, it means two or more views form a loop, like this:
   88193   **
   88194   **     CREATE VIEW one AS SELECT * FROM two;
   88195   **     CREATE VIEW two AS SELECT * FROM one;
   88196   **
   88197   ** Actually, the error above is now caught prior to reaching this point.
   88198   ** But the following test is still important as it does come up
   88199   ** in the following:
   88200   **
   88201   **     CREATE TABLE main.ex1(a);
   88202   **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
   88203   **     SELECT * FROM temp.ex1;
   88204   */
   88205   if( pTable->nCol<0 ){
   88206     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
   88207     return 1;
   88208   }
   88209   assert( pTable->nCol>=0 );
   88210 
   88211   /* If we get this far, it means we need to compute the table names.
   88212   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
   88213   ** "*" elements in the results set of the view and will assign cursors
   88214   ** to the elements of the FROM clause.  But we do not want these changes
   88215   ** to be permanent.  So the computation is done on a copy of the SELECT
   88216   ** statement that defines the view.
   88217   */
   88218   assert( pTable->pSelect );
   88219   pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
   88220   if( pSel ){
   88221     u8 enableLookaside = db->lookaside.bEnabled;
   88222     n = pParse->nTab;
   88223     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
   88224     pTable->nCol = -1;
   88225     db->lookaside.bEnabled = 0;
   88226 #ifndef SQLITE_OMIT_AUTHORIZATION
   88227     xAuth = db->xAuth;
   88228     db->xAuth = 0;
   88229     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
   88230     db->xAuth = xAuth;
   88231 #else
   88232     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
   88233 #endif
   88234     db->lookaside.bEnabled = enableLookaside;
   88235     pParse->nTab = n;
   88236     if( pSelTab ){
   88237       assert( pTable->aCol==0 );
   88238       pTable->nCol = pSelTab->nCol;
   88239       pTable->aCol = pSelTab->aCol;
   88240       pSelTab->nCol = 0;
   88241       pSelTab->aCol = 0;
   88242       sqlite3DeleteTable(db, pSelTab);
   88243       assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
   88244       pTable->pSchema->schemaFlags |= DB_UnresetViews;
   88245     }else{
   88246       pTable->nCol = 0;
   88247       nErr++;
   88248     }
   88249     sqlite3SelectDelete(db, pSel);
   88250   } else {
   88251     nErr++;
   88252   }
   88253 #endif /* SQLITE_OMIT_VIEW */
   88254   return nErr;
   88255 }
   88256 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
   88257 
   88258 #ifndef SQLITE_OMIT_VIEW
   88259 /*
   88260 ** Clear the column names from every VIEW in database idx.
   88261 */
   88262 static void sqliteViewResetAll(sqlite3 *db, int idx){
   88263   HashElem *i;
   88264   assert( sqlite3SchemaMutexHeld(db, idx, 0) );
   88265   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
   88266   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
   88267     Table *pTab = sqliteHashData(i);
   88268     if( pTab->pSelect ){
   88269       sqliteDeleteColumnNames(db, pTab);
   88270       pTab->aCol = 0;
   88271       pTab->nCol = 0;
   88272     }
   88273   }
   88274   DbClearProperty(db, idx, DB_UnresetViews);
   88275 }
   88276 #else
   88277 # define sqliteViewResetAll(A,B)
   88278 #endif /* SQLITE_OMIT_VIEW */
   88279 
   88280 /*
   88281 ** This function is called by the VDBE to adjust the internal schema
   88282 ** used by SQLite when the btree layer moves a table root page. The
   88283 ** root-page of a table or index in database iDb has changed from iFrom
   88284 ** to iTo.
   88285 **
   88286 ** Ticket #1728:  The symbol table might still contain information
   88287 ** on tables and/or indices that are the process of being deleted.
   88288 ** If you are unlucky, one of those deleted indices or tables might
   88289 ** have the same rootpage number as the real table or index that is
   88290 ** being moved.  So we cannot stop searching after the first match
   88291 ** because the first match might be for one of the deleted indices
   88292 ** or tables and not the table/index that is actually being moved.
   88293 ** We must continue looping until all tables and indices with
   88294 ** rootpage==iFrom have been converted to have a rootpage of iTo
   88295 ** in order to be certain that we got the right one.
   88296 */
   88297 #ifndef SQLITE_OMIT_AUTOVACUUM
   88298 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
   88299   HashElem *pElem;
   88300   Hash *pHash;
   88301   Db *pDb;
   88302 
   88303   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   88304   pDb = &db->aDb[iDb];
   88305   pHash = &pDb->pSchema->tblHash;
   88306   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
   88307     Table *pTab = sqliteHashData(pElem);
   88308     if( pTab->tnum==iFrom ){
   88309       pTab->tnum = iTo;
   88310     }
   88311   }
   88312   pHash = &pDb->pSchema->idxHash;
   88313   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
   88314     Index *pIdx = sqliteHashData(pElem);
   88315     if( pIdx->tnum==iFrom ){
   88316       pIdx->tnum = iTo;
   88317     }
   88318   }
   88319 }
   88320 #endif
   88321 
   88322 /*
   88323 ** Write code to erase the table with root-page iTable from database iDb.
   88324 ** Also write code to modify the sqlite_master table and internal schema
   88325 ** if a root-page of another table is moved by the btree-layer whilst
   88326 ** erasing iTable (this can happen with an auto-vacuum database).
   88327 */
   88328 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
   88329   Vdbe *v = sqlite3GetVdbe(pParse);
   88330   int r1 = sqlite3GetTempReg(pParse);
   88331   sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
   88332   sqlite3MayAbort(pParse);
   88333 #ifndef SQLITE_OMIT_AUTOVACUUM
   88334   /* OP_Destroy stores an in integer r1. If this integer
   88335   ** is non-zero, then it is the root page number of a table moved to
   88336   ** location iTable. The following code modifies the sqlite_master table to
   88337   ** reflect this.
   88338   **
   88339   ** The "#NNN" in the SQL is a special constant that means whatever value
   88340   ** is in register NNN.  See grammar rules associated with the TK_REGISTER
   88341   ** token for additional information.
   88342   */
   88343   sqlite3NestedParse(pParse,
   88344      "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
   88345      pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
   88346 #endif
   88347   sqlite3ReleaseTempReg(pParse, r1);
   88348 }
   88349 
   88350 /*
   88351 ** Write VDBE code to erase table pTab and all associated indices on disk.
   88352 ** Code to update the sqlite_master tables and internal schema definitions
   88353 ** in case a root-page belonging to another table is moved by the btree layer
   88354 ** is also added (this can happen with an auto-vacuum database).
   88355 */
   88356 static void destroyTable(Parse *pParse, Table *pTab){
   88357 #ifdef SQLITE_OMIT_AUTOVACUUM
   88358   Index *pIdx;
   88359   int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   88360   destroyRootPage(pParse, pTab->tnum, iDb);
   88361   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   88362     destroyRootPage(pParse, pIdx->tnum, iDb);
   88363   }
   88364 #else
   88365   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
   88366   ** is not defined), then it is important to call OP_Destroy on the
   88367   ** table and index root-pages in order, starting with the numerically
   88368   ** largest root-page number. This guarantees that none of the root-pages
   88369   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
   88370   ** following were coded:
   88371   **
   88372   ** OP_Destroy 4 0
   88373   ** ...
   88374   ** OP_Destroy 5 0
   88375   **
   88376   ** and root page 5 happened to be the largest root-page number in the
   88377   ** database, then root page 5 would be moved to page 4 by the
   88378   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
   88379   ** a free-list page.
   88380   */
   88381   int iTab = pTab->tnum;
   88382   int iDestroyed = 0;
   88383 
   88384   while( 1 ){
   88385     Index *pIdx;
   88386     int iLargest = 0;
   88387 
   88388     if( iDestroyed==0 || iTab<iDestroyed ){
   88389       iLargest = iTab;
   88390     }
   88391     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   88392       int iIdx = pIdx->tnum;
   88393       assert( pIdx->pSchema==pTab->pSchema );
   88394       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
   88395         iLargest = iIdx;
   88396       }
   88397     }
   88398     if( iLargest==0 ){
   88399       return;
   88400     }else{
   88401       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   88402       assert( iDb>=0 && iDb<pParse->db->nDb );
   88403       destroyRootPage(pParse, iLargest, iDb);
   88404       iDestroyed = iLargest;
   88405     }
   88406   }
   88407 #endif
   88408 }
   88409 
   88410 /*
   88411 ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
   88412 ** after a DROP INDEX or DROP TABLE command.
   88413 */
   88414 static void sqlite3ClearStatTables(
   88415   Parse *pParse,         /* The parsing context */
   88416   int iDb,               /* The database number */
   88417   const char *zType,     /* "idx" or "tbl" */
   88418   const char *zName      /* Name of index or table */
   88419 ){
   88420   int i;
   88421   const char *zDbName = pParse->db->aDb[iDb].zName;
   88422   for(i=1; i<=4; i++){
   88423     char zTab[24];
   88424     sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
   88425     if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
   88426       sqlite3NestedParse(pParse,
   88427         "DELETE FROM %Q.%s WHERE %s=%Q",
   88428         zDbName, zTab, zType, zName
   88429       );
   88430     }
   88431   }
   88432 }
   88433 
   88434 /*
   88435 ** Generate code to drop a table.
   88436 */
   88437 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
   88438   Vdbe *v;
   88439   sqlite3 *db = pParse->db;
   88440   Trigger *pTrigger;
   88441   Db *pDb = &db->aDb[iDb];
   88442 
   88443   v = sqlite3GetVdbe(pParse);
   88444   assert( v!=0 );
   88445   sqlite3BeginWriteOperation(pParse, 1, iDb);
   88446 
   88447 #ifndef SQLITE_OMIT_VIRTUALTABLE
   88448   if( IsVirtual(pTab) ){
   88449     sqlite3VdbeAddOp0(v, OP_VBegin);
   88450   }
   88451 #endif
   88452 
   88453   /* Drop all triggers associated with the table being dropped. Code
   88454   ** is generated to remove entries from sqlite_master and/or
   88455   ** sqlite_temp_master if required.
   88456   */
   88457   pTrigger = sqlite3TriggerList(pParse, pTab);
   88458   while( pTrigger ){
   88459     assert( pTrigger->pSchema==pTab->pSchema ||
   88460         pTrigger->pSchema==db->aDb[1].pSchema );
   88461     sqlite3DropTriggerPtr(pParse, pTrigger);
   88462     pTrigger = pTrigger->pNext;
   88463   }
   88464 
   88465 #ifndef SQLITE_OMIT_AUTOINCREMENT
   88466   /* Remove any entries of the sqlite_sequence table associated with
   88467   ** the table being dropped. This is done before the table is dropped
   88468   ** at the btree level, in case the sqlite_sequence table needs to
   88469   ** move as a result of the drop (can happen in auto-vacuum mode).
   88470   */
   88471   if( pTab->tabFlags & TF_Autoincrement ){
   88472     sqlite3NestedParse(pParse,
   88473       "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
   88474       pDb->zName, pTab->zName
   88475     );
   88476   }
   88477 #endif
   88478 
   88479   /* Drop all SQLITE_MASTER table and index entries that refer to the
   88480   ** table. The program name loops through the master table and deletes
   88481   ** every row that refers to a table of the same name as the one being
   88482   ** dropped. Triggers are handled separately because a trigger can be
   88483   ** created in the temp database that refers to a table in another
   88484   ** database.
   88485   */
   88486   sqlite3NestedParse(pParse,
   88487       "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
   88488       pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
   88489   if( !isView && !IsVirtual(pTab) ){
   88490     destroyTable(pParse, pTab);
   88491   }
   88492 
   88493   /* Remove the table entry from SQLite's internal schema and modify
   88494   ** the schema cookie.
   88495   */
   88496   if( IsVirtual(pTab) ){
   88497     sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
   88498   }
   88499   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
   88500   sqlite3ChangeCookie(pParse, iDb);
   88501   sqliteViewResetAll(db, iDb);
   88502 }
   88503 
   88504 /*
   88505 ** This routine is called to do the work of a DROP TABLE statement.
   88506 ** pName is the name of the table to be dropped.
   88507 */
   88508 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
   88509   Table *pTab;
   88510   Vdbe *v;
   88511   sqlite3 *db = pParse->db;
   88512   int iDb;
   88513 
   88514   if( db->mallocFailed ){
   88515     goto exit_drop_table;
   88516   }
   88517   assert( pParse->nErr==0 );
   88518   assert( pName->nSrc==1 );
   88519   if( noErr ) db->suppressErr++;
   88520   pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
   88521   if( noErr ) db->suppressErr--;
   88522 
   88523   if( pTab==0 ){
   88524     if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
   88525     goto exit_drop_table;
   88526   }
   88527   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   88528   assert( iDb>=0 && iDb<db->nDb );
   88529 
   88530   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
   88531   ** it is initialized.
   88532   */
   88533   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
   88534     goto exit_drop_table;
   88535   }
   88536 #ifndef SQLITE_OMIT_AUTHORIZATION
   88537   {
   88538     int code;
   88539     const char *zTab = SCHEMA_TABLE(iDb);
   88540     const char *zDb = db->aDb[iDb].zName;
   88541     const char *zArg2 = 0;
   88542     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
   88543       goto exit_drop_table;
   88544     }
   88545     if( isView ){
   88546       if( !OMIT_TEMPDB && iDb==1 ){
   88547         code = SQLITE_DROP_TEMP_VIEW;
   88548       }else{
   88549         code = SQLITE_DROP_VIEW;
   88550       }
   88551 #ifndef SQLITE_OMIT_VIRTUALTABLE
   88552     }else if( IsVirtual(pTab) ){
   88553       code = SQLITE_DROP_VTABLE;
   88554       zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
   88555 #endif
   88556     }else{
   88557       if( !OMIT_TEMPDB && iDb==1 ){
   88558         code = SQLITE_DROP_TEMP_TABLE;
   88559       }else{
   88560         code = SQLITE_DROP_TABLE;
   88561       }
   88562     }
   88563     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
   88564       goto exit_drop_table;
   88565     }
   88566     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
   88567       goto exit_drop_table;
   88568     }
   88569   }
   88570 #endif
   88571   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
   88572     && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
   88573     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
   88574     goto exit_drop_table;
   88575   }
   88576 
   88577 #ifndef SQLITE_OMIT_VIEW
   88578   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
   88579   ** on a table.
   88580   */
   88581   if( isView && pTab->pSelect==0 ){
   88582     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
   88583     goto exit_drop_table;
   88584   }
   88585   if( !isView && pTab->pSelect ){
   88586     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
   88587     goto exit_drop_table;
   88588   }
   88589 #endif
   88590 
   88591   /* Generate code to remove the table from the master table
   88592   ** on disk.
   88593   */
   88594   v = sqlite3GetVdbe(pParse);
   88595   if( v ){
   88596     sqlite3BeginWriteOperation(pParse, 1, iDb);
   88597     sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
   88598     sqlite3FkDropTable(pParse, pName, pTab);
   88599     sqlite3CodeDropTable(pParse, pTab, iDb, isView);
   88600   }
   88601 
   88602 exit_drop_table:
   88603   sqlite3SrcListDelete(db, pName);
   88604 }
   88605 
   88606 /*
   88607 ** This routine is called to create a new foreign key on the table
   88608 ** currently under construction.  pFromCol determines which columns
   88609 ** in the current table point to the foreign key.  If pFromCol==0 then
   88610 ** connect the key to the last column inserted.  pTo is the name of
   88611 ** the table referred to (a.k.a the "parent" table).  pToCol is a list
   88612 ** of tables in the parent pTo table.  flags contains all
   88613 ** information about the conflict resolution algorithms specified
   88614 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
   88615 **
   88616 ** An FKey structure is created and added to the table currently
   88617 ** under construction in the pParse->pNewTable field.
   88618 **
   88619 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
   88620 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
   88621 */
   88622 SQLITE_PRIVATE void sqlite3CreateForeignKey(
   88623   Parse *pParse,       /* Parsing context */
   88624   ExprList *pFromCol,  /* Columns in this table that point to other table */
   88625   Token *pTo,          /* Name of the other table */
   88626   ExprList *pToCol,    /* Columns in the other table */
   88627   int flags            /* Conflict resolution algorithms. */
   88628 ){
   88629   sqlite3 *db = pParse->db;
   88630 #ifndef SQLITE_OMIT_FOREIGN_KEY
   88631   FKey *pFKey = 0;
   88632   FKey *pNextTo;
   88633   Table *p = pParse->pNewTable;
   88634   int nByte;
   88635   int i;
   88636   int nCol;
   88637   char *z;
   88638 
   88639   assert( pTo!=0 );
   88640   if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
   88641   if( pFromCol==0 ){
   88642     int iCol = p->nCol-1;
   88643     if( NEVER(iCol<0) ) goto fk_end;
   88644     if( pToCol && pToCol->nExpr!=1 ){
   88645       sqlite3ErrorMsg(pParse, "foreign key on %s"
   88646          " should reference only one column of table %T",
   88647          p->aCol[iCol].zName, pTo);
   88648       goto fk_end;
   88649     }
   88650     nCol = 1;
   88651   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
   88652     sqlite3ErrorMsg(pParse,
   88653         "number of columns in foreign key does not match the number of "
   88654         "columns in the referenced table");
   88655     goto fk_end;
   88656   }else{
   88657     nCol = pFromCol->nExpr;
   88658   }
   88659   nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
   88660   if( pToCol ){
   88661     for(i=0; i<pToCol->nExpr; i++){
   88662       nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
   88663     }
   88664   }
   88665   pFKey = sqlite3DbMallocZero(db, nByte );
   88666   if( pFKey==0 ){
   88667     goto fk_end;
   88668   }
   88669   pFKey->pFrom = p;
   88670   pFKey->pNextFrom = p->pFKey;
   88671   z = (char*)&pFKey->aCol[nCol];
   88672   pFKey->zTo = z;
   88673   memcpy(z, pTo->z, pTo->n);
   88674   z[pTo->n] = 0;
   88675   sqlite3Dequote(z);
   88676   z += pTo->n+1;
   88677   pFKey->nCol = nCol;
   88678   if( pFromCol==0 ){
   88679     pFKey->aCol[0].iFrom = p->nCol-1;
   88680   }else{
   88681     for(i=0; i<nCol; i++){
   88682       int j;
   88683       for(j=0; j<p->nCol; j++){
   88684         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
   88685           pFKey->aCol[i].iFrom = j;
   88686           break;
   88687         }
   88688       }
   88689       if( j>=p->nCol ){
   88690         sqlite3ErrorMsg(pParse,
   88691           "unknown column \"%s\" in foreign key definition",
   88692           pFromCol->a[i].zName);
   88693         goto fk_end;
   88694       }
   88695     }
   88696   }
   88697   if( pToCol ){
   88698     for(i=0; i<nCol; i++){
   88699       int n = sqlite3Strlen30(pToCol->a[i].zName);
   88700       pFKey->aCol[i].zCol = z;
   88701       memcpy(z, pToCol->a[i].zName, n);
   88702       z[n] = 0;
   88703       z += n+1;
   88704     }
   88705   }
   88706   pFKey->isDeferred = 0;
   88707   pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
   88708   pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
   88709 
   88710   assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
   88711   pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
   88712       pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
   88713   );
   88714   if( pNextTo==pFKey ){
   88715     db->mallocFailed = 1;
   88716     goto fk_end;
   88717   }
   88718   if( pNextTo ){
   88719     assert( pNextTo->pPrevTo==0 );
   88720     pFKey->pNextTo = pNextTo;
   88721     pNextTo->pPrevTo = pFKey;
   88722   }
   88723 
   88724   /* Link the foreign key to the table as the last step.
   88725   */
   88726   p->pFKey = pFKey;
   88727   pFKey = 0;
   88728 
   88729 fk_end:
   88730   sqlite3DbFree(db, pFKey);
   88731 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
   88732   sqlite3ExprListDelete(db, pFromCol);
   88733   sqlite3ExprListDelete(db, pToCol);
   88734 }
   88735 
   88736 /*
   88737 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
   88738 ** clause is seen as part of a foreign key definition.  The isDeferred
   88739 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
   88740 ** The behavior of the most recently created foreign key is adjusted
   88741 ** accordingly.
   88742 */
   88743 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
   88744 #ifndef SQLITE_OMIT_FOREIGN_KEY
   88745   Table *pTab;
   88746   FKey *pFKey;
   88747   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
   88748   assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
   88749   pFKey->isDeferred = (u8)isDeferred;
   88750 #endif
   88751 }
   88752 
   88753 /*
   88754 ** Generate code that will erase and refill index *pIdx.  This is
   88755 ** used to initialize a newly created index or to recompute the
   88756 ** content of an index in response to a REINDEX command.
   88757 **
   88758 ** if memRootPage is not negative, it means that the index is newly
   88759 ** created.  The register specified by memRootPage contains the
   88760 ** root page number of the index.  If memRootPage is negative, then
   88761 ** the index already exists and must be cleared before being refilled and
   88762 ** the root page number of the index is taken from pIndex->tnum.
   88763 */
   88764 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
   88765   Table *pTab = pIndex->pTable;  /* The table that is indexed */
   88766   int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
   88767   int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
   88768   int iSorter;                   /* Cursor opened by OpenSorter (if in use) */
   88769   int addr1;                     /* Address of top of loop */
   88770   int addr2;                     /* Address to jump to for next iteration */
   88771   int tnum;                      /* Root page of index */
   88772   int iPartIdxLabel;             /* Jump to this label to skip a row */
   88773   Vdbe *v;                       /* Generate code into this virtual machine */
   88774   KeyInfo *pKey;                 /* KeyInfo for index */
   88775   int regRecord;                 /* Register holding assemblied index record */
   88776   sqlite3 *db = pParse->db;      /* The database connection */
   88777   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
   88778 
   88779 #ifndef SQLITE_OMIT_AUTHORIZATION
   88780   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
   88781       db->aDb[iDb].zName ) ){
   88782     return;
   88783   }
   88784 #endif
   88785 
   88786   /* Require a write-lock on the table to perform this operation */
   88787   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
   88788 
   88789   v = sqlite3GetVdbe(pParse);
   88790   if( v==0 ) return;
   88791   if( memRootPage>=0 ){
   88792     tnum = memRootPage;
   88793   }else{
   88794     tnum = pIndex->tnum;
   88795   }
   88796   pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
   88797 
   88798   /* Open the sorter cursor if we are to use one. */
   88799   iSorter = pParse->nTab++;
   88800   sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, 0, (char*)
   88801                     sqlite3KeyInfoRef(pKey), P4_KEYINFO);
   88802 
   88803   /* Open the table. Loop through all rows of the table, inserting index
   88804   ** records into the sorter. */
   88805   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
   88806   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
   88807   regRecord = sqlite3GetTempReg(pParse);
   88808 
   88809   sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
   88810   sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
   88811   sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
   88812   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
   88813   sqlite3VdbeJumpHere(v, addr1);
   88814   if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
   88815   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
   88816                     (char *)pKey, P4_KEYINFO);
   88817   sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
   88818 
   88819   addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
   88820   assert( pKey!=0 || db->mallocFailed || pParse->nErr );
   88821   if( IsUniqueIndex(pIndex) && pKey!=0 ){
   88822     int j2 = sqlite3VdbeCurrentAddr(v) + 3;
   88823     sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
   88824     addr2 = sqlite3VdbeCurrentAddr(v);
   88825     sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
   88826                          pIndex->nKeyCol); VdbeCoverage(v);
   88827     sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
   88828   }else{
   88829     addr2 = sqlite3VdbeCurrentAddr(v);
   88830   }
   88831   sqlite3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord);
   88832   sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
   88833   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
   88834   sqlite3ReleaseTempReg(pParse, regRecord);
   88835   sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
   88836   sqlite3VdbeJumpHere(v, addr1);
   88837 
   88838   sqlite3VdbeAddOp1(v, OP_Close, iTab);
   88839   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
   88840   sqlite3VdbeAddOp1(v, OP_Close, iSorter);
   88841 }
   88842 
   88843 /*
   88844 ** Allocate heap space to hold an Index object with nCol columns.
   88845 **
   88846 ** Increase the allocation size to provide an extra nExtra bytes
   88847 ** of 8-byte aligned space after the Index object and return a
   88848 ** pointer to this extra space in *ppExtra.
   88849 */
   88850 SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(
   88851   sqlite3 *db,         /* Database connection */
   88852   i16 nCol,            /* Total number of columns in the index */
   88853   int nExtra,          /* Number of bytes of extra space to alloc */
   88854   char **ppExtra       /* Pointer to the "extra" space */
   88855 ){
   88856   Index *p;            /* Allocated index object */
   88857   int nByte;           /* Bytes of space for Index object + arrays */
   88858 
   88859   nByte = ROUND8(sizeof(Index)) +              /* Index structure  */
   88860           ROUND8(sizeof(char*)*nCol) +         /* Index.azColl     */
   88861           ROUND8(sizeof(LogEst)*(nCol+1) +     /* Index.aiRowLogEst   */
   88862                  sizeof(i16)*nCol +            /* Index.aiColumn   */
   88863                  sizeof(u8)*nCol);             /* Index.aSortOrder */
   88864   p = sqlite3DbMallocZero(db, nByte + nExtra);
   88865   if( p ){
   88866     char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
   88867     p->azColl = (char**)pExtra;       pExtra += ROUND8(sizeof(char*)*nCol);
   88868     p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
   88869     p->aiColumn = (i16*)pExtra;       pExtra += sizeof(i16)*nCol;
   88870     p->aSortOrder = (u8*)pExtra;
   88871     p->nColumn = nCol;
   88872     p->nKeyCol = nCol - 1;
   88873     *ppExtra = ((char*)p) + nByte;
   88874   }
   88875   return p;
   88876 }
   88877 
   88878 /*
   88879 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index
   88880 ** and pTblList is the name of the table that is to be indexed.  Both will
   88881 ** be NULL for a primary key or an index that is created to satisfy a
   88882 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
   88883 ** as the table to be indexed.  pParse->pNewTable is a table that is
   88884 ** currently being constructed by a CREATE TABLE statement.
   88885 **
   88886 ** pList is a list of columns to be indexed.  pList will be NULL if this
   88887 ** is a primary key or unique-constraint on the most recent column added
   88888 ** to the table currently under construction.
   88889 **
   88890 ** If the index is created successfully, return a pointer to the new Index
   88891 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
   88892 ** as the tables primary key (Index.idxType==SQLITE_IDXTYPE_PRIMARYKEY)
   88893 */
   88894 SQLITE_PRIVATE Index *sqlite3CreateIndex(
   88895   Parse *pParse,     /* All information about this parse */
   88896   Token *pName1,     /* First part of index name. May be NULL */
   88897   Token *pName2,     /* Second part of index name. May be NULL */
   88898   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
   88899   ExprList *pList,   /* A list of columns to be indexed */
   88900   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
   88901   Token *pStart,     /* The CREATE token that begins this statement */
   88902   Expr *pPIWhere,    /* WHERE clause for partial indices */
   88903   int sortOrder,     /* Sort order of primary key when pList==NULL */
   88904   int ifNotExist     /* Omit error if index already exists */
   88905 ){
   88906   Index *pRet = 0;     /* Pointer to return */
   88907   Table *pTab = 0;     /* Table to be indexed */
   88908   Index *pIndex = 0;   /* The index to be created */
   88909   char *zName = 0;     /* Name of the index */
   88910   int nName;           /* Number of characters in zName */
   88911   int i, j;
   88912   DbFixer sFix;        /* For assigning database names to pTable */
   88913   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
   88914   sqlite3 *db = pParse->db;
   88915   Db *pDb;             /* The specific table containing the indexed database */
   88916   int iDb;             /* Index of the database that is being written */
   88917   Token *pName = 0;    /* Unqualified name of the index to create */
   88918   struct ExprList_item *pListItem; /* For looping over pList */
   88919   const Column *pTabCol;           /* A column in the table */
   88920   int nExtra = 0;                  /* Space allocated for zExtra[] */
   88921   int nExtraCol;                   /* Number of extra columns needed */
   88922   char *zExtra = 0;                /* Extra space after the Index object */
   88923   Index *pPk = 0;      /* PRIMARY KEY index for WITHOUT ROWID tables */
   88924 
   88925   assert( pParse->nErr==0 );      /* Never called with prior errors */
   88926   if( db->mallocFailed || IN_DECLARE_VTAB ){
   88927     goto exit_create_index;
   88928   }
   88929   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   88930     goto exit_create_index;
   88931   }
   88932 
   88933   /*
   88934   ** Find the table that is to be indexed.  Return early if not found.
   88935   */
   88936   if( pTblName!=0 ){
   88937 
   88938     /* Use the two-part index name to determine the database
   88939     ** to search for the table. 'Fix' the table name to this db
   88940     ** before looking up the table.
   88941     */
   88942     assert( pName1 && pName2 );
   88943     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
   88944     if( iDb<0 ) goto exit_create_index;
   88945     assert( pName && pName->z );
   88946 
   88947 #ifndef SQLITE_OMIT_TEMPDB
   88948     /* If the index name was unqualified, check if the table
   88949     ** is a temp table. If so, set the database to 1. Do not do this
   88950     ** if initialising a database schema.
   88951     */
   88952     if( !db->init.busy ){
   88953       pTab = sqlite3SrcListLookup(pParse, pTblName);
   88954       if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
   88955         iDb = 1;
   88956       }
   88957     }
   88958 #endif
   88959 
   88960     sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
   88961     if( sqlite3FixSrcList(&sFix, pTblName) ){
   88962       /* Because the parser constructs pTblName from a single identifier,
   88963       ** sqlite3FixSrcList can never fail. */
   88964       assert(0);
   88965     }
   88966     pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
   88967     assert( db->mallocFailed==0 || pTab==0 );
   88968     if( pTab==0 ) goto exit_create_index;
   88969     if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
   88970       sqlite3ErrorMsg(pParse,
   88971            "cannot create a TEMP index on non-TEMP table \"%s\"",
   88972            pTab->zName);
   88973       goto exit_create_index;
   88974     }
   88975     if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
   88976   }else{
   88977     assert( pName==0 );
   88978     assert( pStart==0 );
   88979     pTab = pParse->pNewTable;
   88980     if( !pTab ) goto exit_create_index;
   88981     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   88982   }
   88983   pDb = &db->aDb[iDb];
   88984 
   88985   assert( pTab!=0 );
   88986   assert( pParse->nErr==0 );
   88987   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
   88988        && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
   88989     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
   88990     goto exit_create_index;
   88991   }
   88992 #ifndef SQLITE_OMIT_VIEW
   88993   if( pTab->pSelect ){
   88994     sqlite3ErrorMsg(pParse, "views may not be indexed");
   88995     goto exit_create_index;
   88996   }
   88997 #endif
   88998 #ifndef SQLITE_OMIT_VIRTUALTABLE
   88999   if( IsVirtual(pTab) ){
   89000     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
   89001     goto exit_create_index;
   89002   }
   89003 #endif
   89004 
   89005   /*
   89006   ** Find the name of the index.  Make sure there is not already another
   89007   ** index or table with the same name.
   89008   **
   89009   ** Exception:  If we are reading the names of permanent indices from the
   89010   ** sqlite_master table (because some other process changed the schema) and
   89011   ** one of the index names collides with the name of a temporary table or
   89012   ** index, then we will continue to process this index.
   89013   **
   89014   ** If pName==0 it means that we are
   89015   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
   89016   ** own name.
   89017   */
   89018   if( pName ){
   89019     zName = sqlite3NameFromToken(db, pName);
   89020     if( zName==0 ) goto exit_create_index;
   89021     assert( pName->z!=0 );
   89022     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
   89023       goto exit_create_index;
   89024     }
   89025     if( !db->init.busy ){
   89026       if( sqlite3FindTable(db, zName, 0)!=0 ){
   89027         sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
   89028         goto exit_create_index;
   89029       }
   89030     }
   89031     if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
   89032       if( !ifNotExist ){
   89033         sqlite3ErrorMsg(pParse, "index %s already exists", zName);
   89034       }else{
   89035         assert( !db->init.busy );
   89036         sqlite3CodeVerifySchema(pParse, iDb);
   89037       }
   89038       goto exit_create_index;
   89039     }
   89040   }else{
   89041     int n;
   89042     Index *pLoop;
   89043     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
   89044     zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
   89045     if( zName==0 ){
   89046       goto exit_create_index;
   89047     }
   89048   }
   89049 
   89050   /* Check for authorization to create an index.
   89051   */
   89052 #ifndef SQLITE_OMIT_AUTHORIZATION
   89053   {
   89054     const char *zDb = pDb->zName;
   89055     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
   89056       goto exit_create_index;
   89057     }
   89058     i = SQLITE_CREATE_INDEX;
   89059     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
   89060     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
   89061       goto exit_create_index;
   89062     }
   89063   }
   89064 #endif
   89065 
   89066   /* If pList==0, it means this routine was called to make a primary
   89067   ** key out of the last column added to the table under construction.
   89068   ** So create a fake list to simulate this.
   89069   */
   89070   if( pList==0 ){
   89071     pList = sqlite3ExprListAppend(pParse, 0, 0);
   89072     if( pList==0 ) goto exit_create_index;
   89073     pList->a[0].zName = sqlite3DbStrDup(pParse->db,
   89074                                         pTab->aCol[pTab->nCol-1].zName);
   89075     pList->a[0].sortOrder = (u8)sortOrder;
   89076   }
   89077 
   89078   /* Figure out how many bytes of space are required to store explicitly
   89079   ** specified collation sequence names.
   89080   */
   89081   for(i=0; i<pList->nExpr; i++){
   89082     Expr *pExpr = pList->a[i].pExpr;
   89083     if( pExpr ){
   89084       assert( pExpr->op==TK_COLLATE );
   89085       nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
   89086     }
   89087   }
   89088 
   89089   /*
   89090   ** Allocate the index structure.
   89091   */
   89092   nName = sqlite3Strlen30(zName);
   89093   nExtraCol = pPk ? pPk->nKeyCol : 1;
   89094   pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
   89095                                       nName + nExtra + 1, &zExtra);
   89096   if( db->mallocFailed ){
   89097     goto exit_create_index;
   89098   }
   89099   assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
   89100   assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
   89101   pIndex->zName = zExtra;
   89102   zExtra += nName + 1;
   89103   memcpy(pIndex->zName, zName, nName+1);
   89104   pIndex->pTable = pTab;
   89105   pIndex->onError = (u8)onError;
   89106   pIndex->uniqNotNull = onError!=OE_None;
   89107   pIndex->idxType = pName ? SQLITE_IDXTYPE_APPDEF : SQLITE_IDXTYPE_UNIQUE;
   89108   pIndex->pSchema = db->aDb[iDb].pSchema;
   89109   pIndex->nKeyCol = pList->nExpr;
   89110   if( pPIWhere ){
   89111     sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
   89112     pIndex->pPartIdxWhere = pPIWhere;
   89113     pPIWhere = 0;
   89114   }
   89115   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   89116 
   89117   /* Check to see if we should honor DESC requests on index columns
   89118   */
   89119   if( pDb->pSchema->file_format>=4 ){
   89120     sortOrderMask = -1;   /* Honor DESC */
   89121   }else{
   89122     sortOrderMask = 0;    /* Ignore DESC */
   89123   }
   89124 
   89125   /* Scan the names of the columns of the table to be indexed and
   89126   ** load the column indices into the Index structure.  Report an error
   89127   ** if any column is not found.
   89128   **
   89129   ** TODO:  Add a test to make sure that the same column is not named
   89130   ** more than once within the same index.  Only the first instance of
   89131   ** the column will ever be used by the optimizer.  Note that using the
   89132   ** same column more than once cannot be an error because that would
   89133   ** break backwards compatibility - it needs to be a warning.
   89134   */
   89135   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
   89136     const char *zColName = pListItem->zName;
   89137     int requestedSortOrder;
   89138     char *zColl;                   /* Collation sequence name */
   89139 
   89140     for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
   89141       if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
   89142     }
   89143     if( j>=pTab->nCol ){
   89144       sqlite3ErrorMsg(pParse, "table %s has no column named %s",
   89145         pTab->zName, zColName);
   89146       pParse->checkSchema = 1;
   89147       goto exit_create_index;
   89148     }
   89149     assert( pTab->nCol<=0x7fff && j<=0x7fff );
   89150     pIndex->aiColumn[i] = (i16)j;
   89151     if( pListItem->pExpr ){
   89152       int nColl;
   89153       assert( pListItem->pExpr->op==TK_COLLATE );
   89154       zColl = pListItem->pExpr->u.zToken;
   89155       nColl = sqlite3Strlen30(zColl) + 1;
   89156       assert( nExtra>=nColl );
   89157       memcpy(zExtra, zColl, nColl);
   89158       zColl = zExtra;
   89159       zExtra += nColl;
   89160       nExtra -= nColl;
   89161     }else{
   89162       zColl = pTab->aCol[j].zColl;
   89163       if( !zColl ) zColl = "BINARY";
   89164     }
   89165     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
   89166       goto exit_create_index;
   89167     }
   89168     pIndex->azColl[i] = zColl;
   89169     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
   89170     pIndex->aSortOrder[i] = (u8)requestedSortOrder;
   89171     if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0;
   89172   }
   89173   if( pPk ){
   89174     for(j=0; j<pPk->nKeyCol; j++){
   89175       int x = pPk->aiColumn[j];
   89176       if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
   89177         pIndex->nColumn--;
   89178       }else{
   89179         pIndex->aiColumn[i] = x;
   89180         pIndex->azColl[i] = pPk->azColl[j];
   89181         pIndex->aSortOrder[i] = pPk->aSortOrder[j];
   89182         i++;
   89183       }
   89184     }
   89185     assert( i==pIndex->nColumn );
   89186   }else{
   89187     pIndex->aiColumn[i] = -1;
   89188     pIndex->azColl[i] = "BINARY";
   89189   }
   89190   sqlite3DefaultRowEst(pIndex);
   89191   if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
   89192 
   89193   if( pTab==pParse->pNewTable ){
   89194     /* This routine has been called to create an automatic index as a
   89195     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
   89196     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
   89197     ** i.e. one of:
   89198     **
   89199     ** CREATE TABLE t(x PRIMARY KEY, y);
   89200     ** CREATE TABLE t(x, y, UNIQUE(x, y));
   89201     **
   89202     ** Either way, check to see if the table already has such an index. If
   89203     ** so, don't bother creating this one. This only applies to
   89204     ** automatically created indices. Users can do as they wish with
   89205     ** explicit indices.
   89206     **
   89207     ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
   89208     ** (and thus suppressing the second one) even if they have different
   89209     ** sort orders.
   89210     **
   89211     ** If there are different collating sequences or if the columns of
   89212     ** the constraint occur in different orders, then the constraints are
   89213     ** considered distinct and both result in separate indices.
   89214     */
   89215     Index *pIdx;
   89216     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   89217       int k;
   89218       assert( IsUniqueIndex(pIdx) );
   89219       assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
   89220       assert( IsUniqueIndex(pIndex) );
   89221 
   89222       if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
   89223       for(k=0; k<pIdx->nKeyCol; k++){
   89224         const char *z1;
   89225         const char *z2;
   89226         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
   89227         z1 = pIdx->azColl[k];
   89228         z2 = pIndex->azColl[k];
   89229         if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
   89230       }
   89231       if( k==pIdx->nKeyCol ){
   89232         if( pIdx->onError!=pIndex->onError ){
   89233           /* This constraint creates the same index as a previous
   89234           ** constraint specified somewhere in the CREATE TABLE statement.
   89235           ** However the ON CONFLICT clauses are different. If both this
   89236           ** constraint and the previous equivalent constraint have explicit
   89237           ** ON CONFLICT clauses this is an error. Otherwise, use the
   89238           ** explicitly specified behavior for the index.
   89239           */
   89240           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
   89241             sqlite3ErrorMsg(pParse,
   89242                 "conflicting ON CONFLICT clauses specified", 0);
   89243           }
   89244           if( pIdx->onError==OE_Default ){
   89245             pIdx->onError = pIndex->onError;
   89246           }
   89247         }
   89248         goto exit_create_index;
   89249       }
   89250     }
   89251   }
   89252 
   89253   /* Link the new Index structure to its table and to the other
   89254   ** in-memory database structures.
   89255   */
   89256   if( db->init.busy ){
   89257     Index *p;
   89258     assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
   89259     p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
   89260                           pIndex->zName, sqlite3Strlen30(pIndex->zName),
   89261                           pIndex);
   89262     if( p ){
   89263       assert( p==pIndex );  /* Malloc must have failed */
   89264       db->mallocFailed = 1;
   89265       goto exit_create_index;
   89266     }
   89267     db->flags |= SQLITE_InternChanges;
   89268     if( pTblName!=0 ){
   89269       pIndex->tnum = db->init.newTnum;
   89270     }
   89271   }
   89272 
   89273   /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
   89274   ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
   89275   ** emit code to allocate the index rootpage on disk and make an entry for
   89276   ** the index in the sqlite_master table and populate the index with
   89277   ** content.  But, do not do this if we are simply reading the sqlite_master
   89278   ** table to parse the schema, or if this index is the PRIMARY KEY index
   89279   ** of a WITHOUT ROWID table.
   89280   **
   89281   ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
   89282   ** or UNIQUE index in a CREATE TABLE statement.  Since the table
   89283   ** has just been created, it contains no data and the index initialization
   89284   ** step can be skipped.
   89285   */
   89286   else if( pParse->nErr==0 && (HasRowid(pTab) || pTblName!=0) ){
   89287     Vdbe *v;
   89288     char *zStmt;
   89289     int iMem = ++pParse->nMem;
   89290 
   89291     v = sqlite3GetVdbe(pParse);
   89292     if( v==0 ) goto exit_create_index;
   89293 
   89294 
   89295     /* Create the rootpage for the index
   89296     */
   89297     sqlite3BeginWriteOperation(pParse, 1, iDb);
   89298     sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
   89299 
   89300     /* Gather the complete text of the CREATE INDEX statement into
   89301     ** the zStmt variable
   89302     */
   89303     if( pStart ){
   89304       int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
   89305       if( pName->z[n-1]==';' ) n--;
   89306       /* A named index with an explicit CREATE INDEX statement */
   89307       zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
   89308         onError==OE_None ? "" : " UNIQUE", n, pName->z);
   89309     }else{
   89310       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
   89311       /* zStmt = sqlite3MPrintf(""); */
   89312       zStmt = 0;
   89313     }
   89314 
   89315     /* Add an entry in sqlite_master for this index
   89316     */
   89317     sqlite3NestedParse(pParse,
   89318         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
   89319         db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
   89320         pIndex->zName,
   89321         pTab->zName,
   89322         iMem,
   89323         zStmt
   89324     );
   89325     sqlite3DbFree(db, zStmt);
   89326 
   89327     /* Fill the index with data and reparse the schema. Code an OP_Expire
   89328     ** to invalidate all pre-compiled statements.
   89329     */
   89330     if( pTblName ){
   89331       sqlite3RefillIndex(pParse, pIndex, iMem);
   89332       sqlite3ChangeCookie(pParse, iDb);
   89333       sqlite3VdbeAddParseSchemaOp(v, iDb,
   89334          sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
   89335       sqlite3VdbeAddOp1(v, OP_Expire, 0);
   89336     }
   89337   }
   89338 
   89339   /* When adding an index to the list of indices for a table, make
   89340   ** sure all indices labeled OE_Replace come after all those labeled
   89341   ** OE_Ignore.  This is necessary for the correct constraint check
   89342   ** processing (in sqlite3GenerateConstraintChecks()) as part of
   89343   ** UPDATE and INSERT statements.
   89344   */
   89345   if( db->init.busy || pTblName==0 ){
   89346     if( onError!=OE_Replace || pTab->pIndex==0
   89347          || pTab->pIndex->onError==OE_Replace){
   89348       pIndex->pNext = pTab->pIndex;
   89349       pTab->pIndex = pIndex;
   89350     }else{
   89351       Index *pOther = pTab->pIndex;
   89352       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
   89353         pOther = pOther->pNext;
   89354       }
   89355       pIndex->pNext = pOther->pNext;
   89356       pOther->pNext = pIndex;
   89357     }
   89358     pRet = pIndex;
   89359     pIndex = 0;
   89360   }
   89361 
   89362   /* Clean up before exiting */
   89363 exit_create_index:
   89364   if( pIndex ) freeIndex(db, pIndex);
   89365   sqlite3ExprDelete(db, pPIWhere);
   89366   sqlite3ExprListDelete(db, pList);
   89367   sqlite3SrcListDelete(db, pTblName);
   89368   sqlite3DbFree(db, zName);
   89369   return pRet;
   89370 }
   89371 
   89372 /*
   89373 ** Fill the Index.aiRowEst[] array with default information - information
   89374 ** to be used when we have not run the ANALYZE command.
   89375 **
   89376 ** aiRowEst[0] is suppose to contain the number of elements in the index.
   89377 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
   89378 ** number of rows in the table that match any particular value of the
   89379 ** first column of the index.  aiRowEst[2] is an estimate of the number
   89380 ** of rows that match any particular combination of the first 2 columns
   89381 ** of the index.  And so forth.  It must always be the case that
   89382 *
   89383 **           aiRowEst[N]<=aiRowEst[N-1]
   89384 **           aiRowEst[N]>=1
   89385 **
   89386 ** Apart from that, we have little to go on besides intuition as to
   89387 ** how aiRowEst[] should be initialized.  The numbers generated here
   89388 ** are based on typical values found in actual indices.
   89389 */
   89390 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
   89391   /*                10,  9,  8,  7,  6 */
   89392   LogEst aVal[] = { 33, 32, 30, 28, 26 };
   89393   LogEst *a = pIdx->aiRowLogEst;
   89394   int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
   89395   int i;
   89396 
   89397   /* Set the first entry (number of rows in the index) to the estimated
   89398   ** number of rows in the table. Or 10, if the estimated number of rows
   89399   ** in the table is less than that.  */
   89400   a[0] = pIdx->pTable->nRowLogEst;
   89401   if( a[0]<33 ) a[0] = 33;        assert( 33==sqlite3LogEst(10) );
   89402 
   89403   /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
   89404   ** 6 and each subsequent value (if any) is 5.  */
   89405   memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
   89406   for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
   89407     a[i] = 23;                    assert( 23==sqlite3LogEst(5) );
   89408   }
   89409 
   89410   assert( 0==sqlite3LogEst(1) );
   89411   if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
   89412 }
   89413 
   89414 /*
   89415 ** This routine will drop an existing named index.  This routine
   89416 ** implements the DROP INDEX statement.
   89417 */
   89418 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
   89419   Index *pIndex;
   89420   Vdbe *v;
   89421   sqlite3 *db = pParse->db;
   89422   int iDb;
   89423 
   89424   assert( pParse->nErr==0 );   /* Never called with prior errors */
   89425   if( db->mallocFailed ){
   89426     goto exit_drop_index;
   89427   }
   89428   assert( pName->nSrc==1 );
   89429   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   89430     goto exit_drop_index;
   89431   }
   89432   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
   89433   if( pIndex==0 ){
   89434     if( !ifExists ){
   89435       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
   89436     }else{
   89437       sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
   89438     }
   89439     pParse->checkSchema = 1;
   89440     goto exit_drop_index;
   89441   }
   89442   if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
   89443     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
   89444       "or PRIMARY KEY constraint cannot be dropped", 0);
   89445     goto exit_drop_index;
   89446   }
   89447   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
   89448 #ifndef SQLITE_OMIT_AUTHORIZATION
   89449   {
   89450     int code = SQLITE_DROP_INDEX;
   89451     Table *pTab = pIndex->pTable;
   89452     const char *zDb = db->aDb[iDb].zName;
   89453     const char *zTab = SCHEMA_TABLE(iDb);
   89454     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
   89455       goto exit_drop_index;
   89456     }
   89457     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
   89458     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
   89459       goto exit_drop_index;
   89460     }
   89461   }
   89462 #endif
   89463 
   89464   /* Generate code to remove the index and from the master table */
   89465   v = sqlite3GetVdbe(pParse);
   89466   if( v ){
   89467     sqlite3BeginWriteOperation(pParse, 1, iDb);
   89468     sqlite3NestedParse(pParse,
   89469        "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
   89470        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
   89471     );
   89472     sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
   89473     sqlite3ChangeCookie(pParse, iDb);
   89474     destroyRootPage(pParse, pIndex->tnum, iDb);
   89475     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
   89476   }
   89477 
   89478 exit_drop_index:
   89479   sqlite3SrcListDelete(db, pName);
   89480 }
   89481 
   89482 /*
   89483 ** pArray is a pointer to an array of objects. Each object in the
   89484 ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
   89485 ** to extend the array so that there is space for a new object at the end.
   89486 **
   89487 ** When this function is called, *pnEntry contains the current size of
   89488 ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
   89489 ** in total).
   89490 **
   89491 ** If the realloc() is successful (i.e. if no OOM condition occurs), the
   89492 ** space allocated for the new object is zeroed, *pnEntry updated to
   89493 ** reflect the new size of the array and a pointer to the new allocation
   89494 ** returned. *pIdx is set to the index of the new array entry in this case.
   89495 **
   89496 ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
   89497 ** unchanged and a copy of pArray returned.
   89498 */
   89499 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
   89500   sqlite3 *db,      /* Connection to notify of malloc failures */
   89501   void *pArray,     /* Array of objects.  Might be reallocated */
   89502   int szEntry,      /* Size of each object in the array */
   89503   int *pnEntry,     /* Number of objects currently in use */
   89504   int *pIdx         /* Write the index of a new slot here */
   89505 ){
   89506   char *z;
   89507   int n = *pnEntry;
   89508   if( (n & (n-1))==0 ){
   89509     int sz = (n==0) ? 1 : 2*n;
   89510     void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
   89511     if( pNew==0 ){
   89512       *pIdx = -1;
   89513       return pArray;
   89514     }
   89515     pArray = pNew;
   89516   }
   89517   z = (char*)pArray;
   89518   memset(&z[n * szEntry], 0, szEntry);
   89519   *pIdx = n;
   89520   ++*pnEntry;
   89521   return pArray;
   89522 }
   89523 
   89524 /*
   89525 ** Append a new element to the given IdList.  Create a new IdList if
   89526 ** need be.
   89527 **
   89528 ** A new IdList is returned, or NULL if malloc() fails.
   89529 */
   89530 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
   89531   int i;
   89532   if( pList==0 ){
   89533     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
   89534     if( pList==0 ) return 0;
   89535   }
   89536   pList->a = sqlite3ArrayAllocate(
   89537       db,
   89538       pList->a,
   89539       sizeof(pList->a[0]),
   89540       &pList->nId,
   89541       &i
   89542   );
   89543   if( i<0 ){
   89544     sqlite3IdListDelete(db, pList);
   89545     return 0;
   89546   }
   89547   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
   89548   return pList;
   89549 }
   89550 
   89551 /*
   89552 ** Delete an IdList.
   89553 */
   89554 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
   89555   int i;
   89556   if( pList==0 ) return;
   89557   for(i=0; i<pList->nId; i++){
   89558     sqlite3DbFree(db, pList->a[i].zName);
   89559   }
   89560   sqlite3DbFree(db, pList->a);
   89561   sqlite3DbFree(db, pList);
   89562 }
   89563 
   89564 /*
   89565 ** Return the index in pList of the identifier named zId.  Return -1
   89566 ** if not found.
   89567 */
   89568 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
   89569   int i;
   89570   if( pList==0 ) return -1;
   89571   for(i=0; i<pList->nId; i++){
   89572     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
   89573   }
   89574   return -1;
   89575 }
   89576 
   89577 /*
   89578 ** Expand the space allocated for the given SrcList object by
   89579 ** creating nExtra new slots beginning at iStart.  iStart is zero based.
   89580 ** New slots are zeroed.
   89581 **
   89582 ** For example, suppose a SrcList initially contains two entries: A,B.
   89583 ** To append 3 new entries onto the end, do this:
   89584 **
   89585 **    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
   89586 **
   89587 ** After the call above it would contain:  A, B, nil, nil, nil.
   89588 ** If the iStart argument had been 1 instead of 2, then the result
   89589 ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
   89590 ** the iStart value would be 0.  The result then would
   89591 ** be: nil, nil, nil, A, B.
   89592 **
   89593 ** If a memory allocation fails the SrcList is unchanged.  The
   89594 ** db->mallocFailed flag will be set to true.
   89595 */
   89596 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
   89597   sqlite3 *db,       /* Database connection to notify of OOM errors */
   89598   SrcList *pSrc,     /* The SrcList to be enlarged */
   89599   int nExtra,        /* Number of new slots to add to pSrc->a[] */
   89600   int iStart         /* Index in pSrc->a[] of first new slot */
   89601 ){
   89602   int i;
   89603 
   89604   /* Sanity checking on calling parameters */
   89605   assert( iStart>=0 );
   89606   assert( nExtra>=1 );
   89607   assert( pSrc!=0 );
   89608   assert( iStart<=pSrc->nSrc );
   89609 
   89610   /* Allocate additional space if needed */
   89611   if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
   89612     SrcList *pNew;
   89613     int nAlloc = pSrc->nSrc+nExtra;
   89614     int nGot;
   89615     pNew = sqlite3DbRealloc(db, pSrc,
   89616                sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
   89617     if( pNew==0 ){
   89618       assert( db->mallocFailed );
   89619       return pSrc;
   89620     }
   89621     pSrc = pNew;
   89622     nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
   89623     pSrc->nAlloc = nGot;
   89624   }
   89625 
   89626   /* Move existing slots that come after the newly inserted slots
   89627   ** out of the way */
   89628   for(i=pSrc->nSrc-1; i>=iStart; i--){
   89629     pSrc->a[i+nExtra] = pSrc->a[i];
   89630   }
   89631   pSrc->nSrc += nExtra;
   89632 
   89633   /* Zero the newly allocated slots */
   89634   memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
   89635   for(i=iStart; i<iStart+nExtra; i++){
   89636     pSrc->a[i].iCursor = -1;
   89637   }
   89638 
   89639   /* Return a pointer to the enlarged SrcList */
   89640   return pSrc;
   89641 }
   89642 
   89643 
   89644 /*
   89645 ** Append a new table name to the given SrcList.  Create a new SrcList if
   89646 ** need be.  A new entry is created in the SrcList even if pTable is NULL.
   89647 **
   89648 ** A SrcList is returned, or NULL if there is an OOM error.  The returned
   89649 ** SrcList might be the same as the SrcList that was input or it might be
   89650 ** a new one.  If an OOM error does occurs, then the prior value of pList
   89651 ** that is input to this routine is automatically freed.
   89652 **
   89653 ** If pDatabase is not null, it means that the table has an optional
   89654 ** database name prefix.  Like this:  "database.table".  The pDatabase
   89655 ** points to the table name and the pTable points to the database name.
   89656 ** The SrcList.a[].zName field is filled with the table name which might
   89657 ** come from pTable (if pDatabase is NULL) or from pDatabase.
   89658 ** SrcList.a[].zDatabase is filled with the database name from pTable,
   89659 ** or with NULL if no database is specified.
   89660 **
   89661 ** In other words, if call like this:
   89662 **
   89663 **         sqlite3SrcListAppend(D,A,B,0);
   89664 **
   89665 ** Then B is a table name and the database name is unspecified.  If called
   89666 ** like this:
   89667 **
   89668 **         sqlite3SrcListAppend(D,A,B,C);
   89669 **
   89670 ** Then C is the table name and B is the database name.  If C is defined
   89671 ** then so is B.  In other words, we never have a case where:
   89672 **
   89673 **         sqlite3SrcListAppend(D,A,0,C);
   89674 **
   89675 ** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
   89676 ** before being added to the SrcList.
   89677 */
   89678 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
   89679   sqlite3 *db,        /* Connection to notify of malloc failures */
   89680   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
   89681   Token *pTable,      /* Table to append */
   89682   Token *pDatabase    /* Database of the table */
   89683 ){
   89684   struct SrcList_item *pItem;
   89685   assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
   89686   if( pList==0 ){
   89687     pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
   89688     if( pList==0 ) return 0;
   89689     pList->nAlloc = 1;
   89690   }
   89691   pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
   89692   if( db->mallocFailed ){
   89693     sqlite3SrcListDelete(db, pList);
   89694     return 0;
   89695   }
   89696   pItem = &pList->a[pList->nSrc-1];
   89697   if( pDatabase && pDatabase->z==0 ){
   89698     pDatabase = 0;
   89699   }
   89700   if( pDatabase ){
   89701     Token *pTemp = pDatabase;
   89702     pDatabase = pTable;
   89703     pTable = pTemp;
   89704   }
   89705   pItem->zName = sqlite3NameFromToken(db, pTable);
   89706   pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
   89707   return pList;
   89708 }
   89709 
   89710 /*
   89711 ** Assign VdbeCursor index numbers to all tables in a SrcList
   89712 */
   89713 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
   89714   int i;
   89715   struct SrcList_item *pItem;
   89716   assert(pList || pParse->db->mallocFailed );
   89717   if( pList ){
   89718     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
   89719       if( pItem->iCursor>=0 ) break;
   89720       pItem->iCursor = pParse->nTab++;
   89721       if( pItem->pSelect ){
   89722         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
   89723       }
   89724     }
   89725   }
   89726 }
   89727 
   89728 /*
   89729 ** Delete an entire SrcList including all its substructure.
   89730 */
   89731 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
   89732   int i;
   89733   struct SrcList_item *pItem;
   89734   if( pList==0 ) return;
   89735   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
   89736     sqlite3DbFree(db, pItem->zDatabase);
   89737     sqlite3DbFree(db, pItem->zName);
   89738     sqlite3DbFree(db, pItem->zAlias);
   89739     sqlite3DbFree(db, pItem->zIndex);
   89740     sqlite3DeleteTable(db, pItem->pTab);
   89741     sqlite3SelectDelete(db, pItem->pSelect);
   89742     sqlite3ExprDelete(db, pItem->pOn);
   89743     sqlite3IdListDelete(db, pItem->pUsing);
   89744   }
   89745   sqlite3DbFree(db, pList);
   89746 }
   89747 
   89748 /*
   89749 ** This routine is called by the parser to add a new term to the
   89750 ** end of a growing FROM clause.  The "p" parameter is the part of
   89751 ** the FROM clause that has already been constructed.  "p" is NULL
   89752 ** if this is the first term of the FROM clause.  pTable and pDatabase
   89753 ** are the name of the table and database named in the FROM clause term.
   89754 ** pDatabase is NULL if the database name qualifier is missing - the
   89755 ** usual case.  If the term has a alias, then pAlias points to the
   89756 ** alias token.  If the term is a subquery, then pSubquery is the
   89757 ** SELECT statement that the subquery encodes.  The pTable and
   89758 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
   89759 ** parameters are the content of the ON and USING clauses.
   89760 **
   89761 ** Return a new SrcList which encodes is the FROM with the new
   89762 ** term added.
   89763 */
   89764 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
   89765   Parse *pParse,          /* Parsing context */
   89766   SrcList *p,             /* The left part of the FROM clause already seen */
   89767   Token *pTable,          /* Name of the table to add to the FROM clause */
   89768   Token *pDatabase,       /* Name of the database containing pTable */
   89769   Token *pAlias,          /* The right-hand side of the AS subexpression */
   89770   Select *pSubquery,      /* A subquery used in place of a table name */
   89771   Expr *pOn,              /* The ON clause of a join */
   89772   IdList *pUsing          /* The USING clause of a join */
   89773 ){
   89774   struct SrcList_item *pItem;
   89775   sqlite3 *db = pParse->db;
   89776   if( !p && (pOn || pUsing) ){
   89777     sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
   89778       (pOn ? "ON" : "USING")
   89779     );
   89780     goto append_from_error;
   89781   }
   89782   p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
   89783   if( p==0 || NEVER(p->nSrc==0) ){
   89784     goto append_from_error;
   89785   }
   89786   pItem = &p->a[p->nSrc-1];
   89787   assert( pAlias!=0 );
   89788   if( pAlias->n ){
   89789     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
   89790   }
   89791   pItem->pSelect = pSubquery;
   89792   pItem->pOn = pOn;
   89793   pItem->pUsing = pUsing;
   89794   return p;
   89795 
   89796  append_from_error:
   89797   assert( p==0 );
   89798   sqlite3ExprDelete(db, pOn);
   89799   sqlite3IdListDelete(db, pUsing);
   89800   sqlite3SelectDelete(db, pSubquery);
   89801   return 0;
   89802 }
   89803 
   89804 /*
   89805 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
   89806 ** element of the source-list passed as the second argument.
   89807 */
   89808 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
   89809   assert( pIndexedBy!=0 );
   89810   if( p && ALWAYS(p->nSrc>0) ){
   89811     struct SrcList_item *pItem = &p->a[p->nSrc-1];
   89812     assert( pItem->notIndexed==0 && pItem->zIndex==0 );
   89813     if( pIndexedBy->n==1 && !pIndexedBy->z ){
   89814       /* A "NOT INDEXED" clause was supplied. See parse.y
   89815       ** construct "indexed_opt" for details. */
   89816       pItem->notIndexed = 1;
   89817     }else{
   89818       pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
   89819     }
   89820   }
   89821 }
   89822 
   89823 /*
   89824 ** When building up a FROM clause in the parser, the join operator
   89825 ** is initially attached to the left operand.  But the code generator
   89826 ** expects the join operator to be on the right operand.  This routine
   89827 ** Shifts all join operators from left to right for an entire FROM
   89828 ** clause.
   89829 **
   89830 ** Example: Suppose the join is like this:
   89831 **
   89832 **           A natural cross join B
   89833 **
   89834 ** The operator is "natural cross join".  The A and B operands are stored
   89835 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
   89836 ** operator with A.  This routine shifts that operator over to B.
   89837 */
   89838 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
   89839   if( p ){
   89840     int i;
   89841     assert( p->a || p->nSrc==0 );
   89842     for(i=p->nSrc-1; i>0; i--){
   89843       p->a[i].jointype = p->a[i-1].jointype;
   89844     }
   89845     p->a[0].jointype = 0;
   89846   }
   89847 }
   89848 
   89849 /*
   89850 ** Begin a transaction
   89851 */
   89852 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
   89853   sqlite3 *db;
   89854   Vdbe *v;
   89855   int i;
   89856 
   89857   assert( pParse!=0 );
   89858   db = pParse->db;
   89859   assert( db!=0 );
   89860 /*  if( db->aDb[0].pBt==0 ) return; */
   89861   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
   89862     return;
   89863   }
   89864   v = sqlite3GetVdbe(pParse);
   89865   if( !v ) return;
   89866   if( type!=TK_DEFERRED ){
   89867     for(i=0; i<db->nDb; i++){
   89868       sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
   89869       sqlite3VdbeUsesBtree(v, i);
   89870     }
   89871   }
   89872   sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
   89873 }
   89874 
   89875 /*
   89876 ** Commit a transaction
   89877 */
   89878 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
   89879   Vdbe *v;
   89880 
   89881   assert( pParse!=0 );
   89882   assert( pParse->db!=0 );
   89883   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
   89884     return;
   89885   }
   89886   v = sqlite3GetVdbe(pParse);
   89887   if( v ){
   89888     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
   89889   }
   89890 }
   89891 
   89892 /*
   89893 ** Rollback a transaction
   89894 */
   89895 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
   89896   Vdbe *v;
   89897 
   89898   assert( pParse!=0 );
   89899   assert( pParse->db!=0 );
   89900   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
   89901     return;
   89902   }
   89903   v = sqlite3GetVdbe(pParse);
   89904   if( v ){
   89905     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
   89906   }
   89907 }
   89908 
   89909 /*
   89910 ** This function is called by the parser when it parses a command to create,
   89911 ** release or rollback an SQL savepoint.
   89912 */
   89913 SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
   89914   char *zName = sqlite3NameFromToken(pParse->db, pName);
   89915   if( zName ){
   89916     Vdbe *v = sqlite3GetVdbe(pParse);
   89917 #ifndef SQLITE_OMIT_AUTHORIZATION
   89918     static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
   89919     assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
   89920 #endif
   89921     if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
   89922       sqlite3DbFree(pParse->db, zName);
   89923       return;
   89924     }
   89925     sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
   89926   }
   89927 }
   89928 
   89929 /*
   89930 ** Make sure the TEMP database is open and available for use.  Return
   89931 ** the number of errors.  Leave any error messages in the pParse structure.
   89932 */
   89933 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
   89934   sqlite3 *db = pParse->db;
   89935   if( db->aDb[1].pBt==0 && !pParse->explain ){
   89936     int rc;
   89937     Btree *pBt;
   89938     static const int flags =
   89939           SQLITE_OPEN_READWRITE |
   89940           SQLITE_OPEN_CREATE |
   89941           SQLITE_OPEN_EXCLUSIVE |
   89942           SQLITE_OPEN_DELETEONCLOSE |
   89943           SQLITE_OPEN_TEMP_DB;
   89944 
   89945     rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
   89946     if( rc!=SQLITE_OK ){
   89947       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
   89948         "file for storing temporary tables");
   89949       pParse->rc = rc;
   89950       return 1;
   89951     }
   89952     db->aDb[1].pBt = pBt;
   89953     assert( db->aDb[1].pSchema );
   89954     if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
   89955       db->mallocFailed = 1;
   89956       return 1;
   89957     }
   89958   }
   89959   return 0;
   89960 }
   89961 
   89962 /*
   89963 ** Record the fact that the schema cookie will need to be verified
   89964 ** for database iDb.  The code to actually verify the schema cookie
   89965 ** will occur at the end of the top-level VDBE and will be generated
   89966 ** later, by sqlite3FinishCoding().
   89967 */
   89968 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
   89969   Parse *pToplevel = sqlite3ParseToplevel(pParse);
   89970   sqlite3 *db = pToplevel->db;
   89971 
   89972   assert( iDb>=0 && iDb<db->nDb );
   89973   assert( db->aDb[iDb].pBt!=0 || iDb==1 );
   89974   assert( iDb<SQLITE_MAX_ATTACHED+2 );
   89975   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   89976   if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
   89977     DbMaskSet(pToplevel->cookieMask, iDb);
   89978     pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
   89979     if( !OMIT_TEMPDB && iDb==1 ){
   89980       sqlite3OpenTempDatabase(pToplevel);
   89981     }
   89982   }
   89983 }
   89984 
   89985 /*
   89986 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
   89987 ** attached database. Otherwise, invoke it for the database named zDb only.
   89988 */
   89989 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
   89990   sqlite3 *db = pParse->db;
   89991   int i;
   89992   for(i=0; i<db->nDb; i++){
   89993     Db *pDb = &db->aDb[i];
   89994     if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
   89995       sqlite3CodeVerifySchema(pParse, i);
   89996     }
   89997   }
   89998 }
   89999 
   90000 /*
   90001 ** Generate VDBE code that prepares for doing an operation that
   90002 ** might change the database.
   90003 **
   90004 ** This routine starts a new transaction if we are not already within
   90005 ** a transaction.  If we are already within a transaction, then a checkpoint
   90006 ** is set if the setStatement parameter is true.  A checkpoint should
   90007 ** be set for operations that might fail (due to a constraint) part of
   90008 ** the way through and which will need to undo some writes without having to
   90009 ** rollback the whole transaction.  For operations where all constraints
   90010 ** can be checked before any changes are made to the database, it is never
   90011 ** necessary to undo a write and the checkpoint should not be set.
   90012 */
   90013 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
   90014   Parse *pToplevel = sqlite3ParseToplevel(pParse);
   90015   sqlite3CodeVerifySchema(pParse, iDb);
   90016   DbMaskSet(pToplevel->writeMask, iDb);
   90017   pToplevel->isMultiWrite |= setStatement;
   90018 }
   90019 
   90020 /*
   90021 ** Indicate that the statement currently under construction might write
   90022 ** more than one entry (example: deleting one row then inserting another,
   90023 ** inserting multiple rows in a table, or inserting a row and index entries.)
   90024 ** If an abort occurs after some of these writes have completed, then it will
   90025 ** be necessary to undo the completed writes.
   90026 */
   90027 SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
   90028   Parse *pToplevel = sqlite3ParseToplevel(pParse);
   90029   pToplevel->isMultiWrite = 1;
   90030 }
   90031 
   90032 /*
   90033 ** The code generator calls this routine if is discovers that it is
   90034 ** possible to abort a statement prior to completion.  In order to
   90035 ** perform this abort without corrupting the database, we need to make
   90036 ** sure that the statement is protected by a statement transaction.
   90037 **
   90038 ** Technically, we only need to set the mayAbort flag if the
   90039 ** isMultiWrite flag was previously set.  There is a time dependency
   90040 ** such that the abort must occur after the multiwrite.  This makes
   90041 ** some statements involving the REPLACE conflict resolution algorithm
   90042 ** go a little faster.  But taking advantage of this time dependency
   90043 ** makes it more difficult to prove that the code is correct (in
   90044 ** particular, it prevents us from writing an effective
   90045 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
   90046 ** to take the safe route and skip the optimization.
   90047 */
   90048 SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
   90049   Parse *pToplevel = sqlite3ParseToplevel(pParse);
   90050   pToplevel->mayAbort = 1;
   90051 }
   90052 
   90053 /*
   90054 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
   90055 ** error. The onError parameter determines which (if any) of the statement
   90056 ** and/or current transaction is rolled back.
   90057 */
   90058 SQLITE_PRIVATE void sqlite3HaltConstraint(
   90059   Parse *pParse,    /* Parsing context */
   90060   int errCode,      /* extended error code */
   90061   int onError,      /* Constraint type */
   90062   char *p4,         /* Error message */
   90063   i8 p4type,        /* P4_STATIC or P4_TRANSIENT */
   90064   u8 p5Errmsg       /* P5_ErrMsg type */
   90065 ){
   90066   Vdbe *v = sqlite3GetVdbe(pParse);
   90067   assert( (errCode&0xff)==SQLITE_CONSTRAINT );
   90068   if( onError==OE_Abort ){
   90069     sqlite3MayAbort(pParse);
   90070   }
   90071   sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
   90072   if( p5Errmsg ) sqlite3VdbeChangeP5(v, p5Errmsg);
   90073 }
   90074 
   90075 /*
   90076 ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
   90077 */
   90078 SQLITE_PRIVATE void sqlite3UniqueConstraint(
   90079   Parse *pParse,    /* Parsing context */
   90080   int onError,      /* Constraint type */
   90081   Index *pIdx       /* The index that triggers the constraint */
   90082 ){
   90083   char *zErr;
   90084   int j;
   90085   StrAccum errMsg;
   90086   Table *pTab = pIdx->pTable;
   90087 
   90088   sqlite3StrAccumInit(&errMsg, 0, 0, 200);
   90089   errMsg.db = pParse->db;
   90090   for(j=0; j<pIdx->nKeyCol; j++){
   90091     char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
   90092     if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
   90093     sqlite3StrAccumAppendAll(&errMsg, pTab->zName);
   90094     sqlite3StrAccumAppend(&errMsg, ".", 1);
   90095     sqlite3StrAccumAppendAll(&errMsg, zCol);
   90096   }
   90097   zErr = sqlite3StrAccumFinish(&errMsg);
   90098   sqlite3HaltConstraint(pParse,
   90099     IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
   90100                             : SQLITE_CONSTRAINT_UNIQUE,
   90101     onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
   90102 }
   90103 
   90104 
   90105 /*
   90106 ** Code an OP_Halt due to non-unique rowid.
   90107 */
   90108 SQLITE_PRIVATE void sqlite3RowidConstraint(
   90109   Parse *pParse,    /* Parsing context */
   90110   int onError,      /* Conflict resolution algorithm */
   90111   Table *pTab       /* The table with the non-unique rowid */
   90112 ){
   90113   char *zMsg;
   90114   int rc;
   90115   if( pTab->iPKey>=0 ){
   90116     zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
   90117                           pTab->aCol[pTab->iPKey].zName);
   90118     rc = SQLITE_CONSTRAINT_PRIMARYKEY;
   90119   }else{
   90120     zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
   90121     rc = SQLITE_CONSTRAINT_ROWID;
   90122   }
   90123   sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
   90124                         P5_ConstraintUnique);
   90125 }
   90126 
   90127 /*
   90128 ** Check to see if pIndex uses the collating sequence pColl.  Return
   90129 ** true if it does and false if it does not.
   90130 */
   90131 #ifndef SQLITE_OMIT_REINDEX
   90132 static int collationMatch(const char *zColl, Index *pIndex){
   90133   int i;
   90134   assert( zColl!=0 );
   90135   for(i=0; i<pIndex->nColumn; i++){
   90136     const char *z = pIndex->azColl[i];
   90137     assert( z!=0 || pIndex->aiColumn[i]<0 );
   90138     if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
   90139       return 1;
   90140     }
   90141   }
   90142   return 0;
   90143 }
   90144 #endif
   90145 
   90146 /*
   90147 ** Recompute all indices of pTab that use the collating sequence pColl.
   90148 ** If pColl==0 then recompute all indices of pTab.
   90149 */
   90150 #ifndef SQLITE_OMIT_REINDEX
   90151 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
   90152   Index *pIndex;              /* An index associated with pTab */
   90153 
   90154   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
   90155     if( zColl==0 || collationMatch(zColl, pIndex) ){
   90156       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   90157       sqlite3BeginWriteOperation(pParse, 0, iDb);
   90158       sqlite3RefillIndex(pParse, pIndex, -1);
   90159     }
   90160   }
   90161 }
   90162 #endif
   90163 
   90164 /*
   90165 ** Recompute all indices of all tables in all databases where the
   90166 ** indices use the collating sequence pColl.  If pColl==0 then recompute
   90167 ** all indices everywhere.
   90168 */
   90169 #ifndef SQLITE_OMIT_REINDEX
   90170 static void reindexDatabases(Parse *pParse, char const *zColl){
   90171   Db *pDb;                    /* A single database */
   90172   int iDb;                    /* The database index number */
   90173   sqlite3 *db = pParse->db;   /* The database connection */
   90174   HashElem *k;                /* For looping over tables in pDb */
   90175   Table *pTab;                /* A table in the database */
   90176 
   90177   assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
   90178   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
   90179     assert( pDb!=0 );
   90180     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
   90181       pTab = (Table*)sqliteHashData(k);
   90182       reindexTable(pParse, pTab, zColl);
   90183     }
   90184   }
   90185 }
   90186 #endif
   90187 
   90188 /*
   90189 ** Generate code for the REINDEX command.
   90190 **
   90191 **        REINDEX                            -- 1
   90192 **        REINDEX  <collation>               -- 2
   90193 **        REINDEX  ?<database>.?<tablename>  -- 3
   90194 **        REINDEX  ?<database>.?<indexname>  -- 4
   90195 **
   90196 ** Form 1 causes all indices in all attached databases to be rebuilt.
   90197 ** Form 2 rebuilds all indices in all databases that use the named
   90198 ** collating function.  Forms 3 and 4 rebuild the named index or all
   90199 ** indices associated with the named table.
   90200 */
   90201 #ifndef SQLITE_OMIT_REINDEX
   90202 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
   90203   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
   90204   char *z;                    /* Name of a table or index */
   90205   const char *zDb;            /* Name of the database */
   90206   Table *pTab;                /* A table in the database */
   90207   Index *pIndex;              /* An index associated with pTab */
   90208   int iDb;                    /* The database index number */
   90209   sqlite3 *db = pParse->db;   /* The database connection */
   90210   Token *pObjName;            /* Name of the table or index to be reindexed */
   90211 
   90212   /* Read the database schema. If an error occurs, leave an error message
   90213   ** and code in pParse and return NULL. */
   90214   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   90215     return;
   90216   }
   90217 
   90218   if( pName1==0 ){
   90219     reindexDatabases(pParse, 0);
   90220     return;
   90221   }else if( NEVER(pName2==0) || pName2->z==0 ){
   90222     char *zColl;
   90223     assert( pName1->z );
   90224     zColl = sqlite3NameFromToken(pParse->db, pName1);
   90225     if( !zColl ) return;
   90226     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
   90227     if( pColl ){
   90228       reindexDatabases(pParse, zColl);
   90229       sqlite3DbFree(db, zColl);
   90230       return;
   90231     }
   90232     sqlite3DbFree(db, zColl);
   90233   }
   90234   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
   90235   if( iDb<0 ) return;
   90236   z = sqlite3NameFromToken(db, pObjName);
   90237   if( z==0 ) return;
   90238   zDb = db->aDb[iDb].zName;
   90239   pTab = sqlite3FindTable(db, z, zDb);
   90240   if( pTab ){
   90241     reindexTable(pParse, pTab, 0);
   90242     sqlite3DbFree(db, z);
   90243     return;
   90244   }
   90245   pIndex = sqlite3FindIndex(db, z, zDb);
   90246   sqlite3DbFree(db, z);
   90247   if( pIndex ){
   90248     sqlite3BeginWriteOperation(pParse, 0, iDb);
   90249     sqlite3RefillIndex(pParse, pIndex, -1);
   90250     return;
   90251   }
   90252   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
   90253 }
   90254 #endif
   90255 
   90256 /*
   90257 ** Return a KeyInfo structure that is appropriate for the given Index.
   90258 **
   90259 ** The KeyInfo structure for an index is cached in the Index object.
   90260 ** So there might be multiple references to the returned pointer.  The
   90261 ** caller should not try to modify the KeyInfo object.
   90262 **
   90263 ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
   90264 ** when it has finished using it.
   90265 */
   90266 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
   90267   if( pParse->nErr ) return 0;
   90268 #ifndef SQLITE_OMIT_SHARED_CACHE
   90269   if( pIdx->pKeyInfo && pIdx->pKeyInfo->db!=pParse->db ){
   90270     sqlite3KeyInfoUnref(pIdx->pKeyInfo);
   90271     pIdx->pKeyInfo = 0;
   90272   }
   90273 #endif
   90274   if( pIdx->pKeyInfo==0 ){
   90275     int i;
   90276     int nCol = pIdx->nColumn;
   90277     int nKey = pIdx->nKeyCol;
   90278     KeyInfo *pKey;
   90279     if( pIdx->uniqNotNull ){
   90280       pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
   90281     }else{
   90282       pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
   90283     }
   90284     if( pKey ){
   90285       assert( sqlite3KeyInfoIsWriteable(pKey) );
   90286       for(i=0; i<nCol; i++){
   90287         char *zColl = pIdx->azColl[i];
   90288         assert( zColl!=0 );
   90289         pKey->aColl[i] = strcmp(zColl,"BINARY")==0 ? 0 :
   90290                           sqlite3LocateCollSeq(pParse, zColl);
   90291         pKey->aSortOrder[i] = pIdx->aSortOrder[i];
   90292       }
   90293       if( pParse->nErr ){
   90294         sqlite3KeyInfoUnref(pKey);
   90295       }else{
   90296         pIdx->pKeyInfo = pKey;
   90297       }
   90298     }
   90299   }
   90300   return sqlite3KeyInfoRef(pIdx->pKeyInfo);
   90301 }
   90302 
   90303 #ifndef SQLITE_OMIT_CTE
   90304 /*
   90305 ** This routine is invoked once per CTE by the parser while parsing a
   90306 ** WITH clause.
   90307 */
   90308 SQLITE_PRIVATE With *sqlite3WithAdd(
   90309   Parse *pParse,          /* Parsing context */
   90310   With *pWith,            /* Existing WITH clause, or NULL */
   90311   Token *pName,           /* Name of the common-table */
   90312   ExprList *pArglist,     /* Optional column name list for the table */
   90313   Select *pQuery          /* Query used to initialize the table */
   90314 ){
   90315   sqlite3 *db = pParse->db;
   90316   With *pNew;
   90317   char *zName;
   90318 
   90319   /* Check that the CTE name is unique within this WITH clause. If
   90320   ** not, store an error in the Parse structure. */
   90321   zName = sqlite3NameFromToken(pParse->db, pName);
   90322   if( zName && pWith ){
   90323     int i;
   90324     for(i=0; i<pWith->nCte; i++){
   90325       if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
   90326         sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
   90327       }
   90328     }
   90329   }
   90330 
   90331   if( pWith ){
   90332     int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
   90333     pNew = sqlite3DbRealloc(db, pWith, nByte);
   90334   }else{
   90335     pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
   90336   }
   90337   assert( zName!=0 || pNew==0 );
   90338   assert( db->mallocFailed==0 || pNew==0 );
   90339 
   90340   if( pNew==0 ){
   90341     sqlite3ExprListDelete(db, pArglist);
   90342     sqlite3SelectDelete(db, pQuery);
   90343     sqlite3DbFree(db, zName);
   90344     pNew = pWith;
   90345   }else{
   90346     pNew->a[pNew->nCte].pSelect = pQuery;
   90347     pNew->a[pNew->nCte].pCols = pArglist;
   90348     pNew->a[pNew->nCte].zName = zName;
   90349     pNew->a[pNew->nCte].zErr = 0;
   90350     pNew->nCte++;
   90351   }
   90352 
   90353   return pNew;
   90354 }
   90355 
   90356 /*
   90357 ** Free the contents of the With object passed as the second argument.
   90358 */
   90359 SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){
   90360   if( pWith ){
   90361     int i;
   90362     for(i=0; i<pWith->nCte; i++){
   90363       struct Cte *pCte = &pWith->a[i];
   90364       sqlite3ExprListDelete(db, pCte->pCols);
   90365       sqlite3SelectDelete(db, pCte->pSelect);
   90366       sqlite3DbFree(db, pCte->zName);
   90367     }
   90368     sqlite3DbFree(db, pWith);
   90369   }
   90370 }
   90371 #endif /* !defined(SQLITE_OMIT_CTE) */
   90372 
   90373 /************** End of build.c ***********************************************/
   90374 /************** Begin file callback.c ****************************************/
   90375 /*
   90376 ** 2005 May 23
   90377 **
   90378 ** The author disclaims copyright to this source code.  In place of
   90379 ** a legal notice, here is a blessing:
   90380 **
   90381 **    May you do good and not evil.
   90382 **    May you find forgiveness for yourself and forgive others.
   90383 **    May you share freely, never taking more than you give.
   90384 **
   90385 *************************************************************************
   90386 **
   90387 ** This file contains functions used to access the internal hash tables
   90388 ** of user defined functions and collation sequences.
   90389 */
   90390 
   90391 
   90392 /*
   90393 ** Invoke the 'collation needed' callback to request a collation sequence
   90394 ** in the encoding enc of name zName, length nName.
   90395 */
   90396 static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
   90397   assert( !db->xCollNeeded || !db->xCollNeeded16 );
   90398   if( db->xCollNeeded ){
   90399     char *zExternal = sqlite3DbStrDup(db, zName);
   90400     if( !zExternal ) return;
   90401     db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
   90402     sqlite3DbFree(db, zExternal);
   90403   }
   90404 #ifndef SQLITE_OMIT_UTF16
   90405   if( db->xCollNeeded16 ){
   90406     char const *zExternal;
   90407     sqlite3_value *pTmp = sqlite3ValueNew(db);
   90408     sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
   90409     zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
   90410     if( zExternal ){
   90411       db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
   90412     }
   90413     sqlite3ValueFree(pTmp);
   90414   }
   90415 #endif
   90416 }
   90417 
   90418 /*
   90419 ** This routine is called if the collation factory fails to deliver a
   90420 ** collation function in the best encoding but there may be other versions
   90421 ** of this collation function (for other text encodings) available. Use one
   90422 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
   90423 ** possible.
   90424 */
   90425 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
   90426   CollSeq *pColl2;
   90427   char *z = pColl->zName;
   90428   int i;
   90429   static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
   90430   for(i=0; i<3; i++){
   90431     pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
   90432     if( pColl2->xCmp!=0 ){
   90433       memcpy(pColl, pColl2, sizeof(CollSeq));
   90434       pColl->xDel = 0;         /* Do not copy the destructor */
   90435       return SQLITE_OK;
   90436     }
   90437   }
   90438   return SQLITE_ERROR;
   90439 }
   90440 
   90441 /*
   90442 ** This function is responsible for invoking the collation factory callback
   90443 ** or substituting a collation sequence of a different encoding when the
   90444 ** requested collation sequence is not available in the desired encoding.
   90445 **
   90446 ** If it is not NULL, then pColl must point to the database native encoding
   90447 ** collation sequence with name zName, length nName.
   90448 **
   90449 ** The return value is either the collation sequence to be used in database
   90450 ** db for collation type name zName, length nName, or NULL, if no collation
   90451 ** sequence can be found.  If no collation is found, leave an error message.
   90452 **
   90453 ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
   90454 */
   90455 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
   90456   Parse *pParse,        /* Parsing context */
   90457   u8 enc,               /* The desired encoding for the collating sequence */
   90458   CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
   90459   const char *zName     /* Collating sequence name */
   90460 ){
   90461   CollSeq *p;
   90462   sqlite3 *db = pParse->db;
   90463 
   90464   p = pColl;
   90465   if( !p ){
   90466     p = sqlite3FindCollSeq(db, enc, zName, 0);
   90467   }
   90468   if( !p || !p->xCmp ){
   90469     /* No collation sequence of this type for this encoding is registered.
   90470     ** Call the collation factory to see if it can supply us with one.
   90471     */
   90472     callCollNeeded(db, enc, zName);
   90473     p = sqlite3FindCollSeq(db, enc, zName, 0);
   90474   }
   90475   if( p && !p->xCmp && synthCollSeq(db, p) ){
   90476     p = 0;
   90477   }
   90478   assert( !p || p->xCmp );
   90479   if( p==0 ){
   90480     sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
   90481   }
   90482   return p;
   90483 }
   90484 
   90485 /*
   90486 ** This routine is called on a collation sequence before it is used to
   90487 ** check that it is defined. An undefined collation sequence exists when
   90488 ** a database is loaded that contains references to collation sequences
   90489 ** that have not been defined by sqlite3_create_collation() etc.
   90490 **
   90491 ** If required, this routine calls the 'collation needed' callback to
   90492 ** request a definition of the collating sequence. If this doesn't work,
   90493 ** an equivalent collating sequence that uses a text encoding different
   90494 ** from the main database is substituted, if one is available.
   90495 */
   90496 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
   90497   if( pColl ){
   90498     const char *zName = pColl->zName;
   90499     sqlite3 *db = pParse->db;
   90500     CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
   90501     if( !p ){
   90502       return SQLITE_ERROR;
   90503     }
   90504     assert( p==pColl );
   90505   }
   90506   return SQLITE_OK;
   90507 }
   90508 
   90509 
   90510 
   90511 /*
   90512 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
   90513 ** specified by zName and nName is not found and parameter 'create' is
   90514 ** true, then create a new entry. Otherwise return NULL.
   90515 **
   90516 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
   90517 ** array of three CollSeq structures. The first is the collation sequence
   90518 ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
   90519 **
   90520 ** Stored immediately after the three collation sequences is a copy of
   90521 ** the collation sequence name. A pointer to this string is stored in
   90522 ** each collation sequence structure.
   90523 */
   90524 static CollSeq *findCollSeqEntry(
   90525   sqlite3 *db,          /* Database connection */
   90526   const char *zName,    /* Name of the collating sequence */
   90527   int create            /* Create a new entry if true */
   90528 ){
   90529   CollSeq *pColl;
   90530   int nName = sqlite3Strlen30(zName);
   90531   pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
   90532 
   90533   if( 0==pColl && create ){
   90534     pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
   90535     if( pColl ){
   90536       CollSeq *pDel = 0;
   90537       pColl[0].zName = (char*)&pColl[3];
   90538       pColl[0].enc = SQLITE_UTF8;
   90539       pColl[1].zName = (char*)&pColl[3];
   90540       pColl[1].enc = SQLITE_UTF16LE;
   90541       pColl[2].zName = (char*)&pColl[3];
   90542       pColl[2].enc = SQLITE_UTF16BE;
   90543       memcpy(pColl[0].zName, zName, nName);
   90544       pColl[0].zName[nName] = 0;
   90545       pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
   90546 
   90547       /* If a malloc() failure occurred in sqlite3HashInsert(), it will
   90548       ** return the pColl pointer to be deleted (because it wasn't added
   90549       ** to the hash table).
   90550       */
   90551       assert( pDel==0 || pDel==pColl );
   90552       if( pDel!=0 ){
   90553         db->mallocFailed = 1;
   90554         sqlite3DbFree(db, pDel);
   90555         pColl = 0;
   90556       }
   90557     }
   90558   }
   90559   return pColl;
   90560 }
   90561 
   90562 /*
   90563 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
   90564 ** Return the CollSeq* pointer for the collation sequence named zName
   90565 ** for the encoding 'enc' from the database 'db'.
   90566 **
   90567 ** If the entry specified is not found and 'create' is true, then create a
   90568 ** new entry.  Otherwise return NULL.
   90569 **
   90570 ** A separate function sqlite3LocateCollSeq() is a wrapper around
   90571 ** this routine.  sqlite3LocateCollSeq() invokes the collation factory
   90572 ** if necessary and generates an error message if the collating sequence
   90573 ** cannot be found.
   90574 **
   90575 ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
   90576 */
   90577 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
   90578   sqlite3 *db,
   90579   u8 enc,
   90580   const char *zName,
   90581   int create
   90582 ){
   90583   CollSeq *pColl;
   90584   if( zName ){
   90585     pColl = findCollSeqEntry(db, zName, create);
   90586   }else{
   90587     pColl = db->pDfltColl;
   90588   }
   90589   assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
   90590   assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
   90591   if( pColl ) pColl += enc-1;
   90592   return pColl;
   90593 }
   90594 
   90595 /* During the search for the best function definition, this procedure
   90596 ** is called to test how well the function passed as the first argument
   90597 ** matches the request for a function with nArg arguments in a system
   90598 ** that uses encoding enc. The value returned indicates how well the
   90599 ** request is matched. A higher value indicates a better match.
   90600 **
   90601 ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
   90602 ** is also -1.  In other words, we are searching for a function that
   90603 ** takes a variable number of arguments.
   90604 **
   90605 ** If nArg is -2 that means that we are searching for any function
   90606 ** regardless of the number of arguments it uses, so return a positive
   90607 ** match score for any
   90608 **
   90609 ** The returned value is always between 0 and 6, as follows:
   90610 **
   90611 ** 0: Not a match.
   90612 ** 1: UTF8/16 conversion required and function takes any number of arguments.
   90613 ** 2: UTF16 byte order change required and function takes any number of args.
   90614 ** 3: encoding matches and function takes any number of arguments
   90615 ** 4: UTF8/16 conversion required - argument count matches exactly
   90616 ** 5: UTF16 byte order conversion required - argument count matches exactly
   90617 ** 6: Perfect match:  encoding and argument count match exactly.
   90618 **
   90619 ** If nArg==(-2) then any function with a non-null xStep or xFunc is
   90620 ** a perfect match and any function with both xStep and xFunc NULL is
   90621 ** a non-match.
   90622 */
   90623 #define FUNC_PERFECT_MATCH 6  /* The score for a perfect match */
   90624 static int matchQuality(
   90625   FuncDef *p,     /* The function we are evaluating for match quality */
   90626   int nArg,       /* Desired number of arguments.  (-1)==any */
   90627   u8 enc          /* Desired text encoding */
   90628 ){
   90629   int match;
   90630 
   90631   /* nArg of -2 is a special case */
   90632   if( nArg==(-2) ) return (p->xFunc==0 && p->xStep==0) ? 0 : FUNC_PERFECT_MATCH;
   90633 
   90634   /* Wrong number of arguments means "no match" */
   90635   if( p->nArg!=nArg && p->nArg>=0 ) return 0;
   90636 
   90637   /* Give a better score to a function with a specific number of arguments
   90638   ** than to function that accepts any number of arguments. */
   90639   if( p->nArg==nArg ){
   90640     match = 4;
   90641   }else{
   90642     match = 1;
   90643   }
   90644 
   90645   /* Bonus points if the text encoding matches */
   90646   if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
   90647     match += 2;  /* Exact encoding match */
   90648   }else if( (enc & p->funcFlags & 2)!=0 ){
   90649     match += 1;  /* Both are UTF16, but with different byte orders */
   90650   }
   90651 
   90652   return match;
   90653 }
   90654 
   90655 /*
   90656 ** Search a FuncDefHash for a function with the given name.  Return
   90657 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
   90658 */
   90659 static FuncDef *functionSearch(
   90660   FuncDefHash *pHash,  /* Hash table to search */
   90661   int h,               /* Hash of the name */
   90662   const char *zFunc,   /* Name of function */
   90663   int nFunc            /* Number of bytes in zFunc */
   90664 ){
   90665   FuncDef *p;
   90666   for(p=pHash->a[h]; p; p=p->pHash){
   90667     if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
   90668       return p;
   90669     }
   90670   }
   90671   return 0;
   90672 }
   90673 
   90674 /*
   90675 ** Insert a new FuncDef into a FuncDefHash hash table.
   90676 */
   90677 SQLITE_PRIVATE void sqlite3FuncDefInsert(
   90678   FuncDefHash *pHash,  /* The hash table into which to insert */
   90679   FuncDef *pDef        /* The function definition to insert */
   90680 ){
   90681   FuncDef *pOther;
   90682   int nName = sqlite3Strlen30(pDef->zName);
   90683   u8 c1 = (u8)pDef->zName[0];
   90684   int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
   90685   pOther = functionSearch(pHash, h, pDef->zName, nName);
   90686   if( pOther ){
   90687     assert( pOther!=pDef && pOther->pNext!=pDef );
   90688     pDef->pNext = pOther->pNext;
   90689     pOther->pNext = pDef;
   90690   }else{
   90691     pDef->pNext = 0;
   90692     pDef->pHash = pHash->a[h];
   90693     pHash->a[h] = pDef;
   90694   }
   90695 }
   90696 
   90697 
   90698 
   90699 /*
   90700 ** Locate a user function given a name, a number of arguments and a flag
   90701 ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
   90702 ** pointer to the FuncDef structure that defines that function, or return
   90703 ** NULL if the function does not exist.
   90704 **
   90705 ** If the createFlag argument is true, then a new (blank) FuncDef
   90706 ** structure is created and liked into the "db" structure if a
   90707 ** no matching function previously existed.
   90708 **
   90709 ** If nArg is -2, then the first valid function found is returned.  A
   90710 ** function is valid if either xFunc or xStep is non-zero.  The nArg==(-2)
   90711 ** case is used to see if zName is a valid function name for some number
   90712 ** of arguments.  If nArg is -2, then createFlag must be 0.
   90713 **
   90714 ** If createFlag is false, then a function with the required name and
   90715 ** number of arguments may be returned even if the eTextRep flag does not
   90716 ** match that requested.
   90717 */
   90718 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
   90719   sqlite3 *db,       /* An open database */
   90720   const char *zName, /* Name of the function.  Not null-terminated */
   90721   int nName,         /* Number of characters in the name */
   90722   int nArg,          /* Number of arguments.  -1 means any number */
   90723   u8 enc,            /* Preferred text encoding */
   90724   u8 createFlag      /* Create new entry if true and does not otherwise exist */
   90725 ){
   90726   FuncDef *p;         /* Iterator variable */
   90727   FuncDef *pBest = 0; /* Best match found so far */
   90728   int bestScore = 0;  /* Score of best match */
   90729   int h;              /* Hash value */
   90730 
   90731   assert( nArg>=(-2) );
   90732   assert( nArg>=(-1) || createFlag==0 );
   90733   h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
   90734 
   90735   /* First search for a match amongst the application-defined functions.
   90736   */
   90737   p = functionSearch(&db->aFunc, h, zName, nName);
   90738   while( p ){
   90739     int score = matchQuality(p, nArg, enc);
   90740     if( score>bestScore ){
   90741       pBest = p;
   90742       bestScore = score;
   90743     }
   90744     p = p->pNext;
   90745   }
   90746 
   90747   /* If no match is found, search the built-in functions.
   90748   **
   90749   ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
   90750   ** functions even if a prior app-defined function was found.  And give
   90751   ** priority to built-in functions.
   90752   **
   90753   ** Except, if createFlag is true, that means that we are trying to
   90754   ** install a new function.  Whatever FuncDef structure is returned it will
   90755   ** have fields overwritten with new information appropriate for the
   90756   ** new function.  But the FuncDefs for built-in functions are read-only.
   90757   ** So we must not search for built-ins when creating a new function.
   90758   */
   90759   if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
   90760     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
   90761     bestScore = 0;
   90762     p = functionSearch(pHash, h, zName, nName);
   90763     while( p ){
   90764       int score = matchQuality(p, nArg, enc);
   90765       if( score>bestScore ){
   90766         pBest = p;
   90767         bestScore = score;
   90768       }
   90769       p = p->pNext;
   90770     }
   90771   }
   90772 
   90773   /* If the createFlag parameter is true and the search did not reveal an
   90774   ** exact match for the name, number of arguments and encoding, then add a
   90775   ** new entry to the hash table and return it.
   90776   */
   90777   if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
   90778       (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
   90779     pBest->zName = (char *)&pBest[1];
   90780     pBest->nArg = (u16)nArg;
   90781     pBest->funcFlags = enc;
   90782     memcpy(pBest->zName, zName, nName);
   90783     pBest->zName[nName] = 0;
   90784     sqlite3FuncDefInsert(&db->aFunc, pBest);
   90785   }
   90786 
   90787   if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
   90788     return pBest;
   90789   }
   90790   return 0;
   90791 }
   90792 
   90793 /*
   90794 ** Free all resources held by the schema structure. The void* argument points
   90795 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
   90796 ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
   90797 ** of the schema hash tables).
   90798 **
   90799 ** The Schema.cache_size variable is not cleared.
   90800 */
   90801 SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
   90802   Hash temp1;
   90803   Hash temp2;
   90804   HashElem *pElem;
   90805   Schema *pSchema = (Schema *)p;
   90806 
   90807   temp1 = pSchema->tblHash;
   90808   temp2 = pSchema->trigHash;
   90809   sqlite3HashInit(&pSchema->trigHash);
   90810   sqlite3HashClear(&pSchema->idxHash);
   90811   for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
   90812     sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
   90813   }
   90814   sqlite3HashClear(&temp2);
   90815   sqlite3HashInit(&pSchema->tblHash);
   90816   for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
   90817     Table *pTab = sqliteHashData(pElem);
   90818     sqlite3DeleteTable(0, pTab);
   90819   }
   90820   sqlite3HashClear(&temp1);
   90821   sqlite3HashClear(&pSchema->fkeyHash);
   90822   pSchema->pSeqTab = 0;
   90823   if( pSchema->schemaFlags & DB_SchemaLoaded ){
   90824     pSchema->iGeneration++;
   90825     pSchema->schemaFlags &= ~DB_SchemaLoaded;
   90826   }
   90827 }
   90828 
   90829 /*
   90830 ** Find and return the schema associated with a BTree.  Create
   90831 ** a new one if necessary.
   90832 */
   90833 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
   90834   Schema * p;
   90835   if( pBt ){
   90836     p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
   90837   }else{
   90838     p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
   90839   }
   90840   if( !p ){
   90841     db->mallocFailed = 1;
   90842   }else if ( 0==p->file_format ){
   90843     sqlite3HashInit(&p->tblHash);
   90844     sqlite3HashInit(&p->idxHash);
   90845     sqlite3HashInit(&p->trigHash);
   90846     sqlite3HashInit(&p->fkeyHash);
   90847     p->enc = SQLITE_UTF8;
   90848   }
   90849   return p;
   90850 }
   90851 
   90852 /************** End of callback.c ********************************************/
   90853 /************** Begin file delete.c ******************************************/
   90854 /*
   90855 ** 2001 September 15
   90856 **
   90857 ** The author disclaims copyright to this source code.  In place of
   90858 ** a legal notice, here is a blessing:
   90859 **
   90860 **    May you do good and not evil.
   90861 **    May you find forgiveness for yourself and forgive others.
   90862 **    May you share freely, never taking more than you give.
   90863 **
   90864 *************************************************************************
   90865 ** This file contains C code routines that are called by the parser
   90866 ** in order to generate code for DELETE FROM statements.
   90867 */
   90868 
   90869 /*
   90870 ** While a SrcList can in general represent multiple tables and subqueries
   90871 ** (as in the FROM clause of a SELECT statement) in this case it contains
   90872 ** the name of a single table, as one might find in an INSERT, DELETE,
   90873 ** or UPDATE statement.  Look up that table in the symbol table and
   90874 ** return a pointer.  Set an error message and return NULL if the table
   90875 ** name is not found or if any other error occurs.
   90876 **
   90877 ** The following fields are initialized appropriate in pSrc:
   90878 **
   90879 **    pSrc->a[0].pTab       Pointer to the Table object
   90880 **    pSrc->a[0].pIndex     Pointer to the INDEXED BY index, if there is one
   90881 **
   90882 */
   90883 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
   90884   struct SrcList_item *pItem = pSrc->a;
   90885   Table *pTab;
   90886   assert( pItem && pSrc->nSrc==1 );
   90887   pTab = sqlite3LocateTableItem(pParse, 0, pItem);
   90888   sqlite3DeleteTable(pParse->db, pItem->pTab);
   90889   pItem->pTab = pTab;
   90890   if( pTab ){
   90891     pTab->nRef++;
   90892   }
   90893   if( sqlite3IndexedByLookup(pParse, pItem) ){
   90894     pTab = 0;
   90895   }
   90896   return pTab;
   90897 }
   90898 
   90899 /*
   90900 ** Check to make sure the given table is writable.  If it is not
   90901 ** writable, generate an error message and return 1.  If it is
   90902 ** writable return 0;
   90903 */
   90904 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
   90905   /* A table is not writable under the following circumstances:
   90906   **
   90907   **   1) It is a virtual table and no implementation of the xUpdate method
   90908   **      has been provided, or
   90909   **   2) It is a system table (i.e. sqlite_master), this call is not
   90910   **      part of a nested parse and writable_schema pragma has not
   90911   **      been specified.
   90912   **
   90913   ** In either case leave an error message in pParse and return non-zero.
   90914   */
   90915   if( ( IsVirtual(pTab)
   90916      && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
   90917    || ( (pTab->tabFlags & TF_Readonly)!=0
   90918      && (pParse->db->flags & SQLITE_WriteSchema)==0
   90919      && pParse->nested==0 )
   90920   ){
   90921     sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
   90922     return 1;
   90923   }
   90924 
   90925 #ifndef SQLITE_OMIT_VIEW
   90926   if( !viewOk && pTab->pSelect ){
   90927     sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
   90928     return 1;
   90929   }
   90930 #endif
   90931   return 0;
   90932 }
   90933 
   90934 
   90935 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
   90936 /*
   90937 ** Evaluate a view and store its result in an ephemeral table.  The
   90938 ** pWhere argument is an optional WHERE clause that restricts the
   90939 ** set of rows in the view that are to be added to the ephemeral table.
   90940 */
   90941 SQLITE_PRIVATE void sqlite3MaterializeView(
   90942   Parse *pParse,       /* Parsing context */
   90943   Table *pView,        /* View definition */
   90944   Expr *pWhere,        /* Optional WHERE clause to be added */
   90945   int iCur             /* Cursor number for ephemerial table */
   90946 ){
   90947   SelectDest dest;
   90948   Select *pSel;
   90949   SrcList *pFrom;
   90950   sqlite3 *db = pParse->db;
   90951   int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
   90952   pWhere = sqlite3ExprDup(db, pWhere, 0);
   90953   pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
   90954   if( pFrom ){
   90955     assert( pFrom->nSrc==1 );
   90956     pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
   90957     pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
   90958     assert( pFrom->a[0].pOn==0 );
   90959     assert( pFrom->a[0].pUsing==0 );
   90960   }
   90961   pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
   90962   sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
   90963   sqlite3Select(pParse, pSel, &dest);
   90964   sqlite3SelectDelete(db, pSel);
   90965 }
   90966 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
   90967 
   90968 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
   90969 /*
   90970 ** Generate an expression tree to implement the WHERE, ORDER BY,
   90971 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
   90972 **
   90973 **     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
   90974 **                            \__________________________/
   90975 **                               pLimitWhere (pInClause)
   90976 */
   90977 SQLITE_PRIVATE Expr *sqlite3LimitWhere(
   90978   Parse *pParse,               /* The parser context */
   90979   SrcList *pSrc,               /* the FROM clause -- which tables to scan */
   90980   Expr *pWhere,                /* The WHERE clause.  May be null */
   90981   ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
   90982   Expr *pLimit,                /* The LIMIT clause.  May be null */
   90983   Expr *pOffset,               /* The OFFSET clause.  May be null */
   90984   char *zStmtType              /* Either DELETE or UPDATE.  For err msgs. */
   90985 ){
   90986   Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
   90987   Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
   90988   Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
   90989   ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
   90990   SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
   90991   Select *pSelect = NULL;      /* Complete SELECT tree */
   90992 
   90993   /* Check that there isn't an ORDER BY without a LIMIT clause.
   90994   */
   90995   if( pOrderBy && (pLimit == 0) ) {
   90996     sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
   90997     goto limit_where_cleanup_2;
   90998   }
   90999 
   91000   /* We only need to generate a select expression if there
   91001   ** is a limit/offset term to enforce.
   91002   */
   91003   if( pLimit == 0 ) {
   91004     /* if pLimit is null, pOffset will always be null as well. */
   91005     assert( pOffset == 0 );
   91006     return pWhere;
   91007   }
   91008 
   91009   /* Generate a select expression tree to enforce the limit/offset
   91010   ** term for the DELETE or UPDATE statement.  For example:
   91011   **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
   91012   ** becomes:
   91013   **   DELETE FROM table_a WHERE rowid IN (
   91014   **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
   91015   **   );
   91016   */
   91017 
   91018   pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
   91019   if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
   91020   pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
   91021   if( pEList == 0 ) goto limit_where_cleanup_2;
   91022 
   91023   /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
   91024   ** and the SELECT subtree. */
   91025   pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
   91026   if( pSelectSrc == 0 ) {
   91027     sqlite3ExprListDelete(pParse->db, pEList);
   91028     goto limit_where_cleanup_2;
   91029   }
   91030 
   91031   /* generate the SELECT expression tree. */
   91032   pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
   91033                              pOrderBy,0,pLimit,pOffset);
   91034   if( pSelect == 0 ) return 0;
   91035 
   91036   /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
   91037   pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
   91038   if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
   91039   pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
   91040   if( pInClause == 0 ) goto limit_where_cleanup_1;
   91041 
   91042   pInClause->x.pSelect = pSelect;
   91043   pInClause->flags |= EP_xIsSelect;
   91044   sqlite3ExprSetHeight(pParse, pInClause);
   91045   return pInClause;
   91046 
   91047   /* something went wrong. clean up anything allocated. */
   91048 limit_where_cleanup_1:
   91049   sqlite3SelectDelete(pParse->db, pSelect);
   91050   return 0;
   91051 
   91052 limit_where_cleanup_2:
   91053   sqlite3ExprDelete(pParse->db, pWhere);
   91054   sqlite3ExprListDelete(pParse->db, pOrderBy);
   91055   sqlite3ExprDelete(pParse->db, pLimit);
   91056   sqlite3ExprDelete(pParse->db, pOffset);
   91057   return 0;
   91058 }
   91059 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
   91060        /*      && !defined(SQLITE_OMIT_SUBQUERY) */
   91061 
   91062 /*
   91063 ** Generate code for a DELETE FROM statement.
   91064 **
   91065 **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
   91066 **                 \________/       \________________/
   91067 **                  pTabList              pWhere
   91068 */
   91069 SQLITE_PRIVATE void sqlite3DeleteFrom(
   91070   Parse *pParse,         /* The parser context */
   91071   SrcList *pTabList,     /* The table from which we should delete things */
   91072   Expr *pWhere           /* The WHERE clause.  May be null */
   91073 ){
   91074   Vdbe *v;               /* The virtual database engine */
   91075   Table *pTab;           /* The table from which records will be deleted */
   91076   const char *zDb;       /* Name of database holding pTab */
   91077   int i;                 /* Loop counter */
   91078   WhereInfo *pWInfo;     /* Information about the WHERE clause */
   91079   Index *pIdx;           /* For looping over indices of the table */
   91080   int iTabCur;           /* Cursor number for the table */
   91081   int iDataCur;          /* VDBE cursor for the canonical data source */
   91082   int iIdxCur;           /* Cursor number of the first index */
   91083   int nIdx;              /* Number of indices */
   91084   sqlite3 *db;           /* Main database structure */
   91085   AuthContext sContext;  /* Authorization context */
   91086   NameContext sNC;       /* Name context to resolve expressions in */
   91087   int iDb;               /* Database number */
   91088   int memCnt = -1;       /* Memory cell used for change counting */
   91089   int rcauth;            /* Value returned by authorization callback */
   91090   int okOnePass;         /* True for one-pass algorithm without the FIFO */
   91091   int aiCurOnePass[2];   /* The write cursors opened by WHERE_ONEPASS */
   91092   u8 *aToOpen = 0;       /* Open cursor iTabCur+j if aToOpen[j] is true */
   91093   Index *pPk;            /* The PRIMARY KEY index on the table */
   91094   int iPk = 0;           /* First of nPk registers holding PRIMARY KEY value */
   91095   i16 nPk = 1;           /* Number of columns in the PRIMARY KEY */
   91096   int iKey;              /* Memory cell holding key of row to be deleted */
   91097   i16 nKey;              /* Number of memory cells in the row key */
   91098   int iEphCur = 0;       /* Ephemeral table holding all primary key values */
   91099   int iRowSet = 0;       /* Register for rowset of rows to delete */
   91100   int addrBypass = 0;    /* Address of jump over the delete logic */
   91101   int addrLoop = 0;      /* Top of the delete loop */
   91102   int addrDelete = 0;    /* Jump directly to the delete logic */
   91103   int addrEphOpen = 0;   /* Instruction to open the Ephermeral table */
   91104 
   91105 #ifndef SQLITE_OMIT_TRIGGER
   91106   int isView;                  /* True if attempting to delete from a view */
   91107   Trigger *pTrigger;           /* List of table triggers, if required */
   91108 #endif
   91109 
   91110   memset(&sContext, 0, sizeof(sContext));
   91111   db = pParse->db;
   91112   if( pParse->nErr || db->mallocFailed ){
   91113     goto delete_from_cleanup;
   91114   }
   91115   assert( pTabList->nSrc==1 );
   91116 
   91117   /* Locate the table which we want to delete.  This table has to be
   91118   ** put in an SrcList structure because some of the subroutines we
   91119   ** will be calling are designed to work with multiple tables and expect
   91120   ** an SrcList* parameter instead of just a Table* parameter.
   91121   */
   91122   pTab = sqlite3SrcListLookup(pParse, pTabList);
   91123   if( pTab==0 )  goto delete_from_cleanup;
   91124 
   91125   /* Figure out if we have any triggers and if the table being
   91126   ** deleted from is a view
   91127   */
   91128 #ifndef SQLITE_OMIT_TRIGGER
   91129   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
   91130   isView = pTab->pSelect!=0;
   91131 #else
   91132 # define pTrigger 0
   91133 # define isView 0
   91134 #endif
   91135 #ifdef SQLITE_OMIT_VIEW
   91136 # undef isView
   91137 # define isView 0
   91138 #endif
   91139 
   91140   /* If pTab is really a view, make sure it has been initialized.
   91141   */
   91142   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
   91143     goto delete_from_cleanup;
   91144   }
   91145 
   91146   if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
   91147     goto delete_from_cleanup;
   91148   }
   91149   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   91150   assert( iDb<db->nDb );
   91151   zDb = db->aDb[iDb].zName;
   91152   rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
   91153   assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
   91154   if( rcauth==SQLITE_DENY ){
   91155     goto delete_from_cleanup;
   91156   }
   91157   assert(!isView || pTrigger);
   91158 
   91159   /* Assign cursor numbers to the table and all its indices.
   91160   */
   91161   assert( pTabList->nSrc==1 );
   91162   iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
   91163   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
   91164     pParse->nTab++;
   91165   }
   91166 
   91167   /* Start the view context
   91168   */
   91169   if( isView ){
   91170     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
   91171   }
   91172 
   91173   /* Begin generating code.
   91174   */
   91175   v = sqlite3GetVdbe(pParse);
   91176   if( v==0 ){
   91177     goto delete_from_cleanup;
   91178   }
   91179   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
   91180   sqlite3BeginWriteOperation(pParse, 1, iDb);
   91181 
   91182   /* If we are trying to delete from a view, realize that view into
   91183   ** a ephemeral table.
   91184   */
   91185 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
   91186   if( isView ){
   91187     sqlite3MaterializeView(pParse, pTab, pWhere, iTabCur);
   91188     iDataCur = iIdxCur = iTabCur;
   91189   }
   91190 #endif
   91191 
   91192   /* Resolve the column names in the WHERE clause.
   91193   */
   91194   memset(&sNC, 0, sizeof(sNC));
   91195   sNC.pParse = pParse;
   91196   sNC.pSrcList = pTabList;
   91197   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
   91198     goto delete_from_cleanup;
   91199   }
   91200 
   91201   /* Initialize the counter of the number of rows deleted, if
   91202   ** we are counting rows.
   91203   */
   91204   if( db->flags & SQLITE_CountRows ){
   91205     memCnt = ++pParse->nMem;
   91206     sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
   91207   }
   91208 
   91209 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
   91210   /* Special case: A DELETE without a WHERE clause deletes everything.
   91211   ** It is easier just to erase the whole table. Prior to version 3.6.5,
   91212   ** this optimization caused the row change count (the value returned by
   91213   ** API function sqlite3_count_changes) to be set incorrectly.  */
   91214   if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab)
   91215    && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
   91216   ){
   91217     assert( !isView );
   91218     sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
   91219     if( HasRowid(pTab) ){
   91220       sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
   91221                         pTab->zName, P4_STATIC);
   91222     }
   91223     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   91224       assert( pIdx->pSchema==pTab->pSchema );
   91225       sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
   91226     }
   91227   }else
   91228 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
   91229   {
   91230     if( HasRowid(pTab) ){
   91231       /* For a rowid table, initialize the RowSet to an empty set */
   91232       pPk = 0;
   91233       nPk = 1;
   91234       iRowSet = ++pParse->nMem;
   91235       sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
   91236     }else{
   91237       /* For a WITHOUT ROWID table, create an ephermeral table used to
   91238       ** hold all primary keys for rows to be deleted. */
   91239       pPk = sqlite3PrimaryKeyIndex(pTab);
   91240       assert( pPk!=0 );
   91241       nPk = pPk->nKeyCol;
   91242       iPk = pParse->nMem+1;
   91243       pParse->nMem += nPk;
   91244       iEphCur = pParse->nTab++;
   91245       addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
   91246       sqlite3VdbeSetP4KeyInfo(pParse, pPk);
   91247     }
   91248 
   91249     /* Construct a query to find the rowid or primary key for every row
   91250     ** to be deleted, based on the WHERE clause.
   91251     */
   91252     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0,
   91253                                WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK,
   91254                                iTabCur+1);
   91255     if( pWInfo==0 ) goto delete_from_cleanup;
   91256     okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
   91257 
   91258     /* Keep track of the number of rows to be deleted */
   91259     if( db->flags & SQLITE_CountRows ){
   91260       sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
   91261     }
   91262 
   91263     /* Extract the rowid or primary key for the current row */
   91264     if( pPk ){
   91265       for(i=0; i<nPk; i++){
   91266         sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
   91267                                         pPk->aiColumn[i], iPk+i);
   91268       }
   91269       iKey = iPk;
   91270     }else{
   91271       iKey = pParse->nMem + 1;
   91272       iKey = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iTabCur, iKey, 0);
   91273       if( iKey>pParse->nMem ) pParse->nMem = iKey;
   91274     }
   91275 
   91276     if( okOnePass ){
   91277       /* For ONEPASS, no need to store the rowid/primary-key.  There is only
   91278       ** one, so just keep it in its register(s) and fall through to the
   91279       ** delete code.
   91280       */
   91281       nKey = nPk; /* OP_Found will use an unpacked key */
   91282       aToOpen = sqlite3DbMallocRaw(db, nIdx+2);
   91283       if( aToOpen==0 ){
   91284         sqlite3WhereEnd(pWInfo);
   91285         goto delete_from_cleanup;
   91286       }
   91287       memset(aToOpen, 1, nIdx+1);
   91288       aToOpen[nIdx+1] = 0;
   91289       if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
   91290       if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
   91291       if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
   91292       addrDelete = sqlite3VdbeAddOp0(v, OP_Goto); /* Jump to DELETE logic */
   91293     }else if( pPk ){
   91294       /* Construct a composite key for the row to be deleted and remember it */
   91295       iKey = ++pParse->nMem;
   91296       nKey = 0;   /* Zero tells OP_Found to use a composite key */
   91297       sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
   91298                         sqlite3IndexAffinityStr(v, pPk), nPk);
   91299       sqlite3VdbeAddOp2(v, OP_IdxInsert, iEphCur, iKey);
   91300     }else{
   91301       /* Get the rowid of the row to be deleted and remember it in the RowSet */
   91302       nKey = 1;  /* OP_Seek always uses a single rowid */
   91303       sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
   91304     }
   91305 
   91306     /* End of the WHERE loop */
   91307     sqlite3WhereEnd(pWInfo);
   91308     if( okOnePass ){
   91309       /* Bypass the delete logic below if the WHERE loop found zero rows */
   91310       addrBypass = sqlite3VdbeMakeLabel(v);
   91311       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrBypass);
   91312       sqlite3VdbeJumpHere(v, addrDelete);
   91313     }
   91314 
   91315     /* Unless this is a view, open cursors for the table we are
   91316     ** deleting from and all its indices. If this is a view, then the
   91317     ** only effect this statement has is to fire the INSTEAD OF
   91318     ** triggers.
   91319     */
   91320     if( !isView ){
   91321       sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, iTabCur, aToOpen,
   91322                                  &iDataCur, &iIdxCur);
   91323       assert( pPk || iDataCur==iTabCur );
   91324       assert( pPk || iIdxCur==iDataCur+1 );
   91325     }
   91326 
   91327     /* Set up a loop over the rowids/primary-keys that were found in the
   91328     ** where-clause loop above.
   91329     */
   91330     if( okOnePass ){
   91331       /* Just one row.  Hence the top-of-loop is a no-op */
   91332       assert( nKey==nPk ); /* OP_Found will use an unpacked key */
   91333       if( aToOpen[iDataCur-iTabCur] ){
   91334         assert( pPk!=0 );
   91335         sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
   91336         VdbeCoverage(v);
   91337       }
   91338     }else if( pPk ){
   91339       addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
   91340       sqlite3VdbeAddOp2(v, OP_RowKey, iEphCur, iKey);
   91341       assert( nKey==0 );  /* OP_Found will use a composite key */
   91342     }else{
   91343       addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
   91344       VdbeCoverage(v);
   91345       assert( nKey==1 );
   91346     }
   91347 
   91348     /* Delete the row */
   91349 #ifndef SQLITE_OMIT_VIRTUALTABLE
   91350     if( IsVirtual(pTab) ){
   91351       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
   91352       sqlite3VtabMakeWritable(pParse, pTab);
   91353       sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
   91354       sqlite3VdbeChangeP5(v, OE_Abort);
   91355       sqlite3MayAbort(pParse);
   91356     }else
   91357 #endif
   91358     {
   91359       int count = (pParse->nested==0);    /* True to count changes */
   91360       sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
   91361                                iKey, nKey, count, OE_Default, okOnePass);
   91362     }
   91363 
   91364     /* End of the loop over all rowids/primary-keys. */
   91365     if( okOnePass ){
   91366       sqlite3VdbeResolveLabel(v, addrBypass);
   91367     }else if( pPk ){
   91368       sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
   91369       sqlite3VdbeJumpHere(v, addrLoop);
   91370     }else{
   91371       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrLoop);
   91372       sqlite3VdbeJumpHere(v, addrLoop);
   91373     }
   91374 
   91375     /* Close the cursors open on the table and its indexes. */
   91376     if( !isView && !IsVirtual(pTab) ){
   91377       if( !pPk ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
   91378       for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
   91379         sqlite3VdbeAddOp1(v, OP_Close, iIdxCur + i);
   91380       }
   91381     }
   91382   } /* End non-truncate path */
   91383 
   91384   /* Update the sqlite_sequence table by storing the content of the
   91385   ** maximum rowid counter values recorded while inserting into
   91386   ** autoincrement tables.
   91387   */
   91388   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
   91389     sqlite3AutoincrementEnd(pParse);
   91390   }
   91391 
   91392   /* Return the number of rows that were deleted. If this routine is
   91393   ** generating code because of a call to sqlite3NestedParse(), do not
   91394   ** invoke the callback function.
   91395   */
   91396   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
   91397     sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
   91398     sqlite3VdbeSetNumCols(v, 1);
   91399     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
   91400   }
   91401 
   91402 delete_from_cleanup:
   91403   sqlite3AuthContextPop(&sContext);
   91404   sqlite3SrcListDelete(db, pTabList);
   91405   sqlite3ExprDelete(db, pWhere);
   91406   sqlite3DbFree(db, aToOpen);
   91407   return;
   91408 }
   91409 /* Make sure "isView" and other macros defined above are undefined. Otherwise
   91410 ** thely may interfere with compilation of other functions in this file
   91411 ** (or in another file, if this file becomes part of the amalgamation).  */
   91412 #ifdef isView
   91413  #undef isView
   91414 #endif
   91415 #ifdef pTrigger
   91416  #undef pTrigger
   91417 #endif
   91418 
   91419 /*
   91420 ** This routine generates VDBE code that causes a single row of a
   91421 ** single table to be deleted.  Both the original table entry and
   91422 ** all indices are removed.
   91423 **
   91424 ** Preconditions:
   91425 **
   91426 **   1.  iDataCur is an open cursor on the btree that is the canonical data
   91427 **       store for the table.  (This will be either the table itself,
   91428 **       in the case of a rowid table, or the PRIMARY KEY index in the case
   91429 **       of a WITHOUT ROWID table.)
   91430 **
   91431 **   2.  Read/write cursors for all indices of pTab must be open as
   91432 **       cursor number iIdxCur+i for the i-th index.
   91433 **
   91434 **   3.  The primary key for the row to be deleted must be stored in a
   91435 **       sequence of nPk memory cells starting at iPk.  If nPk==0 that means
   91436 **       that a search record formed from OP_MakeRecord is contained in the
   91437 **       single memory location iPk.
   91438 */
   91439 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
   91440   Parse *pParse,     /* Parsing context */
   91441   Table *pTab,       /* Table containing the row to be deleted */
   91442   Trigger *pTrigger, /* List of triggers to (potentially) fire */
   91443   int iDataCur,      /* Cursor from which column data is extracted */
   91444   int iIdxCur,       /* First index cursor */
   91445   int iPk,           /* First memory cell containing the PRIMARY KEY */
   91446   i16 nPk,           /* Number of PRIMARY KEY memory cells */
   91447   u8 count,          /* If non-zero, increment the row change counter */
   91448   u8 onconf,         /* Default ON CONFLICT policy for triggers */
   91449   u8 bNoSeek         /* iDataCur is already pointing to the row to delete */
   91450 ){
   91451   Vdbe *v = pParse->pVdbe;        /* Vdbe */
   91452   int iOld = 0;                   /* First register in OLD.* array */
   91453   int iLabel;                     /* Label resolved to end of generated code */
   91454   u8 opSeek;                      /* Seek opcode */
   91455 
   91456   /* Vdbe is guaranteed to have been allocated by this stage. */
   91457   assert( v );
   91458   VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
   91459                          iDataCur, iIdxCur, iPk, (int)nPk));
   91460 
   91461   /* Seek cursor iCur to the row to delete. If this row no longer exists
   91462   ** (this can happen if a trigger program has already deleted it), do
   91463   ** not attempt to delete it or fire any DELETE triggers.  */
   91464   iLabel = sqlite3VdbeMakeLabel(v);
   91465   opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
   91466   if( !bNoSeek ){
   91467     sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
   91468     VdbeCoverageIf(v, opSeek==OP_NotExists);
   91469     VdbeCoverageIf(v, opSeek==OP_NotFound);
   91470   }
   91471 
   91472   /* If there are any triggers to fire, allocate a range of registers to
   91473   ** use for the old.* references in the triggers.  */
   91474   if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
   91475     u32 mask;                     /* Mask of OLD.* columns in use */
   91476     int iCol;                     /* Iterator used while populating OLD.* */
   91477     int addrStart;                /* Start of BEFORE trigger programs */
   91478 
   91479     /* TODO: Could use temporary registers here. Also could attempt to
   91480     ** avoid copying the contents of the rowid register.  */
   91481     mask = sqlite3TriggerColmask(
   91482         pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
   91483     );
   91484     mask |= sqlite3FkOldmask(pParse, pTab);
   91485     iOld = pParse->nMem+1;
   91486     pParse->nMem += (1 + pTab->nCol);
   91487 
   91488     /* Populate the OLD.* pseudo-table register array. These values will be
   91489     ** used by any BEFORE and AFTER triggers that exist.  */
   91490     sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
   91491     for(iCol=0; iCol<pTab->nCol; iCol++){
   91492       testcase( mask!=0xffffffff && iCol==31 );
   91493       testcase( mask!=0xffffffff && iCol==32 );
   91494       if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
   91495         sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1);
   91496       }
   91497     }
   91498 
   91499     /* Invoke BEFORE DELETE trigger programs. */
   91500     addrStart = sqlite3VdbeCurrentAddr(v);
   91501     sqlite3CodeRowTrigger(pParse, pTrigger,
   91502         TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
   91503     );
   91504 
   91505     /* If any BEFORE triggers were coded, then seek the cursor to the
   91506     ** row to be deleted again. It may be that the BEFORE triggers moved
   91507     ** the cursor or of already deleted the row that the cursor was
   91508     ** pointing to.
   91509     */
   91510     if( addrStart<sqlite3VdbeCurrentAddr(v) ){
   91511       sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
   91512       VdbeCoverageIf(v, opSeek==OP_NotExists);
   91513       VdbeCoverageIf(v, opSeek==OP_NotFound);
   91514     }
   91515 
   91516     /* Do FK processing. This call checks that any FK constraints that
   91517     ** refer to this table (i.e. constraints attached to other tables)
   91518     ** are not violated by deleting this row.  */
   91519     sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
   91520   }
   91521 
   91522   /* Delete the index and table entries. Skip this step if pTab is really
   91523   ** a view (in which case the only effect of the DELETE statement is to
   91524   ** fire the INSTEAD OF triggers).  */
   91525   if( pTab->pSelect==0 ){
   91526     sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, 0);
   91527     sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
   91528     if( count ){
   91529       sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
   91530     }
   91531   }
   91532 
   91533   /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
   91534   ** handle rows (possibly in other tables) that refer via a foreign key
   91535   ** to the row just deleted. */
   91536   sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
   91537 
   91538   /* Invoke AFTER DELETE trigger programs. */
   91539   sqlite3CodeRowTrigger(pParse, pTrigger,
   91540       TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
   91541   );
   91542 
   91543   /* Jump here if the row had already been deleted before any BEFORE
   91544   ** trigger programs were invoked. Or if a trigger program throws a
   91545   ** RAISE(IGNORE) exception.  */
   91546   sqlite3VdbeResolveLabel(v, iLabel);
   91547   VdbeModuleComment((v, "END: GenRowDel()"));
   91548 }
   91549 
   91550 /*
   91551 ** This routine generates VDBE code that causes the deletion of all
   91552 ** index entries associated with a single row of a single table, pTab
   91553 **
   91554 ** Preconditions:
   91555 **
   91556 **   1.  A read/write cursor "iDataCur" must be open on the canonical storage
   91557 **       btree for the table pTab.  (This will be either the table itself
   91558 **       for rowid tables or to the primary key index for WITHOUT ROWID
   91559 **       tables.)
   91560 **
   91561 **   2.  Read/write cursors for all indices of pTab must be open as
   91562 **       cursor number iIdxCur+i for the i-th index.  (The pTab->pIndex
   91563 **       index is the 0-th index.)
   91564 **
   91565 **   3.  The "iDataCur" cursor must be already be positioned on the row
   91566 **       that is to be deleted.
   91567 */
   91568 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
   91569   Parse *pParse,     /* Parsing and code generating context */
   91570   Table *pTab,       /* Table containing the row to be deleted */
   91571   int iDataCur,      /* Cursor of table holding data. */
   91572   int iIdxCur,       /* First index cursor */
   91573   int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
   91574 ){
   91575   int i;             /* Index loop counter */
   91576   int r1 = -1;       /* Register holding an index key */
   91577   int iPartIdxLabel; /* Jump destination for skipping partial index entries */
   91578   Index *pIdx;       /* Current index */
   91579   Index *pPrior = 0; /* Prior index */
   91580   Vdbe *v;           /* The prepared statement under construction */
   91581   Index *pPk;        /* PRIMARY KEY index, or NULL for rowid tables */
   91582 
   91583   v = pParse->pVdbe;
   91584   pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
   91585   for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
   91586     assert( iIdxCur+i!=iDataCur || pPk==pIdx );
   91587     if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
   91588     if( pIdx==pPk ) continue;
   91589     VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
   91590     r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
   91591                                  &iPartIdxLabel, pPrior, r1);
   91592     sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
   91593                       pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
   91594     sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
   91595     pPrior = pIdx;
   91596   }
   91597 }
   91598 
   91599 /*
   91600 ** Generate code that will assemble an index key and stores it in register
   91601 ** regOut.  The key with be for index pIdx which is an index on pTab.
   91602 ** iCur is the index of a cursor open on the pTab table and pointing to
   91603 ** the entry that needs indexing.  If pTab is a WITHOUT ROWID table, then
   91604 ** iCur must be the cursor of the PRIMARY KEY index.
   91605 **
   91606 ** Return a register number which is the first in a block of
   91607 ** registers that holds the elements of the index key.  The
   91608 ** block of registers has already been deallocated by the time
   91609 ** this routine returns.
   91610 **
   91611 ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
   91612 ** to that label if pIdx is a partial index that should be skipped.
   91613 ** The label should be resolved using sqlite3ResolvePartIdxLabel().
   91614 ** A partial index should be skipped if its WHERE clause evaluates
   91615 ** to false or null.  If pIdx is not a partial index, *piPartIdxLabel
   91616 ** will be set to zero which is an empty label that is ignored by
   91617 ** sqlite3ResolvePartIdxLabel().
   91618 **
   91619 ** The pPrior and regPrior parameters are used to implement a cache to
   91620 ** avoid unnecessary register loads.  If pPrior is not NULL, then it is
   91621 ** a pointer to a different index for which an index key has just been
   91622 ** computed into register regPrior.  If the current pIdx index is generating
   91623 ** its key into the same sequence of registers and if pPrior and pIdx share
   91624 ** a column in common, then the register corresponding to that column already
   91625 ** holds the correct value and the loading of that register is skipped.
   91626 ** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
   91627 ** on a table with multiple indices, and especially with the ROWID or
   91628 ** PRIMARY KEY columns of the index.
   91629 */
   91630 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
   91631   Parse *pParse,       /* Parsing context */
   91632   Index *pIdx,         /* The index for which to generate a key */
   91633   int iDataCur,        /* Cursor number from which to take column data */
   91634   int regOut,          /* Put the new key into this register if not 0 */
   91635   int prefixOnly,      /* Compute only a unique prefix of the key */
   91636   int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
   91637   Index *pPrior,       /* Previously generated index key */
   91638   int regPrior         /* Register holding previous generated key */
   91639 ){
   91640   Vdbe *v = pParse->pVdbe;
   91641   int j;
   91642   Table *pTab = pIdx->pTable;
   91643   int regBase;
   91644   int nCol;
   91645 
   91646   if( piPartIdxLabel ){
   91647     if( pIdx->pPartIdxWhere ){
   91648       *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
   91649       pParse->iPartIdxTab = iDataCur;
   91650       sqlite3ExprCachePush(pParse);
   91651       sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
   91652                          SQLITE_JUMPIFNULL);
   91653     }else{
   91654       *piPartIdxLabel = 0;
   91655     }
   91656   }
   91657   nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
   91658   regBase = sqlite3GetTempRange(pParse, nCol);
   91659   if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
   91660   for(j=0; j<nCol; j++){
   91661     if( pPrior && pPrior->aiColumn[j]==pIdx->aiColumn[j] ) continue;
   91662     sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, pIdx->aiColumn[j],
   91663                                     regBase+j);
   91664     /* If the column affinity is REAL but the number is an integer, then it
   91665     ** might be stored in the table as an integer (using a compact
   91666     ** representation) then converted to REAL by an OP_RealAffinity opcode.
   91667     ** But we are getting ready to store this value back into an index, where
   91668     ** it should be converted by to INTEGER again.  So omit the OP_RealAffinity
   91669     ** opcode if it is present */
   91670     sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
   91671   }
   91672   if( regOut ){
   91673     sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
   91674   }
   91675   sqlite3ReleaseTempRange(pParse, regBase, nCol);
   91676   return regBase;
   91677 }
   91678 
   91679 /*
   91680 ** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
   91681 ** because it was a partial index, then this routine should be called to
   91682 ** resolve that label.
   91683 */
   91684 SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){
   91685   if( iLabel ){
   91686     sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
   91687     sqlite3ExprCachePop(pParse);
   91688   }
   91689 }
   91690 
   91691 /************** End of delete.c **********************************************/
   91692 /************** Begin file func.c ********************************************/
   91693 /*
   91694 ** 2002 February 23
   91695 **
   91696 ** The author disclaims copyright to this source code.  In place of
   91697 ** a legal notice, here is a blessing:
   91698 **
   91699 **    May you do good and not evil.
   91700 **    May you find forgiveness for yourself and forgive others.
   91701 **    May you share freely, never taking more than you give.
   91702 **
   91703 *************************************************************************
   91704 ** This file contains the C-language implementions for many of the SQL
   91705 ** functions of SQLite.  (Some function, and in particular the date and
   91706 ** time functions, are implemented separately.)
   91707 */
   91708 /* #include <stdlib.h> */
   91709 /* #include <assert.h> */
   91710 
   91711 /*
   91712 ** Return the collating function associated with a function.
   91713 */
   91714 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
   91715   return context->pColl;
   91716 }
   91717 
   91718 /*
   91719 ** Indicate that the accumulator load should be skipped on this
   91720 ** iteration of the aggregate loop.
   91721 */
   91722 static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
   91723   context->skipFlag = 1;
   91724 }
   91725 
   91726 /*
   91727 ** Implementation of the non-aggregate min() and max() functions
   91728 */
   91729 static void minmaxFunc(
   91730   sqlite3_context *context,
   91731   int argc,
   91732   sqlite3_value **argv
   91733 ){
   91734   int i;
   91735   int mask;    /* 0 for min() or 0xffffffff for max() */
   91736   int iBest;
   91737   CollSeq *pColl;
   91738 
   91739   assert( argc>1 );
   91740   mask = sqlite3_user_data(context)==0 ? 0 : -1;
   91741   pColl = sqlite3GetFuncCollSeq(context);
   91742   assert( pColl );
   91743   assert( mask==-1 || mask==0 );
   91744   iBest = 0;
   91745   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
   91746   for(i=1; i<argc; i++){
   91747     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
   91748     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
   91749       testcase( mask==0 );
   91750       iBest = i;
   91751     }
   91752   }
   91753   sqlite3_result_value(context, argv[iBest]);
   91754 }
   91755 
   91756 /*
   91757 ** Return the type of the argument.
   91758 */
   91759 static void typeofFunc(
   91760   sqlite3_context *context,
   91761   int NotUsed,
   91762   sqlite3_value **argv
   91763 ){
   91764   const char *z = 0;
   91765   UNUSED_PARAMETER(NotUsed);
   91766   switch( sqlite3_value_type(argv[0]) ){
   91767     case SQLITE_INTEGER: z = "integer"; break;
   91768     case SQLITE_TEXT:    z = "text";    break;
   91769     case SQLITE_FLOAT:   z = "real";    break;
   91770     case SQLITE_BLOB:    z = "blob";    break;
   91771     default:             z = "null";    break;
   91772   }
   91773   sqlite3_result_text(context, z, -1, SQLITE_STATIC);
   91774 }
   91775 
   91776 
   91777 /*
   91778 ** Implementation of the length() function
   91779 */
   91780 static void lengthFunc(
   91781   sqlite3_context *context,
   91782   int argc,
   91783   sqlite3_value **argv
   91784 ){
   91785   int len;
   91786 
   91787   assert( argc==1 );
   91788   UNUSED_PARAMETER(argc);
   91789   switch( sqlite3_value_type(argv[0]) ){
   91790     case SQLITE_BLOB:
   91791     case SQLITE_INTEGER:
   91792     case SQLITE_FLOAT: {
   91793       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
   91794       break;
   91795     }
   91796     case SQLITE_TEXT: {
   91797       const unsigned char *z = sqlite3_value_text(argv[0]);
   91798       if( z==0 ) return;
   91799       len = 0;
   91800       while( *z ){
   91801         len++;
   91802         SQLITE_SKIP_UTF8(z);
   91803       }
   91804       sqlite3_result_int(context, len);
   91805       break;
   91806     }
   91807     default: {
   91808       sqlite3_result_null(context);
   91809       break;
   91810     }
   91811   }
   91812 }
   91813 
   91814 /*
   91815 ** Implementation of the abs() function.
   91816 **
   91817 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
   91818 ** the numeric argument X.
   91819 */
   91820 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   91821   assert( argc==1 );
   91822   UNUSED_PARAMETER(argc);
   91823   switch( sqlite3_value_type(argv[0]) ){
   91824     case SQLITE_INTEGER: {
   91825       i64 iVal = sqlite3_value_int64(argv[0]);
   91826       if( iVal<0 ){
   91827         if( iVal==SMALLEST_INT64 ){
   91828           /* IMP: R-31676-45509 If X is the integer -9223372036854775808
   91829           ** then abs(X) throws an integer overflow error since there is no
   91830           ** equivalent positive 64-bit two complement value. */
   91831           sqlite3_result_error(context, "integer overflow", -1);
   91832           return;
   91833         }
   91834         iVal = -iVal;
   91835       }
   91836       sqlite3_result_int64(context, iVal);
   91837       break;
   91838     }
   91839     case SQLITE_NULL: {
   91840       /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
   91841       sqlite3_result_null(context);
   91842       break;
   91843     }
   91844     default: {
   91845       /* Because sqlite3_value_double() returns 0.0 if the argument is not
   91846       ** something that can be converted into a number, we have:
   91847       ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
   91848       ** cannot be converted to a numeric value.
   91849       */
   91850       double rVal = sqlite3_value_double(argv[0]);
   91851       if( rVal<0 ) rVal = -rVal;
   91852       sqlite3_result_double(context, rVal);
   91853       break;
   91854     }
   91855   }
   91856 }
   91857 
   91858 /*
   91859 ** Implementation of the instr() function.
   91860 **
   91861 ** instr(haystack,needle) finds the first occurrence of needle
   91862 ** in haystack and returns the number of previous characters plus 1,
   91863 ** or 0 if needle does not occur within haystack.
   91864 **
   91865 ** If both haystack and needle are BLOBs, then the result is one more than
   91866 ** the number of bytes in haystack prior to the first occurrence of needle,
   91867 ** or 0 if needle never occurs in haystack.
   91868 */
   91869 static void instrFunc(
   91870   sqlite3_context *context,
   91871   int argc,
   91872   sqlite3_value **argv
   91873 ){
   91874   const unsigned char *zHaystack;
   91875   const unsigned char *zNeedle;
   91876   int nHaystack;
   91877   int nNeedle;
   91878   int typeHaystack, typeNeedle;
   91879   int N = 1;
   91880   int isText;
   91881 
   91882   UNUSED_PARAMETER(argc);
   91883   typeHaystack = sqlite3_value_type(argv[0]);
   91884   typeNeedle = sqlite3_value_type(argv[1]);
   91885   if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
   91886   nHaystack = sqlite3_value_bytes(argv[0]);
   91887   nNeedle = sqlite3_value_bytes(argv[1]);
   91888   if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
   91889     zHaystack = sqlite3_value_blob(argv[0]);
   91890     zNeedle = sqlite3_value_blob(argv[1]);
   91891     isText = 0;
   91892   }else{
   91893     zHaystack = sqlite3_value_text(argv[0]);
   91894     zNeedle = sqlite3_value_text(argv[1]);
   91895     isText = 1;
   91896   }
   91897   while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
   91898     N++;
   91899     do{
   91900       nHaystack--;
   91901       zHaystack++;
   91902     }while( isText && (zHaystack[0]&0xc0)==0x80 );
   91903   }
   91904   if( nNeedle>nHaystack ) N = 0;
   91905   sqlite3_result_int(context, N);
   91906 }
   91907 
   91908 /*
   91909 ** Implementation of the printf() function.
   91910 */
   91911 static void printfFunc(
   91912   sqlite3_context *context,
   91913   int argc,
   91914   sqlite3_value **argv
   91915 ){
   91916   PrintfArguments x;
   91917   StrAccum str;
   91918   const char *zFormat;
   91919   int n;
   91920 
   91921   if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
   91922     x.nArg = argc-1;
   91923     x.nUsed = 0;
   91924     x.apArg = argv+1;
   91925     sqlite3StrAccumInit(&str, 0, 0, SQLITE_MAX_LENGTH);
   91926     str.db = sqlite3_context_db_handle(context);
   91927     sqlite3XPrintf(&str, SQLITE_PRINTF_SQLFUNC, zFormat, &x);
   91928     n = str.nChar;
   91929     sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
   91930                         SQLITE_DYNAMIC);
   91931   }
   91932 }
   91933 
   91934 /*
   91935 ** Implementation of the substr() function.
   91936 **
   91937 ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
   91938 ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
   91939 ** of x.  If x is text, then we actually count UTF-8 characters.
   91940 ** If x is a blob, then we count bytes.
   91941 **
   91942 ** If p1 is negative, then we begin abs(p1) from the end of x[].
   91943 **
   91944 ** If p2 is negative, return the p2 characters preceding p1.
   91945 */
   91946 static void substrFunc(
   91947   sqlite3_context *context,
   91948   int argc,
   91949   sqlite3_value **argv
   91950 ){
   91951   const unsigned char *z;
   91952   const unsigned char *z2;
   91953   int len;
   91954   int p0type;
   91955   i64 p1, p2;
   91956   int negP2 = 0;
   91957 
   91958   assert( argc==3 || argc==2 );
   91959   if( sqlite3_value_type(argv[1])==SQLITE_NULL
   91960    || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
   91961   ){
   91962     return;
   91963   }
   91964   p0type = sqlite3_value_type(argv[0]);
   91965   p1 = sqlite3_value_int(argv[1]);
   91966   if( p0type==SQLITE_BLOB ){
   91967     len = sqlite3_value_bytes(argv[0]);
   91968     z = sqlite3_value_blob(argv[0]);
   91969     if( z==0 ) return;
   91970     assert( len==sqlite3_value_bytes(argv[0]) );
   91971   }else{
   91972     z = sqlite3_value_text(argv[0]);
   91973     if( z==0 ) return;
   91974     len = 0;
   91975     if( p1<0 ){
   91976       for(z2=z; *z2; len++){
   91977         SQLITE_SKIP_UTF8(z2);
   91978       }
   91979     }
   91980   }
   91981   if( argc==3 ){
   91982     p2 = sqlite3_value_int(argv[2]);
   91983     if( p2<0 ){
   91984       p2 = -p2;
   91985       negP2 = 1;
   91986     }
   91987   }else{
   91988     p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
   91989   }
   91990   if( p1<0 ){
   91991     p1 += len;
   91992     if( p1<0 ){
   91993       p2 += p1;
   91994       if( p2<0 ) p2 = 0;
   91995       p1 = 0;
   91996     }
   91997   }else if( p1>0 ){
   91998     p1--;
   91999   }else if( p2>0 ){
   92000     p2--;
   92001   }
   92002   if( negP2 ){
   92003     p1 -= p2;
   92004     if( p1<0 ){
   92005       p2 += p1;
   92006       p1 = 0;
   92007     }
   92008   }
   92009   assert( p1>=0 && p2>=0 );
   92010   if( p0type!=SQLITE_BLOB ){
   92011     while( *z && p1 ){
   92012       SQLITE_SKIP_UTF8(z);
   92013       p1--;
   92014     }
   92015     for(z2=z; *z2 && p2; p2--){
   92016       SQLITE_SKIP_UTF8(z2);
   92017     }
   92018     sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
   92019   }else{
   92020     if( p1+p2>len ){
   92021       p2 = len-p1;
   92022       if( p2<0 ) p2 = 0;
   92023     }
   92024     sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
   92025   }
   92026 }
   92027 
   92028 /*
   92029 ** Implementation of the round() function
   92030 */
   92031 #ifndef SQLITE_OMIT_FLOATING_POINT
   92032 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   92033   int n = 0;
   92034   double r;
   92035   char *zBuf;
   92036   assert( argc==1 || argc==2 );
   92037   if( argc==2 ){
   92038     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
   92039     n = sqlite3_value_int(argv[1]);
   92040     if( n>30 ) n = 30;
   92041     if( n<0 ) n = 0;
   92042   }
   92043   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
   92044   r = sqlite3_value_double(argv[0]);
   92045   /* If Y==0 and X will fit in a 64-bit int,
   92046   ** handle the rounding directly,
   92047   ** otherwise use printf.
   92048   */
   92049   if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
   92050     r = (double)((sqlite_int64)(r+0.5));
   92051   }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
   92052     r = -(double)((sqlite_int64)((-r)+0.5));
   92053   }else{
   92054     zBuf = sqlite3_mprintf("%.*f",n,r);
   92055     if( zBuf==0 ){
   92056       sqlite3_result_error_nomem(context);
   92057       return;
   92058     }
   92059     sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
   92060     sqlite3_free(zBuf);
   92061   }
   92062   sqlite3_result_double(context, r);
   92063 }
   92064 #endif
   92065 
   92066 /*
   92067 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
   92068 ** allocation fails, call sqlite3_result_error_nomem() to notify
   92069 ** the database handle that malloc() has failed and return NULL.
   92070 ** If nByte is larger than the maximum string or blob length, then
   92071 ** raise an SQLITE_TOOBIG exception and return NULL.
   92072 */
   92073 static void *contextMalloc(sqlite3_context *context, i64 nByte){
   92074   char *z;
   92075   sqlite3 *db = sqlite3_context_db_handle(context);
   92076   assert( nByte>0 );
   92077   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
   92078   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
   92079   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   92080     sqlite3_result_error_toobig(context);
   92081     z = 0;
   92082   }else{
   92083     z = sqlite3Malloc((int)nByte);
   92084     if( !z ){
   92085       sqlite3_result_error_nomem(context);
   92086     }
   92087   }
   92088   return z;
   92089 }
   92090 
   92091 /*
   92092 ** Implementation of the upper() and lower() SQL functions.
   92093 */
   92094 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   92095   char *z1;
   92096   const char *z2;
   92097   int i, n;
   92098   UNUSED_PARAMETER(argc);
   92099   z2 = (char*)sqlite3_value_text(argv[0]);
   92100   n = sqlite3_value_bytes(argv[0]);
   92101   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
   92102   assert( z2==(char*)sqlite3_value_text(argv[0]) );
   92103   if( z2 ){
   92104     z1 = contextMalloc(context, ((i64)n)+1);
   92105     if( z1 ){
   92106       for(i=0; i<n; i++){
   92107         z1[i] = (char)sqlite3Toupper(z2[i]);
   92108       }
   92109       sqlite3_result_text(context, z1, n, sqlite3_free);
   92110     }
   92111   }
   92112 }
   92113 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   92114   char *z1;
   92115   const char *z2;
   92116   int i, n;
   92117   UNUSED_PARAMETER(argc);
   92118   z2 = (char*)sqlite3_value_text(argv[0]);
   92119   n = sqlite3_value_bytes(argv[0]);
   92120   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
   92121   assert( z2==(char*)sqlite3_value_text(argv[0]) );
   92122   if( z2 ){
   92123     z1 = contextMalloc(context, ((i64)n)+1);
   92124     if( z1 ){
   92125       for(i=0; i<n; i++){
   92126         z1[i] = sqlite3Tolower(z2[i]);
   92127       }
   92128       sqlite3_result_text(context, z1, n, sqlite3_free);
   92129     }
   92130   }
   92131 }
   92132 
   92133 /*
   92134 ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
   92135 ** as VDBE code so that unused argument values do not have to be computed.
   92136 ** However, we still need some kind of function implementation for this
   92137 ** routines in the function table.  The noopFunc macro provides this.
   92138 ** noopFunc will never be called so it doesn't matter what the implementation
   92139 ** is.  We might as well use the "version()" function as a substitute.
   92140 */
   92141 #define noopFunc versionFunc   /* Substitute function - never called */
   92142 
   92143 /*
   92144 ** Implementation of random().  Return a random integer.
   92145 */
   92146 static void randomFunc(
   92147   sqlite3_context *context,
   92148   int NotUsed,
   92149   sqlite3_value **NotUsed2
   92150 ){
   92151   sqlite_int64 r;
   92152   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   92153   sqlite3_randomness(sizeof(r), &r);
   92154   if( r<0 ){
   92155     /* We need to prevent a random number of 0x8000000000000000
   92156     ** (or -9223372036854775808) since when you do abs() of that
   92157     ** number of you get the same value back again.  To do this
   92158     ** in a way that is testable, mask the sign bit off of negative
   92159     ** values, resulting in a positive value.  Then take the
   92160     ** 2s complement of that positive value.  The end result can
   92161     ** therefore be no less than -9223372036854775807.
   92162     */
   92163     r = -(r & LARGEST_INT64);
   92164   }
   92165   sqlite3_result_int64(context, r);
   92166 }
   92167 
   92168 /*
   92169 ** Implementation of randomblob(N).  Return a random blob
   92170 ** that is N bytes long.
   92171 */
   92172 static void randomBlob(
   92173   sqlite3_context *context,
   92174   int argc,
   92175   sqlite3_value **argv
   92176 ){
   92177   int n;
   92178   unsigned char *p;
   92179   assert( argc==1 );
   92180   UNUSED_PARAMETER(argc);
   92181   n = sqlite3_value_int(argv[0]);
   92182   if( n<1 ){
   92183     n = 1;
   92184   }
   92185   p = contextMalloc(context, n);
   92186   if( p ){
   92187     sqlite3_randomness(n, p);
   92188     sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
   92189   }
   92190 }
   92191 
   92192 /*
   92193 ** Implementation of the last_insert_rowid() SQL function.  The return
   92194 ** value is the same as the sqlite3_last_insert_rowid() API function.
   92195 */
   92196 static void last_insert_rowid(
   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   /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
   92204   ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
   92205   ** function. */
   92206   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
   92207 }
   92208 
   92209 /*
   92210 ** Implementation of the changes() SQL function.
   92211 **
   92212 ** IMP: R-62073-11209 The changes() SQL function is a wrapper
   92213 ** around the sqlite3_changes() C/C++ function and hence follows the same
   92214 ** rules for counting changes.
   92215 */
   92216 static void changes(
   92217   sqlite3_context *context,
   92218   int NotUsed,
   92219   sqlite3_value **NotUsed2
   92220 ){
   92221   sqlite3 *db = sqlite3_context_db_handle(context);
   92222   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   92223   sqlite3_result_int(context, sqlite3_changes(db));
   92224 }
   92225 
   92226 /*
   92227 ** Implementation of the total_changes() SQL function.  The return value is
   92228 ** the same as the sqlite3_total_changes() API function.
   92229 */
   92230 static void total_changes(
   92231   sqlite3_context *context,
   92232   int NotUsed,
   92233   sqlite3_value **NotUsed2
   92234 ){
   92235   sqlite3 *db = sqlite3_context_db_handle(context);
   92236   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   92237   /* IMP: R-52756-41993 This function is a wrapper around the
   92238   ** sqlite3_total_changes() C/C++ interface. */
   92239   sqlite3_result_int(context, sqlite3_total_changes(db));
   92240 }
   92241 
   92242 /*
   92243 ** A structure defining how to do GLOB-style comparisons.
   92244 */
   92245 struct compareInfo {
   92246   u8 matchAll;
   92247   u8 matchOne;
   92248   u8 matchSet;
   92249   u8 noCase;
   92250 };
   92251 
   92252 /*
   92253 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
   92254 ** character is exactly one byte in size.  Also, all characters are
   92255 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
   92256 ** whereas only characters less than 0x80 do in ASCII.
   92257 */
   92258 #if defined(SQLITE_EBCDIC)
   92259 # define sqlite3Utf8Read(A)    (*((*A)++))
   92260 # define GlobUpperToLower(A)   A = sqlite3UpperToLower[A]
   92261 #else
   92262 # define GlobUpperToLower(A)   if( !((A)&~0x7f) ){ A = sqlite3UpperToLower[A]; }
   92263 #endif
   92264 
   92265 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
   92266 /* The correct SQL-92 behavior is for the LIKE operator to ignore
   92267 ** case.  Thus  'a' LIKE 'A' would be true. */
   92268 static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
   92269 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
   92270 ** is case sensitive causing 'a' LIKE 'A' to be false */
   92271 static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
   92272 
   92273 /*
   92274 ** Compare two UTF-8 strings for equality where the first string can
   92275 ** potentially be a "glob" expression.  Return true (1) if they
   92276 ** are the same and false (0) if they are different.
   92277 **
   92278 ** Globbing rules:
   92279 **
   92280 **      '*'       Matches any sequence of zero or more characters.
   92281 **
   92282 **      '?'       Matches exactly one character.
   92283 **
   92284 **     [...]      Matches one character from the enclosed list of
   92285 **                characters.
   92286 **
   92287 **     [^...]     Matches one character not in the enclosed list.
   92288 **
   92289 ** With the [...] and [^...] matching, a ']' character can be included
   92290 ** in the list by making it the first character after '[' or '^'.  A
   92291 ** range of characters can be specified using '-'.  Example:
   92292 ** "[a-z]" matches any single lower-case letter.  To match a '-', make
   92293 ** it the last character in the list.
   92294 **
   92295 ** This routine is usually quick, but can be N**2 in the worst case.
   92296 **
   92297 ** Hints: to match '*' or '?', put them in "[]".  Like this:
   92298 **
   92299 **         abc[*]xyz        Matches "abc*xyz" only
   92300 */
   92301 static int patternCompare(
   92302   const u8 *zPattern,              /* The glob pattern */
   92303   const u8 *zString,               /* The string to compare against the glob */
   92304   const struct compareInfo *pInfo, /* Information about how to do the compare */
   92305   u32 esc                          /* The escape character */
   92306 ){
   92307   u32 c, c2;
   92308   int invert;
   92309   int seen;
   92310   u8 matchOne = pInfo->matchOne;
   92311   u8 matchAll = pInfo->matchAll;
   92312   u8 matchSet = pInfo->matchSet;
   92313   u8 noCase = pInfo->noCase;
   92314   int prevEscape = 0;     /* True if the previous character was 'escape' */
   92315 
   92316   while( (c = sqlite3Utf8Read(&zPattern))!=0 ){
   92317     if( c==matchAll && !prevEscape ){
   92318       while( (c=sqlite3Utf8Read(&zPattern)) == matchAll
   92319                || c == matchOne ){
   92320         if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
   92321           return 0;
   92322         }
   92323       }
   92324       if( c==0 ){
   92325         return 1;
   92326       }else if( c==esc ){
   92327         c = sqlite3Utf8Read(&zPattern);
   92328         if( c==0 ){
   92329           return 0;
   92330         }
   92331       }else if( c==matchSet ){
   92332         assert( esc==0 );         /* This is GLOB, not LIKE */
   92333         assert( matchSet<0x80 );  /* '[' is a single-byte character */
   92334         while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
   92335           SQLITE_SKIP_UTF8(zString);
   92336         }
   92337         return *zString!=0;
   92338       }
   92339       while( (c2 = sqlite3Utf8Read(&zString))!=0 ){
   92340         if( noCase ){
   92341           GlobUpperToLower(c2);
   92342           GlobUpperToLower(c);
   92343           while( c2 != 0 && c2 != c ){
   92344             c2 = sqlite3Utf8Read(&zString);
   92345             GlobUpperToLower(c2);
   92346           }
   92347         }else{
   92348           while( c2 != 0 && c2 != c ){
   92349             c2 = sqlite3Utf8Read(&zString);
   92350           }
   92351         }
   92352         if( c2==0 ) return 0;
   92353         if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
   92354       }
   92355       return 0;
   92356     }else if( c==matchOne && !prevEscape ){
   92357       if( sqlite3Utf8Read(&zString)==0 ){
   92358         return 0;
   92359       }
   92360     }else if( c==matchSet ){
   92361       u32 prior_c = 0;
   92362       assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
   92363       seen = 0;
   92364       invert = 0;
   92365       c = sqlite3Utf8Read(&zString);
   92366       if( c==0 ) return 0;
   92367       c2 = sqlite3Utf8Read(&zPattern);
   92368       if( c2=='^' ){
   92369         invert = 1;
   92370         c2 = sqlite3Utf8Read(&zPattern);
   92371       }
   92372       if( c2==']' ){
   92373         if( c==']' ) seen = 1;
   92374         c2 = sqlite3Utf8Read(&zPattern);
   92375       }
   92376       while( c2 && c2!=']' ){
   92377         if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
   92378           c2 = sqlite3Utf8Read(&zPattern);
   92379           if( c>=prior_c && c<=c2 ) seen = 1;
   92380           prior_c = 0;
   92381         }else{
   92382           if( c==c2 ){
   92383             seen = 1;
   92384           }
   92385           prior_c = c2;
   92386         }
   92387         c2 = sqlite3Utf8Read(&zPattern);
   92388       }
   92389       if( c2==0 || (seen ^ invert)==0 ){
   92390         return 0;
   92391       }
   92392     }else if( esc==c && !prevEscape ){
   92393       prevEscape = 1;
   92394     }else{
   92395       c2 = sqlite3Utf8Read(&zString);
   92396       if( noCase ){
   92397         GlobUpperToLower(c);
   92398         GlobUpperToLower(c2);
   92399       }
   92400       if( c!=c2 ){
   92401         return 0;
   92402       }
   92403       prevEscape = 0;
   92404     }
   92405   }
   92406   return *zString==0;
   92407 }
   92408 
   92409 /*
   92410 ** The sqlite3_strglob() interface.
   92411 */
   92412 SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){
   92413   return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, 0)==0;
   92414 }
   92415 
   92416 /*
   92417 ** Count the number of times that the LIKE operator (or GLOB which is
   92418 ** just a variation of LIKE) gets called.  This is used for testing
   92419 ** only.
   92420 */
   92421 #ifdef SQLITE_TEST
   92422 SQLITE_API int sqlite3_like_count = 0;
   92423 #endif
   92424 
   92425 
   92426 /*
   92427 ** Implementation of the like() SQL function.  This function implements
   92428 ** the build-in LIKE operator.  The first argument to the function is the
   92429 ** pattern and the second argument is the string.  So, the SQL statements:
   92430 **
   92431 **       A LIKE B
   92432 **
   92433 ** is implemented as like(B,A).
   92434 **
   92435 ** This same function (with a different compareInfo structure) computes
   92436 ** the GLOB operator.
   92437 */
   92438 static void likeFunc(
   92439   sqlite3_context *context,
   92440   int argc,
   92441   sqlite3_value **argv
   92442 ){
   92443   const unsigned char *zA, *zB;
   92444   u32 escape = 0;
   92445   int nPat;
   92446   sqlite3 *db = sqlite3_context_db_handle(context);
   92447 
   92448   zB = sqlite3_value_text(argv[0]);
   92449   zA = sqlite3_value_text(argv[1]);
   92450 
   92451   /* Limit the length of the LIKE or GLOB pattern to avoid problems
   92452   ** of deep recursion and N*N behavior in patternCompare().
   92453   */
   92454   nPat = sqlite3_value_bytes(argv[0]);
   92455   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
   92456   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
   92457   if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
   92458     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
   92459     return;
   92460   }
   92461   assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
   92462 
   92463   if( argc==3 ){
   92464     /* The escape character string must consist of a single UTF-8 character.
   92465     ** Otherwise, return an error.
   92466     */
   92467     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
   92468     if( zEsc==0 ) return;
   92469     if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
   92470       sqlite3_result_error(context,
   92471           "ESCAPE expression must be a single character", -1);
   92472       return;
   92473     }
   92474     escape = sqlite3Utf8Read(&zEsc);
   92475   }
   92476   if( zA && zB ){
   92477     struct compareInfo *pInfo = sqlite3_user_data(context);
   92478 #ifdef SQLITE_TEST
   92479     sqlite3_like_count++;
   92480 #endif
   92481 
   92482     sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
   92483   }
   92484 }
   92485 
   92486 /*
   92487 ** Implementation of the NULLIF(x,y) function.  The result is the first
   92488 ** argument if the arguments are different.  The result is NULL if the
   92489 ** arguments are equal to each other.
   92490 */
   92491 static void nullifFunc(
   92492   sqlite3_context *context,
   92493   int NotUsed,
   92494   sqlite3_value **argv
   92495 ){
   92496   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
   92497   UNUSED_PARAMETER(NotUsed);
   92498   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
   92499     sqlite3_result_value(context, argv[0]);
   92500   }
   92501 }
   92502 
   92503 /*
   92504 ** Implementation of the sqlite_version() function.  The result is the version
   92505 ** of the SQLite library that is running.
   92506 */
   92507 static void versionFunc(
   92508   sqlite3_context *context,
   92509   int NotUsed,
   92510   sqlite3_value **NotUsed2
   92511 ){
   92512   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   92513   /* IMP: R-48699-48617 This function is an SQL wrapper around the
   92514   ** sqlite3_libversion() C-interface. */
   92515   sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
   92516 }
   92517 
   92518 /*
   92519 ** Implementation of the sqlite_source_id() function. The result is a string
   92520 ** that identifies the particular version of the source code used to build
   92521 ** SQLite.
   92522 */
   92523 static void sourceidFunc(
   92524   sqlite3_context *context,
   92525   int NotUsed,
   92526   sqlite3_value **NotUsed2
   92527 ){
   92528   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   92529   /* IMP: R-24470-31136 This function is an SQL wrapper around the
   92530   ** sqlite3_sourceid() C interface. */
   92531   sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
   92532 }
   92533 
   92534 /*
   92535 ** Implementation of the sqlite_log() function.  This is a wrapper around
   92536 ** sqlite3_log().  The return value is NULL.  The function exists purely for
   92537 ** its side-effects.
   92538 */
   92539 static void errlogFunc(
   92540   sqlite3_context *context,
   92541   int argc,
   92542   sqlite3_value **argv
   92543 ){
   92544   UNUSED_PARAMETER(argc);
   92545   UNUSED_PARAMETER(context);
   92546   sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
   92547 }
   92548 
   92549 /*
   92550 ** Implementation of the sqlite_compileoption_used() function.
   92551 ** The result is an integer that identifies if the compiler option
   92552 ** was used to build SQLite.
   92553 */
   92554 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
   92555 static void compileoptionusedFunc(
   92556   sqlite3_context *context,
   92557   int argc,
   92558   sqlite3_value **argv
   92559 ){
   92560   const char *zOptName;
   92561   assert( argc==1 );
   92562   UNUSED_PARAMETER(argc);
   92563   /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
   92564   ** function is a wrapper around the sqlite3_compileoption_used() C/C++
   92565   ** function.
   92566   */
   92567   if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
   92568     sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
   92569   }
   92570 }
   92571 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
   92572 
   92573 /*
   92574 ** Implementation of the sqlite_compileoption_get() function.
   92575 ** The result is a string that identifies the compiler options
   92576 ** used to build SQLite.
   92577 */
   92578 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
   92579 static void compileoptiongetFunc(
   92580   sqlite3_context *context,
   92581   int argc,
   92582   sqlite3_value **argv
   92583 ){
   92584   int n;
   92585   assert( argc==1 );
   92586   UNUSED_PARAMETER(argc);
   92587   /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
   92588   ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
   92589   */
   92590   n = sqlite3_value_int(argv[0]);
   92591   sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
   92592 }
   92593 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
   92594 
   92595 /* Array for converting from half-bytes (nybbles) into ASCII hex
   92596 ** digits. */
   92597 static const char hexdigits[] = {
   92598   '0', '1', '2', '3', '4', '5', '6', '7',
   92599   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
   92600 };
   92601 
   92602 /*
   92603 ** Implementation of the QUOTE() function.  This function takes a single
   92604 ** argument.  If the argument is numeric, the return value is the same as
   92605 ** the argument.  If the argument is NULL, the return value is the string
   92606 ** "NULL".  Otherwise, the argument is enclosed in single quotes with
   92607 ** single-quote escapes.
   92608 */
   92609 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   92610   assert( argc==1 );
   92611   UNUSED_PARAMETER(argc);
   92612   switch( sqlite3_value_type(argv[0]) ){
   92613     case SQLITE_FLOAT: {
   92614       double r1, r2;
   92615       char zBuf[50];
   92616       r1 = sqlite3_value_double(argv[0]);
   92617       sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
   92618       sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
   92619       if( r1!=r2 ){
   92620         sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
   92621       }
   92622       sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
   92623       break;
   92624     }
   92625     case SQLITE_INTEGER: {
   92626       sqlite3_result_value(context, argv[0]);
   92627       break;
   92628     }
   92629     case SQLITE_BLOB: {
   92630       char *zText = 0;
   92631       char const *zBlob = sqlite3_value_blob(argv[0]);
   92632       int nBlob = sqlite3_value_bytes(argv[0]);
   92633       assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
   92634       zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
   92635       if( zText ){
   92636         int i;
   92637         for(i=0; i<nBlob; i++){
   92638           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
   92639           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
   92640         }
   92641         zText[(nBlob*2)+2] = '\'';
   92642         zText[(nBlob*2)+3] = '\0';
   92643         zText[0] = 'X';
   92644         zText[1] = '\'';
   92645         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
   92646         sqlite3_free(zText);
   92647       }
   92648       break;
   92649     }
   92650     case SQLITE_TEXT: {
   92651       int i,j;
   92652       u64 n;
   92653       const unsigned char *zArg = sqlite3_value_text(argv[0]);
   92654       char *z;
   92655 
   92656       if( zArg==0 ) return;
   92657       for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
   92658       z = contextMalloc(context, ((i64)i)+((i64)n)+3);
   92659       if( z ){
   92660         z[0] = '\'';
   92661         for(i=0, j=1; zArg[i]; i++){
   92662           z[j++] = zArg[i];
   92663           if( zArg[i]=='\'' ){
   92664             z[j++] = '\'';
   92665           }
   92666         }
   92667         z[j++] = '\'';
   92668         z[j] = 0;
   92669         sqlite3_result_text(context, z, j, sqlite3_free);
   92670       }
   92671       break;
   92672     }
   92673     default: {
   92674       assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
   92675       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
   92676       break;
   92677     }
   92678   }
   92679 }
   92680 
   92681 /*
   92682 ** The unicode() function.  Return the integer unicode code-point value
   92683 ** for the first character of the input string.
   92684 */
   92685 static void unicodeFunc(
   92686   sqlite3_context *context,
   92687   int argc,
   92688   sqlite3_value **argv
   92689 ){
   92690   const unsigned char *z = sqlite3_value_text(argv[0]);
   92691   (void)argc;
   92692   if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
   92693 }
   92694 
   92695 /*
   92696 ** The char() function takes zero or more arguments, each of which is
   92697 ** an integer.  It constructs a string where each character of the string
   92698 ** is the unicode character for the corresponding integer argument.
   92699 */
   92700 static void charFunc(
   92701   sqlite3_context *context,
   92702   int argc,
   92703   sqlite3_value **argv
   92704 ){
   92705   unsigned char *z, *zOut;
   92706   int i;
   92707   zOut = z = sqlite3_malloc( argc*4+1 );
   92708   if( z==0 ){
   92709     sqlite3_result_error_nomem(context);
   92710     return;
   92711   }
   92712   for(i=0; i<argc; i++){
   92713     sqlite3_int64 x;
   92714     unsigned c;
   92715     x = sqlite3_value_int64(argv[i]);
   92716     if( x<0 || x>0x10ffff ) x = 0xfffd;
   92717     c = (unsigned)(x & 0x1fffff);
   92718     if( c<0x00080 ){
   92719       *zOut++ = (u8)(c&0xFF);
   92720     }else if( c<0x00800 ){
   92721       *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
   92722       *zOut++ = 0x80 + (u8)(c & 0x3F);
   92723     }else if( c<0x10000 ){
   92724       *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
   92725       *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
   92726       *zOut++ = 0x80 + (u8)(c & 0x3F);
   92727     }else{
   92728       *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
   92729       *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
   92730       *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
   92731       *zOut++ = 0x80 + (u8)(c & 0x3F);
   92732     }                                                    \
   92733   }
   92734   sqlite3_result_text(context, (char*)z, (int)(zOut-z), sqlite3_free);
   92735 }
   92736 
   92737 /*
   92738 ** The hex() function.  Interpret the argument as a blob.  Return
   92739 ** a hexadecimal rendering as text.
   92740 */
   92741 static void hexFunc(
   92742   sqlite3_context *context,
   92743   int argc,
   92744   sqlite3_value **argv
   92745 ){
   92746   int i, n;
   92747   const unsigned char *pBlob;
   92748   char *zHex, *z;
   92749   assert( argc==1 );
   92750   UNUSED_PARAMETER(argc);
   92751   pBlob = sqlite3_value_blob(argv[0]);
   92752   n = sqlite3_value_bytes(argv[0]);
   92753   assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
   92754   z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
   92755   if( zHex ){
   92756     for(i=0; i<n; i++, pBlob++){
   92757       unsigned char c = *pBlob;
   92758       *(z++) = hexdigits[(c>>4)&0xf];
   92759       *(z++) = hexdigits[c&0xf];
   92760     }
   92761     *z = 0;
   92762     sqlite3_result_text(context, zHex, n*2, sqlite3_free);
   92763   }
   92764 }
   92765 
   92766 /*
   92767 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
   92768 */
   92769 static void zeroblobFunc(
   92770   sqlite3_context *context,
   92771   int argc,
   92772   sqlite3_value **argv
   92773 ){
   92774   i64 n;
   92775   sqlite3 *db = sqlite3_context_db_handle(context);
   92776   assert( argc==1 );
   92777   UNUSED_PARAMETER(argc);
   92778   n = sqlite3_value_int64(argv[0]);
   92779   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
   92780   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
   92781   if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   92782     sqlite3_result_error_toobig(context);
   92783   }else{
   92784     sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
   92785   }
   92786 }
   92787 
   92788 /*
   92789 ** The replace() function.  Three arguments are all strings: call
   92790 ** them A, B, and C. The result is also a string which is derived
   92791 ** from A by replacing every occurrence of B with C.  The match
   92792 ** must be exact.  Collating sequences are not used.
   92793 */
   92794 static void replaceFunc(
   92795   sqlite3_context *context,
   92796   int argc,
   92797   sqlite3_value **argv
   92798 ){
   92799   const unsigned char *zStr;        /* The input string A */
   92800   const unsigned char *zPattern;    /* The pattern string B */
   92801   const unsigned char *zRep;        /* The replacement string C */
   92802   unsigned char *zOut;              /* The output */
   92803   int nStr;                /* Size of zStr */
   92804   int nPattern;            /* Size of zPattern */
   92805   int nRep;                /* Size of zRep */
   92806   i64 nOut;                /* Maximum size of zOut */
   92807   int loopLimit;           /* Last zStr[] that might match zPattern[] */
   92808   int i, j;                /* Loop counters */
   92809 
   92810   assert( argc==3 );
   92811   UNUSED_PARAMETER(argc);
   92812   zStr = sqlite3_value_text(argv[0]);
   92813   if( zStr==0 ) return;
   92814   nStr = sqlite3_value_bytes(argv[0]);
   92815   assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
   92816   zPattern = sqlite3_value_text(argv[1]);
   92817   if( zPattern==0 ){
   92818     assert( sqlite3_value_type(argv[1])==SQLITE_NULL
   92819             || sqlite3_context_db_handle(context)->mallocFailed );
   92820     return;
   92821   }
   92822   if( zPattern[0]==0 ){
   92823     assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
   92824     sqlite3_result_value(context, argv[0]);
   92825     return;
   92826   }
   92827   nPattern = sqlite3_value_bytes(argv[1]);
   92828   assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
   92829   zRep = sqlite3_value_text(argv[2]);
   92830   if( zRep==0 ) return;
   92831   nRep = sqlite3_value_bytes(argv[2]);
   92832   assert( zRep==sqlite3_value_text(argv[2]) );
   92833   nOut = nStr + 1;
   92834   assert( nOut<SQLITE_MAX_LENGTH );
   92835   zOut = contextMalloc(context, (i64)nOut);
   92836   if( zOut==0 ){
   92837     return;
   92838   }
   92839   loopLimit = nStr - nPattern;
   92840   for(i=j=0; i<=loopLimit; i++){
   92841     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
   92842       zOut[j++] = zStr[i];
   92843     }else{
   92844       u8 *zOld;
   92845       sqlite3 *db = sqlite3_context_db_handle(context);
   92846       nOut += nRep - nPattern;
   92847       testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
   92848       testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
   92849       if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   92850         sqlite3_result_error_toobig(context);
   92851         sqlite3_free(zOut);
   92852         return;
   92853       }
   92854       zOld = zOut;
   92855       zOut = sqlite3_realloc(zOut, (int)nOut);
   92856       if( zOut==0 ){
   92857         sqlite3_result_error_nomem(context);
   92858         sqlite3_free(zOld);
   92859         return;
   92860       }
   92861       memcpy(&zOut[j], zRep, nRep);
   92862       j += nRep;
   92863       i += nPattern-1;
   92864     }
   92865   }
   92866   assert( j+nStr-i+1==nOut );
   92867   memcpy(&zOut[j], &zStr[i], nStr-i);
   92868   j += nStr - i;
   92869   assert( j<=nOut );
   92870   zOut[j] = 0;
   92871   sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
   92872 }
   92873 
   92874 /*
   92875 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
   92876 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
   92877 */
   92878 static void trimFunc(
   92879   sqlite3_context *context,
   92880   int argc,
   92881   sqlite3_value **argv
   92882 ){
   92883   const unsigned char *zIn;         /* Input string */
   92884   const unsigned char *zCharSet;    /* Set of characters to trim */
   92885   int nIn;                          /* Number of bytes in input */
   92886   int flags;                        /* 1: trimleft  2: trimright  3: trim */
   92887   int i;                            /* Loop counter */
   92888   unsigned char *aLen = 0;          /* Length of each character in zCharSet */
   92889   unsigned char **azChar = 0;       /* Individual characters in zCharSet */
   92890   int nChar;                        /* Number of characters in zCharSet */
   92891 
   92892   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
   92893     return;
   92894   }
   92895   zIn = sqlite3_value_text(argv[0]);
   92896   if( zIn==0 ) return;
   92897   nIn = sqlite3_value_bytes(argv[0]);
   92898   assert( zIn==sqlite3_value_text(argv[0]) );
   92899   if( argc==1 ){
   92900     static const unsigned char lenOne[] = { 1 };
   92901     static unsigned char * const azOne[] = { (u8*)" " };
   92902     nChar = 1;
   92903     aLen = (u8*)lenOne;
   92904     azChar = (unsigned char **)azOne;
   92905     zCharSet = 0;
   92906   }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
   92907     return;
   92908   }else{
   92909     const unsigned char *z;
   92910     for(z=zCharSet, nChar=0; *z; nChar++){
   92911       SQLITE_SKIP_UTF8(z);
   92912     }
   92913     if( nChar>0 ){
   92914       azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
   92915       if( azChar==0 ){
   92916         return;
   92917       }
   92918       aLen = (unsigned char*)&azChar[nChar];
   92919       for(z=zCharSet, nChar=0; *z; nChar++){
   92920         azChar[nChar] = (unsigned char *)z;
   92921         SQLITE_SKIP_UTF8(z);
   92922         aLen[nChar] = (u8)(z - azChar[nChar]);
   92923       }
   92924     }
   92925   }
   92926   if( nChar>0 ){
   92927     flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
   92928     if( flags & 1 ){
   92929       while( nIn>0 ){
   92930         int len = 0;
   92931         for(i=0; i<nChar; i++){
   92932           len = aLen[i];
   92933           if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
   92934         }
   92935         if( i>=nChar ) break;
   92936         zIn += len;
   92937         nIn -= len;
   92938       }
   92939     }
   92940     if( flags & 2 ){
   92941       while( nIn>0 ){
   92942         int len = 0;
   92943         for(i=0; i<nChar; i++){
   92944           len = aLen[i];
   92945           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
   92946         }
   92947         if( i>=nChar ) break;
   92948         nIn -= len;
   92949       }
   92950     }
   92951     if( zCharSet ){
   92952       sqlite3_free(azChar);
   92953     }
   92954   }
   92955   sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
   92956 }
   92957 
   92958 
   92959 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
   92960 ** is only available if the SQLITE_SOUNDEX compile-time option is used
   92961 ** when SQLite is built.
   92962 */
   92963 #ifdef SQLITE_SOUNDEX
   92964 /*
   92965 ** Compute the soundex encoding of a word.
   92966 **
   92967 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
   92968 ** soundex encoding of the string X.
   92969 */
   92970 static void soundexFunc(
   92971   sqlite3_context *context,
   92972   int argc,
   92973   sqlite3_value **argv
   92974 ){
   92975   char zResult[8];
   92976   const u8 *zIn;
   92977   int i, j;
   92978   static const unsigned char iCode[] = {
   92979     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   92980     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   92981     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   92982     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   92983     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
   92984     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
   92985     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
   92986     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
   92987   };
   92988   assert( argc==1 );
   92989   zIn = (u8*)sqlite3_value_text(argv[0]);
   92990   if( zIn==0 ) zIn = (u8*)"";
   92991   for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
   92992   if( zIn[i] ){
   92993     u8 prevcode = iCode[zIn[i]&0x7f];
   92994     zResult[0] = sqlite3Toupper(zIn[i]);
   92995     for(j=1; j<4 && zIn[i]; i++){
   92996       int code = iCode[zIn[i]&0x7f];
   92997       if( code>0 ){
   92998         if( code!=prevcode ){
   92999           prevcode = code;
   93000           zResult[j++] = code + '0';
   93001         }
   93002       }else{
   93003         prevcode = 0;
   93004       }
   93005     }
   93006     while( j<4 ){
   93007       zResult[j++] = '0';
   93008     }
   93009     zResult[j] = 0;
   93010     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
   93011   }else{
   93012     /* IMP: R-64894-50321 The string "?000" is returned if the argument
   93013     ** is NULL or contains no ASCII alphabetic characters. */
   93014     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
   93015   }
   93016 }
   93017 #endif /* SQLITE_SOUNDEX */
   93018 
   93019 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   93020 /*
   93021 ** A function that loads a shared-library extension then returns NULL.
   93022 */
   93023 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
   93024   const char *zFile = (const char *)sqlite3_value_text(argv[0]);
   93025   const char *zProc;
   93026   sqlite3 *db = sqlite3_context_db_handle(context);
   93027   char *zErrMsg = 0;
   93028 
   93029   if( argc==2 ){
   93030     zProc = (const char *)sqlite3_value_text(argv[1]);
   93031   }else{
   93032     zProc = 0;
   93033   }
   93034   if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
   93035     sqlite3_result_error(context, zErrMsg, -1);
   93036     sqlite3_free(zErrMsg);
   93037   }
   93038 }
   93039 #endif
   93040 
   93041 
   93042 /*
   93043 ** An instance of the following structure holds the context of a
   93044 ** sum() or avg() aggregate computation.
   93045 */
   93046 typedef struct SumCtx SumCtx;
   93047 struct SumCtx {
   93048   double rSum;      /* Floating point sum */
   93049   i64 iSum;         /* Integer sum */
   93050   i64 cnt;          /* Number of elements summed */
   93051   u8 overflow;      /* True if integer overflow seen */
   93052   u8 approx;        /* True if non-integer value was input to the sum */
   93053 };
   93054 
   93055 /*
   93056 ** Routines used to compute the sum, average, and total.
   93057 **
   93058 ** The SUM() function follows the (broken) SQL standard which means
   93059 ** that it returns NULL if it sums over no inputs.  TOTAL returns
   93060 ** 0.0 in that case.  In addition, TOTAL always returns a float where
   93061 ** SUM might return an integer if it never encounters a floating point
   93062 ** value.  TOTAL never fails, but SUM might through an exception if
   93063 ** it overflows an integer.
   93064 */
   93065 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
   93066   SumCtx *p;
   93067   int type;
   93068   assert( argc==1 );
   93069   UNUSED_PARAMETER(argc);
   93070   p = sqlite3_aggregate_context(context, sizeof(*p));
   93071   type = sqlite3_value_numeric_type(argv[0]);
   93072   if( p && type!=SQLITE_NULL ){
   93073     p->cnt++;
   93074     if( type==SQLITE_INTEGER ){
   93075       i64 v = sqlite3_value_int64(argv[0]);
   93076       p->rSum += v;
   93077       if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
   93078         p->overflow = 1;
   93079       }
   93080     }else{
   93081       p->rSum += sqlite3_value_double(argv[0]);
   93082       p->approx = 1;
   93083     }
   93084   }
   93085 }
   93086 static void sumFinalize(sqlite3_context *context){
   93087   SumCtx *p;
   93088   p = sqlite3_aggregate_context(context, 0);
   93089   if( p && p->cnt>0 ){
   93090     if( p->overflow ){
   93091       sqlite3_result_error(context,"integer overflow",-1);
   93092     }else if( p->approx ){
   93093       sqlite3_result_double(context, p->rSum);
   93094     }else{
   93095       sqlite3_result_int64(context, p->iSum);
   93096     }
   93097   }
   93098 }
   93099 static void avgFinalize(sqlite3_context *context){
   93100   SumCtx *p;
   93101   p = sqlite3_aggregate_context(context, 0);
   93102   if( p && p->cnt>0 ){
   93103     sqlite3_result_double(context, p->rSum/(double)p->cnt);
   93104   }
   93105 }
   93106 static void totalFinalize(sqlite3_context *context){
   93107   SumCtx *p;
   93108   p = sqlite3_aggregate_context(context, 0);
   93109   /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
   93110   sqlite3_result_double(context, p ? p->rSum : (double)0);
   93111 }
   93112 
   93113 /*
   93114 ** The following structure keeps track of state information for the
   93115 ** count() aggregate function.
   93116 */
   93117 typedef struct CountCtx CountCtx;
   93118 struct CountCtx {
   93119   i64 n;
   93120 };
   93121 
   93122 /*
   93123 ** Routines to implement the count() aggregate function.
   93124 */
   93125 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
   93126   CountCtx *p;
   93127   p = sqlite3_aggregate_context(context, sizeof(*p));
   93128   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
   93129     p->n++;
   93130   }
   93131 
   93132 #ifndef SQLITE_OMIT_DEPRECATED
   93133   /* The sqlite3_aggregate_count() function is deprecated.  But just to make
   93134   ** sure it still operates correctly, verify that its count agrees with our
   93135   ** internal count when using count(*) and when the total count can be
   93136   ** expressed as a 32-bit integer. */
   93137   assert( argc==1 || p==0 || p->n>0x7fffffff
   93138           || p->n==sqlite3_aggregate_count(context) );
   93139 #endif
   93140 }
   93141 static void countFinalize(sqlite3_context *context){
   93142   CountCtx *p;
   93143   p = sqlite3_aggregate_context(context, 0);
   93144   sqlite3_result_int64(context, p ? p->n : 0);
   93145 }
   93146 
   93147 /*
   93148 ** Routines to implement min() and max() aggregate functions.
   93149 */
   93150 static void minmaxStep(
   93151   sqlite3_context *context,
   93152   int NotUsed,
   93153   sqlite3_value **argv
   93154 ){
   93155   Mem *pArg  = (Mem *)argv[0];
   93156   Mem *pBest;
   93157   UNUSED_PARAMETER(NotUsed);
   93158 
   93159   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
   93160   if( !pBest ) return;
   93161 
   93162   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
   93163     if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
   93164   }else if( pBest->flags ){
   93165     int max;
   93166     int cmp;
   93167     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
   93168     /* This step function is used for both the min() and max() aggregates,
   93169     ** the only difference between the two being that the sense of the
   93170     ** comparison is inverted. For the max() aggregate, the
   93171     ** sqlite3_user_data() function returns (void *)-1. For min() it
   93172     ** returns (void *)db, where db is the sqlite3* database pointer.
   93173     ** Therefore the next statement sets variable 'max' to 1 for the max()
   93174     ** aggregate, or 0 for min().
   93175     */
   93176     max = sqlite3_user_data(context)!=0;
   93177     cmp = sqlite3MemCompare(pBest, pArg, pColl);
   93178     if( (max && cmp<0) || (!max && cmp>0) ){
   93179       sqlite3VdbeMemCopy(pBest, pArg);
   93180     }else{
   93181       sqlite3SkipAccumulatorLoad(context);
   93182     }
   93183   }else{
   93184     sqlite3VdbeMemCopy(pBest, pArg);
   93185   }
   93186 }
   93187 static void minMaxFinalize(sqlite3_context *context){
   93188   sqlite3_value *pRes;
   93189   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
   93190   if( pRes ){
   93191     if( pRes->flags ){
   93192       sqlite3_result_value(context, pRes);
   93193     }
   93194     sqlite3VdbeMemRelease(pRes);
   93195   }
   93196 }
   93197 
   93198 /*
   93199 ** group_concat(EXPR, ?SEPARATOR?)
   93200 */
   93201 static void groupConcatStep(
   93202   sqlite3_context *context,
   93203   int argc,
   93204   sqlite3_value **argv
   93205 ){
   93206   const char *zVal;
   93207   StrAccum *pAccum;
   93208   const char *zSep;
   93209   int nVal, nSep;
   93210   assert( argc==1 || argc==2 );
   93211   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
   93212   pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
   93213 
   93214   if( pAccum ){
   93215     sqlite3 *db = sqlite3_context_db_handle(context);
   93216     int firstTerm = pAccum->useMalloc==0;
   93217     pAccum->useMalloc = 2;
   93218     pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
   93219     if( !firstTerm ){
   93220       if( argc==2 ){
   93221         zSep = (char*)sqlite3_value_text(argv[1]);
   93222         nSep = sqlite3_value_bytes(argv[1]);
   93223       }else{
   93224         zSep = ",";
   93225         nSep = 1;
   93226       }
   93227       if( nSep ) sqlite3StrAccumAppend(pAccum, zSep, nSep);
   93228     }
   93229     zVal = (char*)sqlite3_value_text(argv[0]);
   93230     nVal = sqlite3_value_bytes(argv[0]);
   93231     if( zVal ) sqlite3StrAccumAppend(pAccum, zVal, nVal);
   93232   }
   93233 }
   93234 static void groupConcatFinalize(sqlite3_context *context){
   93235   StrAccum *pAccum;
   93236   pAccum = sqlite3_aggregate_context(context, 0);
   93237   if( pAccum ){
   93238     if( pAccum->accError==STRACCUM_TOOBIG ){
   93239       sqlite3_result_error_toobig(context);
   93240     }else if( pAccum->accError==STRACCUM_NOMEM ){
   93241       sqlite3_result_error_nomem(context);
   93242     }else{
   93243       sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
   93244                           sqlite3_free);
   93245     }
   93246   }
   93247 }
   93248 
   93249 /*
   93250 ** This routine does per-connection function registration.  Most
   93251 ** of the built-in functions above are part of the global function set.
   93252 ** This routine only deals with those that are not global.
   93253 */
   93254 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
   93255   int rc = sqlite3_overload_function(db, "MATCH", 2);
   93256   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
   93257   if( rc==SQLITE_NOMEM ){
   93258     db->mallocFailed = 1;
   93259   }
   93260 }
   93261 
   93262 /*
   93263 ** Set the LIKEOPT flag on the 2-argument function with the given name.
   93264 */
   93265 static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
   93266   FuncDef *pDef;
   93267   pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
   93268                              2, SQLITE_UTF8, 0);
   93269   if( ALWAYS(pDef) ){
   93270     pDef->funcFlags |= flagVal;
   93271   }
   93272 }
   93273 
   93274 /*
   93275 ** Register the built-in LIKE and GLOB functions.  The caseSensitive
   93276 ** parameter determines whether or not the LIKE operator is case
   93277 ** sensitive.  GLOB is always case sensitive.
   93278 */
   93279 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
   93280   struct compareInfo *pInfo;
   93281   if( caseSensitive ){
   93282     pInfo = (struct compareInfo*)&likeInfoAlt;
   93283   }else{
   93284     pInfo = (struct compareInfo*)&likeInfoNorm;
   93285   }
   93286   sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
   93287   sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
   93288   sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
   93289       (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
   93290   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
   93291   setLikeOptFlag(db, "like",
   93292       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
   93293 }
   93294 
   93295 /*
   93296 ** pExpr points to an expression which implements a function.  If
   93297 ** it is appropriate to apply the LIKE optimization to that function
   93298 ** then set aWc[0] through aWc[2] to the wildcard characters and
   93299 ** return TRUE.  If the function is not a LIKE-style function then
   93300 ** return FALSE.
   93301 */
   93302 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
   93303   FuncDef *pDef;
   93304   if( pExpr->op!=TK_FUNCTION
   93305    || !pExpr->x.pList
   93306    || pExpr->x.pList->nExpr!=2
   93307   ){
   93308     return 0;
   93309   }
   93310   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   93311   pDef = sqlite3FindFunction(db, pExpr->u.zToken,
   93312                              sqlite3Strlen30(pExpr->u.zToken),
   93313                              2, SQLITE_UTF8, 0);
   93314   if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
   93315     return 0;
   93316   }
   93317 
   93318   /* The memcpy() statement assumes that the wildcard characters are
   93319   ** the first three statements in the compareInfo structure.  The
   93320   ** asserts() that follow verify that assumption
   93321   */
   93322   memcpy(aWc, pDef->pUserData, 3);
   93323   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
   93324   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
   93325   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
   93326   *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
   93327   return 1;
   93328 }
   93329 
   93330 /*
   93331 ** All all of the FuncDef structures in the aBuiltinFunc[] array above
   93332 ** to the global function hash table.  This occurs at start-time (as
   93333 ** a consequence of calling sqlite3_initialize()).
   93334 **
   93335 ** After this routine runs
   93336 */
   93337 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
   93338   /*
   93339   ** The following array holds FuncDef structures for all of the functions
   93340   ** defined in this file.
   93341   **
   93342   ** The array cannot be constant since changes are made to the
   93343   ** FuncDef.pHash elements at start-time.  The elements of this array
   93344   ** are read-only after initialization is complete.
   93345   */
   93346   static SQLITE_WSD FuncDef aBuiltinFunc[] = {
   93347     FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
   93348     FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
   93349     FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
   93350     FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
   93351     FUNCTION(trim,               1, 3, 0, trimFunc         ),
   93352     FUNCTION(trim,               2, 3, 0, trimFunc         ),
   93353     FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
   93354     FUNCTION(min,                0, 0, 1, 0                ),
   93355     AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
   93356     FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
   93357     FUNCTION(max,                0, 1, 1, 0                ),
   93358     AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
   93359     FUNCTION2(typeof,            1, 0, 0, typeofFunc,  SQLITE_FUNC_TYPEOF),
   93360     FUNCTION2(length,            1, 0, 0, lengthFunc,  SQLITE_FUNC_LENGTH),
   93361     FUNCTION(instr,              2, 0, 0, instrFunc        ),
   93362     FUNCTION(substr,             2, 0, 0, substrFunc       ),
   93363     FUNCTION(substr,             3, 0, 0, substrFunc       ),
   93364     FUNCTION(printf,            -1, 0, 0, printfFunc       ),
   93365     FUNCTION(unicode,            1, 0, 0, unicodeFunc      ),
   93366     FUNCTION(char,              -1, 0, 0, charFunc         ),
   93367     FUNCTION(abs,                1, 0, 0, absFunc          ),
   93368 #ifndef SQLITE_OMIT_FLOATING_POINT
   93369     FUNCTION(round,              1, 0, 0, roundFunc        ),
   93370     FUNCTION(round,              2, 0, 0, roundFunc        ),
   93371 #endif
   93372     FUNCTION(upper,              1, 0, 0, upperFunc        ),
   93373     FUNCTION(lower,              1, 0, 0, lowerFunc        ),
   93374     FUNCTION(coalesce,           1, 0, 0, 0                ),
   93375     FUNCTION(coalesce,           0, 0, 0, 0                ),
   93376     FUNCTION2(coalesce,         -1, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
   93377     FUNCTION(hex,                1, 0, 0, hexFunc          ),
   93378     FUNCTION2(ifnull,            2, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
   93379     FUNCTION2(unlikely,          1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
   93380     FUNCTION2(likelihood,        2, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
   93381     FUNCTION2(likely,            1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
   93382     VFUNCTION(random,            0, 0, 0, randomFunc       ),
   93383     VFUNCTION(randomblob,        1, 0, 0, randomBlob       ),
   93384     FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
   93385     FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
   93386     FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),
   93387     FUNCTION(sqlite_log,         2, 0, 0, errlogFunc       ),
   93388 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
   93389     FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
   93390     FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
   93391 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
   93392     FUNCTION(quote,              1, 0, 0, quoteFunc        ),
   93393     VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
   93394     VFUNCTION(changes,           0, 0, 0, changes          ),
   93395     VFUNCTION(total_changes,     0, 0, 0, total_changes    ),
   93396     FUNCTION(replace,            3, 0, 0, replaceFunc      ),
   93397     FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
   93398   #ifdef SQLITE_SOUNDEX
   93399     FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
   93400   #endif
   93401   #ifndef SQLITE_OMIT_LOAD_EXTENSION
   93402     FUNCTION(load_extension,     1, 0, 0, loadExt          ),
   93403     FUNCTION(load_extension,     2, 0, 0, loadExt          ),
   93404   #endif
   93405     AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
   93406     AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
   93407     AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
   93408  /* AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ), */
   93409     {0,SQLITE_UTF8|SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
   93410     AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
   93411     AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
   93412     AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
   93413 
   93414     LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
   93415   #ifdef SQLITE_CASE_SENSITIVE_LIKE
   93416     LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
   93417     LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
   93418   #else
   93419     LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
   93420     LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
   93421   #endif
   93422   };
   93423 
   93424   int i;
   93425   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
   93426   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
   93427 
   93428   for(i=0; i<ArraySize(aBuiltinFunc); i++){
   93429     sqlite3FuncDefInsert(pHash, &aFunc[i]);
   93430   }
   93431   sqlite3RegisterDateTimeFunctions();
   93432 #ifndef SQLITE_OMIT_ALTERTABLE
   93433   sqlite3AlterFunctions();
   93434 #endif
   93435 #if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
   93436   sqlite3AnalyzeFunctions();
   93437 #endif
   93438 }
   93439 
   93440 /************** End of func.c ************************************************/
   93441 /************** Begin file fkey.c ********************************************/
   93442 /*
   93443 **
   93444 ** The author disclaims copyright to this source code.  In place of
   93445 ** a legal notice, here is a blessing:
   93446 **
   93447 **    May you do good and not evil.
   93448 **    May you find forgiveness for yourself and forgive others.
   93449 **    May you share freely, never taking more than you give.
   93450 **
   93451 *************************************************************************
   93452 ** This file contains code used by the compiler to add foreign key
   93453 ** support to compiled SQL statements.
   93454 */
   93455 
   93456 #ifndef SQLITE_OMIT_FOREIGN_KEY
   93457 #ifndef SQLITE_OMIT_TRIGGER
   93458 
   93459 /*
   93460 ** Deferred and Immediate FKs
   93461 ** --------------------------
   93462 **
   93463 ** Foreign keys in SQLite come in two flavours: deferred and immediate.
   93464 ** If an immediate foreign key constraint is violated,
   93465 ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
   93466 ** statement transaction rolled back. If a
   93467 ** deferred foreign key constraint is violated, no action is taken
   93468 ** immediately. However if the application attempts to commit the
   93469 ** transaction before fixing the constraint violation, the attempt fails.
   93470 **
   93471 ** Deferred constraints are implemented using a simple counter associated
   93472 ** with the database handle. The counter is set to zero each time a
   93473 ** database transaction is opened. Each time a statement is executed
   93474 ** that causes a foreign key violation, the counter is incremented. Each
   93475 ** time a statement is executed that removes an existing violation from
   93476 ** the database, the counter is decremented. When the transaction is
   93477 ** committed, the commit fails if the current value of the counter is
   93478 ** greater than zero. This scheme has two big drawbacks:
   93479 **
   93480 **   * When a commit fails due to a deferred foreign key constraint,
   93481 **     there is no way to tell which foreign constraint is not satisfied,
   93482 **     or which row it is not satisfied for.
   93483 **
   93484 **   * If the database contains foreign key violations when the
   93485 **     transaction is opened, this may cause the mechanism to malfunction.
   93486 **
   93487 ** Despite these problems, this approach is adopted as it seems simpler
   93488 ** than the alternatives.
   93489 **
   93490 ** INSERT operations:
   93491 **
   93492 **   I.1) For each FK for which the table is the child table, search
   93493 **        the parent table for a match. If none is found increment the
   93494 **        constraint counter.
   93495 **
   93496 **   I.2) For each FK for which the table is the parent table,
   93497 **        search the child table for rows that correspond to the new
   93498 **        row in the parent table. Decrement the counter for each row
   93499 **        found (as the constraint is now satisfied).
   93500 **
   93501 ** DELETE operations:
   93502 **
   93503 **   D.1) For each FK for which the table is the child table,
   93504 **        search the parent table for a row that corresponds to the
   93505 **        deleted row in the child table. If such a row is not found,
   93506 **        decrement the counter.
   93507 **
   93508 **   D.2) For each FK for which the table is the parent table, search
   93509 **        the child table for rows that correspond to the deleted row
   93510 **        in the parent table. For each found increment the counter.
   93511 **
   93512 ** UPDATE operations:
   93513 **
   93514 **   An UPDATE command requires that all 4 steps above are taken, but only
   93515 **   for FK constraints for which the affected columns are actually
   93516 **   modified (values must be compared at runtime).
   93517 **
   93518 ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
   93519 ** This simplifies the implementation a bit.
   93520 **
   93521 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
   93522 ** resolution is considered to delete rows before the new row is inserted.
   93523 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
   93524 ** is thrown, even if the FK constraint would be satisfied after the new
   93525 ** row is inserted.
   93526 **
   93527 ** Immediate constraints are usually handled similarly. The only difference
   93528 ** is that the counter used is stored as part of each individual statement
   93529 ** object (struct Vdbe). If, after the statement has run, its immediate
   93530 ** constraint counter is greater than zero,
   93531 ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
   93532 ** and the statement transaction is rolled back. An exception is an INSERT
   93533 ** statement that inserts a single row only (no triggers). In this case,
   93534 ** instead of using a counter, an exception is thrown immediately if the
   93535 ** INSERT violates a foreign key constraint. This is necessary as such
   93536 ** an INSERT does not open a statement transaction.
   93537 **
   93538 ** TODO: How should dropping a table be handled? How should renaming a
   93539 ** table be handled?
   93540 **
   93541 **
   93542 ** Query API Notes
   93543 ** ---------------
   93544 **
   93545 ** Before coding an UPDATE or DELETE row operation, the code-generator
   93546 ** for those two operations needs to know whether or not the operation
   93547 ** requires any FK processing and, if so, which columns of the original
   93548 ** row are required by the FK processing VDBE code (i.e. if FKs were
   93549 ** implemented using triggers, which of the old.* columns would be
   93550 ** accessed). No information is required by the code-generator before
   93551 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
   93552 ** generation code to query for this information are:
   93553 **
   93554 **   sqlite3FkRequired() - Test to see if FK processing is required.
   93555 **   sqlite3FkOldmask()  - Query for the set of required old.* columns.
   93556 **
   93557 **
   93558 ** Externally accessible module functions
   93559 ** --------------------------------------
   93560 **
   93561 **   sqlite3FkCheck()    - Check for foreign key violations.
   93562 **   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
   93563 **   sqlite3FkDelete()   - Delete an FKey structure.
   93564 */
   93565 
   93566 /*
   93567 ** VDBE Calling Convention
   93568 ** -----------------------
   93569 **
   93570 ** Example:
   93571 **
   93572 **   For the following INSERT statement:
   93573 **
   93574 **     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
   93575 **     INSERT INTO t1 VALUES(1, 2, 3.1);
   93576 **
   93577 **   Register (x):        2    (type integer)
   93578 **   Register (x+1):      1    (type integer)
   93579 **   Register (x+2):      NULL (type NULL)
   93580 **   Register (x+3):      3.1  (type real)
   93581 */
   93582 
   93583 /*
   93584 ** A foreign key constraint requires that the key columns in the parent
   93585 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
   93586 ** Given that pParent is the parent table for foreign key constraint pFKey,
   93587 ** search the schema for a unique index on the parent key columns.
   93588 **
   93589 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
   93590 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
   93591 ** is set to point to the unique index.
   93592 **
   93593 ** If the parent key consists of a single column (the foreign key constraint
   93594 ** is not a composite foreign key), output variable *paiCol is set to NULL.
   93595 ** Otherwise, it is set to point to an allocated array of size N, where
   93596 ** N is the number of columns in the parent key. The first element of the
   93597 ** array is the index of the child table column that is mapped by the FK
   93598 ** constraint to the parent table column stored in the left-most column
   93599 ** of index *ppIdx. The second element of the array is the index of the
   93600 ** child table column that corresponds to the second left-most column of
   93601 ** *ppIdx, and so on.
   93602 **
   93603 ** If the required index cannot be found, either because:
   93604 **
   93605 **   1) The named parent key columns do not exist, or
   93606 **
   93607 **   2) The named parent key columns do exist, but are not subject to a
   93608 **      UNIQUE or PRIMARY KEY constraint, or
   93609 **
   93610 **   3) No parent key columns were provided explicitly as part of the
   93611 **      foreign key definition, and the parent table does not have a
   93612 **      PRIMARY KEY, or
   93613 **
   93614 **   4) No parent key columns were provided explicitly as part of the
   93615 **      foreign key definition, and the PRIMARY KEY of the parent table
   93616 **      consists of a a different number of columns to the child key in
   93617 **      the child table.
   93618 **
   93619 ** then non-zero is returned, and a "foreign key mismatch" error loaded
   93620 ** into pParse. If an OOM error occurs, non-zero is returned and the
   93621 ** pParse->db->mallocFailed flag is set.
   93622 */
   93623 SQLITE_PRIVATE int sqlite3FkLocateIndex(
   93624   Parse *pParse,                  /* Parse context to store any error in */
   93625   Table *pParent,                 /* Parent table of FK constraint pFKey */
   93626   FKey *pFKey,                    /* Foreign key to find index for */
   93627   Index **ppIdx,                  /* OUT: Unique index on parent table */
   93628   int **paiCol                    /* OUT: Map of index columns in pFKey */
   93629 ){
   93630   Index *pIdx = 0;                    /* Value to return via *ppIdx */
   93631   int *aiCol = 0;                     /* Value to return via *paiCol */
   93632   int nCol = pFKey->nCol;             /* Number of columns in parent key */
   93633   char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
   93634 
   93635   /* The caller is responsible for zeroing output parameters. */
   93636   assert( ppIdx && *ppIdx==0 );
   93637   assert( !paiCol || *paiCol==0 );
   93638   assert( pParse );
   93639 
   93640   /* If this is a non-composite (single column) foreign key, check if it
   93641   ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
   93642   ** and *paiCol set to zero and return early.
   93643   **
   93644   ** Otherwise, for a composite foreign key (more than one column), allocate
   93645   ** space for the aiCol array (returned via output parameter *paiCol).
   93646   ** Non-composite foreign keys do not require the aiCol array.
   93647   */
   93648   if( nCol==1 ){
   93649     /* The FK maps to the IPK if any of the following are true:
   93650     **
   93651     **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
   93652     **      mapped to the primary key of table pParent, or
   93653     **   2) The FK is explicitly mapped to a column declared as INTEGER
   93654     **      PRIMARY KEY.
   93655     */
   93656     if( pParent->iPKey>=0 ){
   93657       if( !zKey ) return 0;
   93658       if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
   93659     }
   93660   }else if( paiCol ){
   93661     assert( nCol>1 );
   93662     aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
   93663     if( !aiCol ) return 1;
   93664     *paiCol = aiCol;
   93665   }
   93666 
   93667   for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
   93668     if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) ){
   93669       /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
   93670       ** of columns. If each indexed column corresponds to a foreign key
   93671       ** column of pFKey, then this index is a winner.  */
   93672 
   93673       if( zKey==0 ){
   93674         /* If zKey is NULL, then this foreign key is implicitly mapped to
   93675         ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
   93676         ** identified by the test.  */
   93677         if( IsPrimaryKeyIndex(pIdx) ){
   93678           if( aiCol ){
   93679             int i;
   93680             for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
   93681           }
   93682           break;
   93683         }
   93684       }else{
   93685         /* If zKey is non-NULL, then this foreign key was declared to
   93686         ** map to an explicit list of columns in table pParent. Check if this
   93687         ** index matches those columns. Also, check that the index uses
   93688         ** the default collation sequences for each column. */
   93689         int i, j;
   93690         for(i=0; i<nCol; i++){
   93691           i16 iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
   93692           char *zDfltColl;                  /* Def. collation for column */
   93693           char *zIdxCol;                    /* Name of indexed column */
   93694 
   93695           /* If the index uses a collation sequence that is different from
   93696           ** the default collation sequence for the column, this index is
   93697           ** unusable. Bail out early in this case.  */
   93698           zDfltColl = pParent->aCol[iCol].zColl;
   93699           if( !zDfltColl ){
   93700             zDfltColl = "BINARY";
   93701           }
   93702           if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
   93703 
   93704           zIdxCol = pParent->aCol[iCol].zName;
   93705           for(j=0; j<nCol; j++){
   93706             if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
   93707               if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
   93708               break;
   93709             }
   93710           }
   93711           if( j==nCol ) break;
   93712         }
   93713         if( i==nCol ) break;      /* pIdx is usable */
   93714       }
   93715     }
   93716   }
   93717 
   93718   if( !pIdx ){
   93719     if( !pParse->disableTriggers ){
   93720       sqlite3ErrorMsg(pParse,
   93721            "foreign key mismatch - \"%w\" referencing \"%w\"",
   93722            pFKey->pFrom->zName, pFKey->zTo);
   93723     }
   93724     sqlite3DbFree(pParse->db, aiCol);
   93725     return 1;
   93726   }
   93727 
   93728   *ppIdx = pIdx;
   93729   return 0;
   93730 }
   93731 
   93732 /*
   93733 ** This function is called when a row is inserted into or deleted from the
   93734 ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
   93735 ** on the child table of pFKey, this function is invoked twice for each row
   93736 ** affected - once to "delete" the old row, and then again to "insert" the
   93737 ** new row.
   93738 **
   93739 ** Each time it is called, this function generates VDBE code to locate the
   93740 ** row in the parent table that corresponds to the row being inserted into
   93741 ** or deleted from the child table. If the parent row can be found, no
   93742 ** special action is taken. Otherwise, if the parent row can *not* be
   93743 ** found in the parent table:
   93744 **
   93745 **   Operation | FK type   | Action taken
   93746 **   --------------------------------------------------------------------------
   93747 **   INSERT      immediate   Increment the "immediate constraint counter".
   93748 **
   93749 **   DELETE      immediate   Decrement the "immediate constraint counter".
   93750 **
   93751 **   INSERT      deferred    Increment the "deferred constraint counter".
   93752 **
   93753 **   DELETE      deferred    Decrement the "deferred constraint counter".
   93754 **
   93755 ** These operations are identified in the comment at the top of this file
   93756 ** (fkey.c) as "I.1" and "D.1".
   93757 */
   93758 static void fkLookupParent(
   93759   Parse *pParse,        /* Parse context */
   93760   int iDb,              /* Index of database housing pTab */
   93761   Table *pTab,          /* Parent table of FK pFKey */
   93762   Index *pIdx,          /* Unique index on parent key columns in pTab */
   93763   FKey *pFKey,          /* Foreign key constraint */
   93764   int *aiCol,           /* Map from parent key columns to child table columns */
   93765   int regData,          /* Address of array containing child table row */
   93766   int nIncr,            /* Increment constraint counter by this */
   93767   int isIgnore          /* If true, pretend pTab contains all NULL values */
   93768 ){
   93769   int i;                                    /* Iterator variable */
   93770   Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
   93771   int iCur = pParse->nTab - 1;              /* Cursor number to use */
   93772   int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
   93773 
   93774   /* If nIncr is less than zero, then check at runtime if there are any
   93775   ** outstanding constraints to resolve. If there are not, there is no need
   93776   ** to check if deleting this row resolves any outstanding violations.
   93777   **
   93778   ** Check if any of the key columns in the child table row are NULL. If
   93779   ** any are, then the constraint is considered satisfied. No need to
   93780   ** search for a matching row in the parent table.  */
   93781   if( nIncr<0 ){
   93782     sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
   93783     VdbeCoverage(v);
   93784   }
   93785   for(i=0; i<pFKey->nCol; i++){
   93786     int iReg = aiCol[i] + regData + 1;
   93787     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
   93788   }
   93789 
   93790   if( isIgnore==0 ){
   93791     if( pIdx==0 ){
   93792       /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
   93793       ** column of the parent table (table pTab).  */
   93794       int iMustBeInt;               /* Address of MustBeInt instruction */
   93795       int regTemp = sqlite3GetTempReg(pParse);
   93796 
   93797       /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
   93798       ** apply the affinity of the parent key). If this fails, then there
   93799       ** is no matching parent key. Before using MustBeInt, make a copy of
   93800       ** the value. Otherwise, the value inserted into the child key column
   93801       ** will have INTEGER affinity applied to it, which may not be correct.  */
   93802       sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
   93803       iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
   93804       VdbeCoverage(v);
   93805 
   93806       /* If the parent table is the same as the child table, and we are about
   93807       ** to increment the constraint-counter (i.e. this is an INSERT operation),
   93808       ** then check if the row being inserted matches itself. If so, do not
   93809       ** increment the constraint-counter.  */
   93810       if( pTab==pFKey->pFrom && nIncr==1 ){
   93811         sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
   93812         sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
   93813       }
   93814 
   93815       sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
   93816       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
   93817       sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
   93818       sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
   93819       sqlite3VdbeJumpHere(v, iMustBeInt);
   93820       sqlite3ReleaseTempReg(pParse, regTemp);
   93821     }else{
   93822       int nCol = pFKey->nCol;
   93823       int regTemp = sqlite3GetTempRange(pParse, nCol);
   93824       int regRec = sqlite3GetTempReg(pParse);
   93825 
   93826       sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
   93827       sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
   93828       for(i=0; i<nCol; i++){
   93829         sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
   93830       }
   93831 
   93832       /* If the parent table is the same as the child table, and we are about
   93833       ** to increment the constraint-counter (i.e. this is an INSERT operation),
   93834       ** then check if the row being inserted matches itself. If so, do not
   93835       ** increment the constraint-counter.
   93836       **
   93837       ** If any of the parent-key values are NULL, then the row cannot match
   93838       ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
   93839       ** of the parent-key values are NULL (at this point it is known that
   93840       ** none of the child key values are).
   93841       */
   93842       if( pTab==pFKey->pFrom && nIncr==1 ){
   93843         int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
   93844         for(i=0; i<nCol; i++){
   93845           int iChild = aiCol[i]+1+regData;
   93846           int iParent = pIdx->aiColumn[i]+1+regData;
   93847           assert( aiCol[i]!=pTab->iPKey );
   93848           if( pIdx->aiColumn[i]==pTab->iPKey ){
   93849             /* The parent key is a composite key that includes the IPK column */
   93850             iParent = regData;
   93851           }
   93852           sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
   93853           sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
   93854         }
   93855         sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
   93856       }
   93857 
   93858       sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
   93859                         sqlite3IndexAffinityStr(v,pIdx), nCol);
   93860       sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
   93861 
   93862       sqlite3ReleaseTempReg(pParse, regRec);
   93863       sqlite3ReleaseTempRange(pParse, regTemp, nCol);
   93864     }
   93865   }
   93866 
   93867   if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
   93868    && !pParse->pToplevel
   93869    && !pParse->isMultiWrite
   93870   ){
   93871     /* Special case: If this is an INSERT statement that will insert exactly
   93872     ** one row into the table, raise a constraint immediately instead of
   93873     ** incrementing a counter. This is necessary as the VM code is being
   93874     ** generated for will not open a statement transaction.  */
   93875     assert( nIncr==1 );
   93876     sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
   93877         OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
   93878   }else{
   93879     if( nIncr>0 && pFKey->isDeferred==0 ){
   93880       sqlite3ParseToplevel(pParse)->mayAbort = 1;
   93881     }
   93882     sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
   93883   }
   93884 
   93885   sqlite3VdbeResolveLabel(v, iOk);
   93886   sqlite3VdbeAddOp1(v, OP_Close, iCur);
   93887 }
   93888 
   93889 
   93890 /*
   93891 ** Return an Expr object that refers to a memory register corresponding
   93892 ** to column iCol of table pTab.
   93893 **
   93894 ** regBase is the first of an array of register that contains the data
   93895 ** for pTab.  regBase itself holds the rowid.  regBase+1 holds the first
   93896 ** column.  regBase+2 holds the second column, and so forth.
   93897 */
   93898 static Expr *exprTableRegister(
   93899   Parse *pParse,     /* Parsing and code generating context */
   93900   Table *pTab,       /* The table whose content is at r[regBase]... */
   93901   int regBase,       /* Contents of table pTab */
   93902   i16 iCol           /* Which column of pTab is desired */
   93903 ){
   93904   Expr *pExpr;
   93905   Column *pCol;
   93906   const char *zColl;
   93907   sqlite3 *db = pParse->db;
   93908 
   93909   pExpr = sqlite3Expr(db, TK_REGISTER, 0);
   93910   if( pExpr ){
   93911     if( iCol>=0 && iCol!=pTab->iPKey ){
   93912       pCol = &pTab->aCol[iCol];
   93913       pExpr->iTable = regBase + iCol + 1;
   93914       pExpr->affinity = pCol->affinity;
   93915       zColl = pCol->zColl;
   93916       if( zColl==0 ) zColl = db->pDfltColl->zName;
   93917       pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
   93918     }else{
   93919       pExpr->iTable = regBase;
   93920       pExpr->affinity = SQLITE_AFF_INTEGER;
   93921     }
   93922   }
   93923   return pExpr;
   93924 }
   93925 
   93926 /*
   93927 ** Return an Expr object that refers to column iCol of table pTab which
   93928 ** has cursor iCur.
   93929 */
   93930 static Expr *exprTableColumn(
   93931   sqlite3 *db,      /* The database connection */
   93932   Table *pTab,      /* The table whose column is desired */
   93933   int iCursor,      /* The open cursor on the table */
   93934   i16 iCol          /* The column that is wanted */
   93935 ){
   93936   Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
   93937   if( pExpr ){
   93938     pExpr->pTab = pTab;
   93939     pExpr->iTable = iCursor;
   93940     pExpr->iColumn = iCol;
   93941   }
   93942   return pExpr;
   93943 }
   93944 
   93945 /*
   93946 ** This function is called to generate code executed when a row is deleted
   93947 ** from the parent table of foreign key constraint pFKey and, if pFKey is
   93948 ** deferred, when a row is inserted into the same table. When generating
   93949 ** code for an SQL UPDATE operation, this function may be called twice -
   93950 ** once to "delete" the old row and once to "insert" the new row.
   93951 **
   93952 ** The code generated by this function scans through the rows in the child
   93953 ** table that correspond to the parent table row being deleted or inserted.
   93954 ** For each child row found, one of the following actions is taken:
   93955 **
   93956 **   Operation | FK type   | Action taken
   93957 **   --------------------------------------------------------------------------
   93958 **   DELETE      immediate   Increment the "immediate constraint counter".
   93959 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
   93960 **                           throw a "FOREIGN KEY constraint failed" exception.
   93961 **
   93962 **   INSERT      immediate   Decrement the "immediate constraint counter".
   93963 **
   93964 **   DELETE      deferred    Increment the "deferred constraint counter".
   93965 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
   93966 **                           throw a "FOREIGN KEY constraint failed" exception.
   93967 **
   93968 **   INSERT      deferred    Decrement the "deferred constraint counter".
   93969 **
   93970 ** These operations are identified in the comment at the top of this file
   93971 ** (fkey.c) as "I.2" and "D.2".
   93972 */
   93973 static void fkScanChildren(
   93974   Parse *pParse,                  /* Parse context */
   93975   SrcList *pSrc,                  /* The child table to be scanned */
   93976   Table *pTab,                    /* The parent table */
   93977   Index *pIdx,                    /* Index on parent covering the foreign key */
   93978   FKey *pFKey,                    /* The foreign key linking pSrc to pTab */
   93979   int *aiCol,                     /* Map from pIdx cols to child table cols */
   93980   int regData,                    /* Parent row data starts here */
   93981   int nIncr                       /* Amount to increment deferred counter by */
   93982 ){
   93983   sqlite3 *db = pParse->db;       /* Database handle */
   93984   int i;                          /* Iterator variable */
   93985   Expr *pWhere = 0;               /* WHERE clause to scan with */
   93986   NameContext sNameContext;       /* Context used to resolve WHERE clause */
   93987   WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
   93988   int iFkIfZero = 0;              /* Address of OP_FkIfZero */
   93989   Vdbe *v = sqlite3GetVdbe(pParse);
   93990 
   93991   assert( pIdx==0 || pIdx->pTable==pTab );
   93992   assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
   93993   assert( pIdx!=0 || pFKey->nCol==1 );
   93994   assert( pIdx!=0 || HasRowid(pTab) );
   93995 
   93996   if( nIncr<0 ){
   93997     iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
   93998     VdbeCoverage(v);
   93999   }
   94000 
   94001   /* Create an Expr object representing an SQL expression like:
   94002   **
   94003   **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
   94004   **
   94005   ** The collation sequence used for the comparison should be that of
   94006   ** the parent key columns. The affinity of the parent key column should
   94007   ** be applied to each child key value before the comparison takes place.
   94008   */
   94009   for(i=0; i<pFKey->nCol; i++){
   94010     Expr *pLeft;                  /* Value from parent table row */
   94011     Expr *pRight;                 /* Column ref to child table */
   94012     Expr *pEq;                    /* Expression (pLeft = pRight) */
   94013     i16 iCol;                     /* Index of column in child table */
   94014     const char *zCol;             /* Name of column in child table */
   94015 
   94016     iCol = pIdx ? pIdx->aiColumn[i] : -1;
   94017     pLeft = exprTableRegister(pParse, pTab, regData, iCol);
   94018     iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
   94019     assert( iCol>=0 );
   94020     zCol = pFKey->pFrom->aCol[iCol].zName;
   94021     pRight = sqlite3Expr(db, TK_ID, zCol);
   94022     pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
   94023     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
   94024   }
   94025 
   94026   /* If the child table is the same as the parent table, then add terms
   94027   ** to the WHERE clause that prevent this entry from being scanned.
   94028   ** The added WHERE clause terms are like this:
   94029   **
   94030   **     $current_rowid!=rowid
   94031   **     NOT( $current_a==a AND $current_b==b AND ... )
   94032   **
   94033   ** The first form is used for rowid tables.  The second form is used
   94034   ** for WITHOUT ROWID tables.  In the second form, the primary key is
   94035   ** (a,b,...)
   94036   */
   94037   if( pTab==pFKey->pFrom && nIncr>0 ){
   94038     Expr *pNe;                    /* Expression (pLeft != pRight) */
   94039     Expr *pLeft;                  /* Value from parent table row */
   94040     Expr *pRight;                 /* Column ref to child table */
   94041     if( HasRowid(pTab) ){
   94042       pLeft = exprTableRegister(pParse, pTab, regData, -1);
   94043       pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
   94044       pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
   94045     }else{
   94046       Expr *pEq, *pAll = 0;
   94047       Index *pPk = sqlite3PrimaryKeyIndex(pTab);
   94048       assert( pIdx!=0 );
   94049       for(i=0; i<pPk->nKeyCol; i++){
   94050         i16 iCol = pIdx->aiColumn[i];
   94051         pLeft = exprTableRegister(pParse, pTab, regData, iCol);
   94052         pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, iCol);
   94053         pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
   94054         pAll = sqlite3ExprAnd(db, pAll, pEq);
   94055       }
   94056       pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0, 0);
   94057     }
   94058     pWhere = sqlite3ExprAnd(db, pWhere, pNe);
   94059   }
   94060 
   94061   /* Resolve the references in the WHERE clause. */
   94062   memset(&sNameContext, 0, sizeof(NameContext));
   94063   sNameContext.pSrcList = pSrc;
   94064   sNameContext.pParse = pParse;
   94065   sqlite3ResolveExprNames(&sNameContext, pWhere);
   94066 
   94067   /* Create VDBE to loop through the entries in pSrc that match the WHERE
   94068   ** clause. If the constraint is not deferred, throw an exception for
   94069   ** each row found. Otherwise, for deferred constraints, increment the
   94070   ** deferred constraint counter by nIncr for each row selected.  */
   94071   pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
   94072   if( nIncr>0 && pFKey->isDeferred==0 ){
   94073     sqlite3ParseToplevel(pParse)->mayAbort = 1;
   94074   }
   94075   sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
   94076   if( pWInfo ){
   94077     sqlite3WhereEnd(pWInfo);
   94078   }
   94079 
   94080   /* Clean up the WHERE clause constructed above. */
   94081   sqlite3ExprDelete(db, pWhere);
   94082   if( iFkIfZero ){
   94083     sqlite3VdbeJumpHere(v, iFkIfZero);
   94084   }
   94085 }
   94086 
   94087 /*
   94088 ** This function returns a linked list of FKey objects (connected by
   94089 ** FKey.pNextTo) holding all children of table pTab.  For example,
   94090 ** given the following schema:
   94091 **
   94092 **   CREATE TABLE t1(a PRIMARY KEY);
   94093 **   CREATE TABLE t2(b REFERENCES t1(a);
   94094 **
   94095 ** Calling this function with table "t1" as an argument returns a pointer
   94096 ** to the FKey structure representing the foreign key constraint on table
   94097 ** "t2". Calling this function with "t2" as the argument would return a
   94098 ** NULL pointer (as there are no FK constraints for which t2 is the parent
   94099 ** table).
   94100 */
   94101 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
   94102   int nName = sqlite3Strlen30(pTab->zName);
   94103   return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
   94104 }
   94105 
   94106 /*
   94107 ** The second argument is a Trigger structure allocated by the
   94108 ** fkActionTrigger() routine. This function deletes the Trigger structure
   94109 ** and all of its sub-components.
   94110 **
   94111 ** The Trigger structure or any of its sub-components may be allocated from
   94112 ** the lookaside buffer belonging to database handle dbMem.
   94113 */
   94114 static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
   94115   if( p ){
   94116     TriggerStep *pStep = p->step_list;
   94117     sqlite3ExprDelete(dbMem, pStep->pWhere);
   94118     sqlite3ExprListDelete(dbMem, pStep->pExprList);
   94119     sqlite3SelectDelete(dbMem, pStep->pSelect);
   94120     sqlite3ExprDelete(dbMem, p->pWhen);
   94121     sqlite3DbFree(dbMem, p);
   94122   }
   94123 }
   94124 
   94125 /*
   94126 ** This function is called to generate code that runs when table pTab is
   94127 ** being dropped from the database. The SrcList passed as the second argument
   94128 ** to this function contains a single entry guaranteed to resolve to
   94129 ** table pTab.
   94130 **
   94131 ** Normally, no code is required. However, if either
   94132 **
   94133 **   (a) The table is the parent table of a FK constraint, or
   94134 **   (b) The table is the child table of a deferred FK constraint and it is
   94135 **       determined at runtime that there are outstanding deferred FK
   94136 **       constraint violations in the database,
   94137 **
   94138 ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
   94139 ** the table from the database. Triggers are disabled while running this
   94140 ** DELETE, but foreign key actions are not.
   94141 */
   94142 SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
   94143   sqlite3 *db = pParse->db;
   94144   if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
   94145     int iSkip = 0;
   94146     Vdbe *v = sqlite3GetVdbe(pParse);
   94147 
   94148     assert( v );                  /* VDBE has already been allocated */
   94149     if( sqlite3FkReferences(pTab)==0 ){
   94150       /* Search for a deferred foreign key constraint for which this table
   94151       ** is the child table. If one cannot be found, return without
   94152       ** generating any VDBE code. If one can be found, then jump over
   94153       ** the entire DELETE if there are no outstanding deferred constraints
   94154       ** when this statement is run.  */
   94155       FKey *p;
   94156       for(p=pTab->pFKey; p; p=p->pNextFrom){
   94157         if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
   94158       }
   94159       if( !p ) return;
   94160       iSkip = sqlite3VdbeMakeLabel(v);
   94161       sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
   94162     }
   94163 
   94164     pParse->disableTriggers = 1;
   94165     sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
   94166     pParse->disableTriggers = 0;
   94167 
   94168     /* If the DELETE has generated immediate foreign key constraint
   94169     ** violations, halt the VDBE and return an error at this point, before
   94170     ** any modifications to the schema are made. This is because statement
   94171     ** transactions are not able to rollback schema changes.
   94172     **
   94173     ** If the SQLITE_DeferFKs flag is set, then this is not required, as
   94174     ** the statement transaction will not be rolled back even if FK
   94175     ** constraints are violated.
   94176     */
   94177     if( (db->flags & SQLITE_DeferFKs)==0 ){
   94178       sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
   94179       VdbeCoverage(v);
   94180       sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
   94181           OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
   94182     }
   94183 
   94184     if( iSkip ){
   94185       sqlite3VdbeResolveLabel(v, iSkip);
   94186     }
   94187   }
   94188 }
   94189 
   94190 
   94191 /*
   94192 ** The second argument points to an FKey object representing a foreign key
   94193 ** for which pTab is the child table. An UPDATE statement against pTab
   94194 ** is currently being processed. For each column of the table that is
   94195 ** actually updated, the corresponding element in the aChange[] array
   94196 ** is zero or greater (if a column is unmodified the corresponding element
   94197 ** is set to -1). If the rowid column is modified by the UPDATE statement
   94198 ** the bChngRowid argument is non-zero.
   94199 **
   94200 ** This function returns true if any of the columns that are part of the
   94201 ** child key for FK constraint *p are modified.
   94202 */
   94203 static int fkChildIsModified(
   94204   Table *pTab,                    /* Table being updated */
   94205   FKey *p,                        /* Foreign key for which pTab is the child */
   94206   int *aChange,                   /* Array indicating modified columns */
   94207   int bChngRowid                  /* True if rowid is modified by this update */
   94208 ){
   94209   int i;
   94210   for(i=0; i<p->nCol; i++){
   94211     int iChildKey = p->aCol[i].iFrom;
   94212     if( aChange[iChildKey]>=0 ) return 1;
   94213     if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
   94214   }
   94215   return 0;
   94216 }
   94217 
   94218 /*
   94219 ** The second argument points to an FKey object representing a foreign key
   94220 ** for which pTab is the parent table. An UPDATE statement against pTab
   94221 ** is currently being processed. For each column of the table that is
   94222 ** actually updated, the corresponding element in the aChange[] array
   94223 ** is zero or greater (if a column is unmodified the corresponding element
   94224 ** is set to -1). If the rowid column is modified by the UPDATE statement
   94225 ** the bChngRowid argument is non-zero.
   94226 **
   94227 ** This function returns true if any of the columns that are part of the
   94228 ** parent key for FK constraint *p are modified.
   94229 */
   94230 static int fkParentIsModified(
   94231   Table *pTab,
   94232   FKey *p,
   94233   int *aChange,
   94234   int bChngRowid
   94235 ){
   94236   int i;
   94237   for(i=0; i<p->nCol; i++){
   94238     char *zKey = p->aCol[i].zCol;
   94239     int iKey;
   94240     for(iKey=0; iKey<pTab->nCol; iKey++){
   94241       if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
   94242         Column *pCol = &pTab->aCol[iKey];
   94243         if( zKey ){
   94244           if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
   94245         }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
   94246           return 1;
   94247         }
   94248       }
   94249     }
   94250   }
   94251   return 0;
   94252 }
   94253 
   94254 /*
   94255 ** This function is called when inserting, deleting or updating a row of
   94256 ** table pTab to generate VDBE code to perform foreign key constraint
   94257 ** processing for the operation.
   94258 **
   94259 ** For a DELETE operation, parameter regOld is passed the index of the
   94260 ** first register in an array of (pTab->nCol+1) registers containing the
   94261 ** rowid of the row being deleted, followed by each of the column values
   94262 ** of the row being deleted, from left to right. Parameter regNew is passed
   94263 ** zero in this case.
   94264 **
   94265 ** For an INSERT operation, regOld is passed zero and regNew is passed the
   94266 ** first register of an array of (pTab->nCol+1) registers containing the new
   94267 ** row data.
   94268 **
   94269 ** For an UPDATE operation, this function is called twice. Once before
   94270 ** the original record is deleted from the table using the calling convention
   94271 ** described for DELETE. Then again after the original record is deleted
   94272 ** but before the new record is inserted using the INSERT convention.
   94273 */
   94274 SQLITE_PRIVATE void sqlite3FkCheck(
   94275   Parse *pParse,                  /* Parse context */
   94276   Table *pTab,                    /* Row is being deleted from this table */
   94277   int regOld,                     /* Previous row data is stored here */
   94278   int regNew,                     /* New row data is stored here */
   94279   int *aChange,                   /* Array indicating UPDATEd columns (or 0) */
   94280   int bChngRowid                  /* True if rowid is UPDATEd */
   94281 ){
   94282   sqlite3 *db = pParse->db;       /* Database handle */
   94283   FKey *pFKey;                    /* Used to iterate through FKs */
   94284   int iDb;                        /* Index of database containing pTab */
   94285   const char *zDb;                /* Name of database containing pTab */
   94286   int isIgnoreErrors = pParse->disableTriggers;
   94287 
   94288   /* Exactly one of regOld and regNew should be non-zero. */
   94289   assert( (regOld==0)!=(regNew==0) );
   94290 
   94291   /* If foreign-keys are disabled, this function is a no-op. */
   94292   if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
   94293 
   94294   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   94295   zDb = db->aDb[iDb].zName;
   94296 
   94297   /* Loop through all the foreign key constraints for which pTab is the
   94298   ** child table (the table that the foreign key definition is part of).  */
   94299   for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
   94300     Table *pTo;                   /* Parent table of foreign key pFKey */
   94301     Index *pIdx = 0;              /* Index on key columns in pTo */
   94302     int *aiFree = 0;
   94303     int *aiCol;
   94304     int iCol;
   94305     int i;
   94306     int isIgnore = 0;
   94307 
   94308     if( aChange
   94309      && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
   94310      && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
   94311     ){
   94312       continue;
   94313     }
   94314 
   94315     /* Find the parent table of this foreign key. Also find a unique index
   94316     ** on the parent key columns in the parent table. If either of these
   94317     ** schema items cannot be located, set an error in pParse and return
   94318     ** early.  */
   94319     if( pParse->disableTriggers ){
   94320       pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
   94321     }else{
   94322       pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
   94323     }
   94324     if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
   94325       assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
   94326       if( !isIgnoreErrors || db->mallocFailed ) return;
   94327       if( pTo==0 ){
   94328         /* If isIgnoreErrors is true, then a table is being dropped. In this
   94329         ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
   94330         ** before actually dropping it in order to check FK constraints.
   94331         ** If the parent table of an FK constraint on the current table is
   94332         ** missing, behave as if it is empty. i.e. decrement the relevant
   94333         ** FK counter for each row of the current table with non-NULL keys.
   94334         */
   94335         Vdbe *v = sqlite3GetVdbe(pParse);
   94336         int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
   94337         for(i=0; i<pFKey->nCol; i++){
   94338           int iReg = pFKey->aCol[i].iFrom + regOld + 1;
   94339           sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
   94340         }
   94341         sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
   94342       }
   94343       continue;
   94344     }
   94345     assert( pFKey->nCol==1 || (aiFree && pIdx) );
   94346 
   94347     if( aiFree ){
   94348       aiCol = aiFree;
   94349     }else{
   94350       iCol = pFKey->aCol[0].iFrom;
   94351       aiCol = &iCol;
   94352     }
   94353     for(i=0; i<pFKey->nCol; i++){
   94354       if( aiCol[i]==pTab->iPKey ){
   94355         aiCol[i] = -1;
   94356       }
   94357 #ifndef SQLITE_OMIT_AUTHORIZATION
   94358       /* Request permission to read the parent key columns. If the
   94359       ** authorization callback returns SQLITE_IGNORE, behave as if any
   94360       ** values read from the parent table are NULL. */
   94361       if( db->xAuth ){
   94362         int rcauth;
   94363         char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
   94364         rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
   94365         isIgnore = (rcauth==SQLITE_IGNORE);
   94366       }
   94367 #endif
   94368     }
   94369 
   94370     /* Take a shared-cache advisory read-lock on the parent table. Allocate
   94371     ** a cursor to use to search the unique index on the parent key columns
   94372     ** in the parent table.  */
   94373     sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
   94374     pParse->nTab++;
   94375 
   94376     if( regOld!=0 ){
   94377       /* A row is being removed from the child table. Search for the parent.
   94378       ** If the parent does not exist, removing the child row resolves an
   94379       ** outstanding foreign key constraint violation. */
   94380       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
   94381     }
   94382     if( regNew!=0 ){
   94383       /* A row is being added to the child table. If a parent row cannot
   94384       ** be found, adding the child row has violated the FK constraint. */
   94385       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
   94386     }
   94387 
   94388     sqlite3DbFree(db, aiFree);
   94389   }
   94390 
   94391   /* Loop through all the foreign key constraints that refer to this table.
   94392   ** (the "child" constraints) */
   94393   for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
   94394     Index *pIdx = 0;              /* Foreign key index for pFKey */
   94395     SrcList *pSrc;
   94396     int *aiCol = 0;
   94397 
   94398     if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
   94399       continue;
   94400     }
   94401 
   94402     if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
   94403      && !pParse->pToplevel && !pParse->isMultiWrite
   94404     ){
   94405       assert( regOld==0 && regNew!=0 );
   94406       /* Inserting a single row into a parent table cannot cause an immediate
   94407       ** foreign key violation. So do nothing in this case.  */
   94408       continue;
   94409     }
   94410 
   94411     if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
   94412       if( !isIgnoreErrors || db->mallocFailed ) return;
   94413       continue;
   94414     }
   94415     assert( aiCol || pFKey->nCol==1 );
   94416 
   94417     /* Create a SrcList structure containing the child table.  We need the
   94418     ** child table as a SrcList for sqlite3WhereBegin() */
   94419     pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
   94420     if( pSrc ){
   94421       struct SrcList_item *pItem = pSrc->a;
   94422       pItem->pTab = pFKey->pFrom;
   94423       pItem->zName = pFKey->pFrom->zName;
   94424       pItem->pTab->nRef++;
   94425       pItem->iCursor = pParse->nTab++;
   94426 
   94427       if( regNew!=0 ){
   94428         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
   94429       }
   94430       if( regOld!=0 ){
   94431         /* If there is a RESTRICT action configured for the current operation
   94432         ** on the parent table of this FK, then throw an exception
   94433         ** immediately if the FK constraint is violated, even if this is a
   94434         ** deferred trigger. That's what RESTRICT means. To defer checking
   94435         ** the constraint, the FK should specify NO ACTION (represented
   94436         ** using OE_None). NO ACTION is the default.  */
   94437         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
   94438       }
   94439       pItem->zName = 0;
   94440       sqlite3SrcListDelete(db, pSrc);
   94441     }
   94442     sqlite3DbFree(db, aiCol);
   94443   }
   94444 }
   94445 
   94446 #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
   94447 
   94448 /*
   94449 ** This function is called before generating code to update or delete a
   94450 ** row contained in table pTab.
   94451 */
   94452 SQLITE_PRIVATE u32 sqlite3FkOldmask(
   94453   Parse *pParse,                  /* Parse context */
   94454   Table *pTab                     /* Table being modified */
   94455 ){
   94456   u32 mask = 0;
   94457   if( pParse->db->flags&SQLITE_ForeignKeys ){
   94458     FKey *p;
   94459     int i;
   94460     for(p=pTab->pFKey; p; p=p->pNextFrom){
   94461       for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
   94462     }
   94463     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
   94464       Index *pIdx = 0;
   94465       sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
   94466       if( pIdx ){
   94467         for(i=0; i<pIdx->nKeyCol; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
   94468       }
   94469     }
   94470   }
   94471   return mask;
   94472 }
   94473 
   94474 
   94475 /*
   94476 ** This function is called before generating code to update or delete a
   94477 ** row contained in table pTab. If the operation is a DELETE, then
   94478 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
   94479 ** to an array of size N, where N is the number of columns in table pTab.
   94480 ** If the i'th column is not modified by the UPDATE, then the corresponding
   94481 ** entry in the aChange[] array is set to -1. If the column is modified,
   94482 ** the value is 0 or greater. Parameter chngRowid is set to true if the
   94483 ** UPDATE statement modifies the rowid fields of the table.
   94484 **
   94485 ** If any foreign key processing will be required, this function returns
   94486 ** true. If there is no foreign key related processing, this function
   94487 ** returns false.
   94488 */
   94489 SQLITE_PRIVATE int sqlite3FkRequired(
   94490   Parse *pParse,                  /* Parse context */
   94491   Table *pTab,                    /* Table being modified */
   94492   int *aChange,                   /* Non-NULL for UPDATE operations */
   94493   int chngRowid                   /* True for UPDATE that affects rowid */
   94494 ){
   94495   if( pParse->db->flags&SQLITE_ForeignKeys ){
   94496     if( !aChange ){
   94497       /* A DELETE operation. Foreign key processing is required if the
   94498       ** table in question is either the child or parent table for any
   94499       ** foreign key constraint.  */
   94500       return (sqlite3FkReferences(pTab) || pTab->pFKey);
   94501     }else{
   94502       /* This is an UPDATE. Foreign key processing is only required if the
   94503       ** operation modifies one or more child or parent key columns. */
   94504       FKey *p;
   94505 
   94506       /* Check if any child key columns are being modified. */
   94507       for(p=pTab->pFKey; p; p=p->pNextFrom){
   94508         if( fkChildIsModified(pTab, p, aChange, chngRowid) ) return 1;
   94509       }
   94510 
   94511       /* Check if any parent key columns are being modified. */
   94512       for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
   94513         if( fkParentIsModified(pTab, p, aChange, chngRowid) ) return 1;
   94514       }
   94515     }
   94516   }
   94517   return 0;
   94518 }
   94519 
   94520 /*
   94521 ** This function is called when an UPDATE or DELETE operation is being
   94522 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
   94523 ** If the current operation is an UPDATE, then the pChanges parameter is
   94524 ** passed a pointer to the list of columns being modified. If it is a
   94525 ** DELETE, pChanges is passed a NULL pointer.
   94526 **
   94527 ** It returns a pointer to a Trigger structure containing a trigger
   94528 ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
   94529 ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
   94530 ** returned (these actions require no special handling by the triggers
   94531 ** sub-system, code for them is created by fkScanChildren()).
   94532 **
   94533 ** For example, if pFKey is the foreign key and pTab is table "p" in
   94534 ** the following schema:
   94535 **
   94536 **   CREATE TABLE p(pk PRIMARY KEY);
   94537 **   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
   94538 **
   94539 ** then the returned trigger structure is equivalent to:
   94540 **
   94541 **   CREATE TRIGGER ... DELETE ON p BEGIN
   94542 **     DELETE FROM c WHERE ck = old.pk;
   94543 **   END;
   94544 **
   94545 ** The returned pointer is cached as part of the foreign key object. It
   94546 ** is eventually freed along with the rest of the foreign key object by
   94547 ** sqlite3FkDelete().
   94548 */
   94549 static Trigger *fkActionTrigger(
   94550   Parse *pParse,                  /* Parse context */
   94551   Table *pTab,                    /* Table being updated or deleted from */
   94552   FKey *pFKey,                    /* Foreign key to get action for */
   94553   ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
   94554 ){
   94555   sqlite3 *db = pParse->db;       /* Database handle */
   94556   int action;                     /* One of OE_None, OE_Cascade etc. */
   94557   Trigger *pTrigger;              /* Trigger definition to return */
   94558   int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
   94559 
   94560   action = pFKey->aAction[iAction];
   94561   pTrigger = pFKey->apTrigger[iAction];
   94562 
   94563   if( action!=OE_None && !pTrigger ){
   94564     u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
   94565     char const *zFrom;            /* Name of child table */
   94566     int nFrom;                    /* Length in bytes of zFrom */
   94567     Index *pIdx = 0;              /* Parent key index for this FK */
   94568     int *aiCol = 0;               /* child table cols -> parent key cols */
   94569     TriggerStep *pStep = 0;        /* First (only) step of trigger program */
   94570     Expr *pWhere = 0;             /* WHERE clause of trigger step */
   94571     ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
   94572     Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
   94573     int i;                        /* Iterator variable */
   94574     Expr *pWhen = 0;              /* WHEN clause for the trigger */
   94575 
   94576     if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
   94577     assert( aiCol || pFKey->nCol==1 );
   94578 
   94579     for(i=0; i<pFKey->nCol; i++){
   94580       Token tOld = { "old", 3 };  /* Literal "old" token */
   94581       Token tNew = { "new", 3 };  /* Literal "new" token */
   94582       Token tFromCol;             /* Name of column in child table */
   94583       Token tToCol;               /* Name of column in parent table */
   94584       int iFromCol;               /* Idx of column in child table */
   94585       Expr *pEq;                  /* tFromCol = OLD.tToCol */
   94586 
   94587       iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
   94588       assert( iFromCol>=0 );
   94589       tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
   94590       tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
   94591 
   94592       tToCol.n = sqlite3Strlen30(tToCol.z);
   94593       tFromCol.n = sqlite3Strlen30(tFromCol.z);
   94594 
   94595       /* Create the expression "OLD.zToCol = zFromCol". It is important
   94596       ** that the "OLD.zToCol" term is on the LHS of the = operator, so
   94597       ** that the affinity and collation sequence associated with the
   94598       ** parent table are used for the comparison. */
   94599       pEq = sqlite3PExpr(pParse, TK_EQ,
   94600           sqlite3PExpr(pParse, TK_DOT,
   94601             sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
   94602             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
   94603           , 0),
   94604           sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
   94605       , 0);
   94606       pWhere = sqlite3ExprAnd(db, pWhere, pEq);
   94607 
   94608       /* For ON UPDATE, construct the next term of the WHEN clause.
   94609       ** The final WHEN clause will be like this:
   94610       **
   94611       **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
   94612       */
   94613       if( pChanges ){
   94614         pEq = sqlite3PExpr(pParse, TK_IS,
   94615             sqlite3PExpr(pParse, TK_DOT,
   94616               sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
   94617               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
   94618               0),
   94619             sqlite3PExpr(pParse, TK_DOT,
   94620               sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
   94621               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
   94622               0),
   94623             0);
   94624         pWhen = sqlite3ExprAnd(db, pWhen, pEq);
   94625       }
   94626 
   94627       if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
   94628         Expr *pNew;
   94629         if( action==OE_Cascade ){
   94630           pNew = sqlite3PExpr(pParse, TK_DOT,
   94631             sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
   94632             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
   94633           , 0);
   94634         }else if( action==OE_SetDflt ){
   94635           Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
   94636           if( pDflt ){
   94637             pNew = sqlite3ExprDup(db, pDflt, 0);
   94638           }else{
   94639             pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
   94640           }
   94641         }else{
   94642           pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
   94643         }
   94644         pList = sqlite3ExprListAppend(pParse, pList, pNew);
   94645         sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
   94646       }
   94647     }
   94648     sqlite3DbFree(db, aiCol);
   94649 
   94650     zFrom = pFKey->pFrom->zName;
   94651     nFrom = sqlite3Strlen30(zFrom);
   94652 
   94653     if( action==OE_Restrict ){
   94654       Token tFrom;
   94655       Expr *pRaise;
   94656 
   94657       tFrom.z = zFrom;
   94658       tFrom.n = nFrom;
   94659       pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
   94660       if( pRaise ){
   94661         pRaise->affinity = OE_Abort;
   94662       }
   94663       pSelect = sqlite3SelectNew(pParse,
   94664           sqlite3ExprListAppend(pParse, 0, pRaise),
   94665           sqlite3SrcListAppend(db, 0, &tFrom, 0),
   94666           pWhere,
   94667           0, 0, 0, 0, 0, 0
   94668       );
   94669       pWhere = 0;
   94670     }
   94671 
   94672     /* Disable lookaside memory allocation */
   94673     enableLookaside = db->lookaside.bEnabled;
   94674     db->lookaside.bEnabled = 0;
   94675 
   94676     pTrigger = (Trigger *)sqlite3DbMallocZero(db,
   94677         sizeof(Trigger) +         /* struct Trigger */
   94678         sizeof(TriggerStep) +     /* Single step in trigger program */
   94679         nFrom + 1                 /* Space for pStep->target.z */
   94680     );
   94681     if( pTrigger ){
   94682       pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
   94683       pStep->target.z = (char *)&pStep[1];
   94684       pStep->target.n = nFrom;
   94685       memcpy((char *)pStep->target.z, zFrom, nFrom);
   94686 
   94687       pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
   94688       pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
   94689       pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
   94690       if( pWhen ){
   94691         pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
   94692         pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
   94693       }
   94694     }
   94695 
   94696     /* Re-enable the lookaside buffer, if it was disabled earlier. */
   94697     db->lookaside.bEnabled = enableLookaside;
   94698 
   94699     sqlite3ExprDelete(db, pWhere);
   94700     sqlite3ExprDelete(db, pWhen);
   94701     sqlite3ExprListDelete(db, pList);
   94702     sqlite3SelectDelete(db, pSelect);
   94703     if( db->mallocFailed==1 ){
   94704       fkTriggerDelete(db, pTrigger);
   94705       return 0;
   94706     }
   94707     assert( pStep!=0 );
   94708 
   94709     switch( action ){
   94710       case OE_Restrict:
   94711         pStep->op = TK_SELECT;
   94712         break;
   94713       case OE_Cascade:
   94714         if( !pChanges ){
   94715           pStep->op = TK_DELETE;
   94716           break;
   94717         }
   94718       default:
   94719         pStep->op = TK_UPDATE;
   94720     }
   94721     pStep->pTrig = pTrigger;
   94722     pTrigger->pSchema = pTab->pSchema;
   94723     pTrigger->pTabSchema = pTab->pSchema;
   94724     pFKey->apTrigger[iAction] = pTrigger;
   94725     pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
   94726   }
   94727 
   94728   return pTrigger;
   94729 }
   94730 
   94731 /*
   94732 ** This function is called when deleting or updating a row to implement
   94733 ** any required CASCADE, SET NULL or SET DEFAULT actions.
   94734 */
   94735 SQLITE_PRIVATE void sqlite3FkActions(
   94736   Parse *pParse,                  /* Parse context */
   94737   Table *pTab,                    /* Table being updated or deleted from */
   94738   ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
   94739   int regOld,                     /* Address of array containing old row */
   94740   int *aChange,                   /* Array indicating UPDATEd columns (or 0) */
   94741   int bChngRowid                  /* True if rowid is UPDATEd */
   94742 ){
   94743   /* If foreign-key support is enabled, iterate through all FKs that
   94744   ** refer to table pTab. If there is an action associated with the FK
   94745   ** for this operation (either update or delete), invoke the associated
   94746   ** trigger sub-program.  */
   94747   if( pParse->db->flags&SQLITE_ForeignKeys ){
   94748     FKey *pFKey;                  /* Iterator variable */
   94749     for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
   94750       if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
   94751         Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
   94752         if( pAct ){
   94753           sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
   94754         }
   94755       }
   94756     }
   94757   }
   94758 }
   94759 
   94760 #endif /* ifndef SQLITE_OMIT_TRIGGER */
   94761 
   94762 /*
   94763 ** Free all memory associated with foreign key definitions attached to
   94764 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
   94765 ** hash table.
   94766 */
   94767 SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
   94768   FKey *pFKey;                    /* Iterator variable */
   94769   FKey *pNext;                    /* Copy of pFKey->pNextFrom */
   94770 
   94771   assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
   94772   for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
   94773 
   94774     /* Remove the FK from the fkeyHash hash table. */
   94775     if( !db || db->pnBytesFreed==0 ){
   94776       if( pFKey->pPrevTo ){
   94777         pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
   94778       }else{
   94779         void *p = (void *)pFKey->pNextTo;
   94780         const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
   94781         sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p);
   94782       }
   94783       if( pFKey->pNextTo ){
   94784         pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
   94785       }
   94786     }
   94787 
   94788     /* EV: R-30323-21917 Each foreign key constraint in SQLite is
   94789     ** classified as either immediate or deferred.
   94790     */
   94791     assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
   94792 
   94793     /* Delete any triggers created to implement actions for this FK. */
   94794 #ifndef SQLITE_OMIT_TRIGGER
   94795     fkTriggerDelete(db, pFKey->apTrigger[0]);
   94796     fkTriggerDelete(db, pFKey->apTrigger[1]);
   94797 #endif
   94798 
   94799     pNext = pFKey->pNextFrom;
   94800     sqlite3DbFree(db, pFKey);
   94801   }
   94802 }
   94803 #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
   94804 
   94805 /************** End of fkey.c ************************************************/
   94806 /************** Begin file insert.c ******************************************/
   94807 /*
   94808 ** 2001 September 15
   94809 **
   94810 ** The author disclaims copyright to this source code.  In place of
   94811 ** a legal notice, here is a blessing:
   94812 **
   94813 **    May you do good and not evil.
   94814 **    May you find forgiveness for yourself and forgive others.
   94815 **    May you share freely, never taking more than you give.
   94816 **
   94817 *************************************************************************
   94818 ** This file contains C code routines that are called by the parser
   94819 ** to handle INSERT statements in SQLite.
   94820 */
   94821 
   94822 /*
   94823 ** Generate code that will
   94824 **
   94825 **   (1) acquire a lock for table pTab then
   94826 **   (2) open pTab as cursor iCur.
   94827 **
   94828 ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
   94829 ** for that table that is actually opened.
   94830 */
   94831 SQLITE_PRIVATE void sqlite3OpenTable(
   94832   Parse *pParse,  /* Generate code into this VDBE */
   94833   int iCur,       /* The cursor number of the table */
   94834   int iDb,        /* The database index in sqlite3.aDb[] */
   94835   Table *pTab,    /* The table to be opened */
   94836   int opcode      /* OP_OpenRead or OP_OpenWrite */
   94837 ){
   94838   Vdbe *v;
   94839   assert( !IsVirtual(pTab) );
   94840   v = sqlite3GetVdbe(pParse);
   94841   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
   94842   sqlite3TableLock(pParse, iDb, pTab->tnum,
   94843                    (opcode==OP_OpenWrite)?1:0, pTab->zName);
   94844   if( HasRowid(pTab) ){
   94845     sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
   94846     VdbeComment((v, "%s", pTab->zName));
   94847   }else{
   94848     Index *pPk = sqlite3PrimaryKeyIndex(pTab);
   94849     assert( pPk!=0 );
   94850     assert( pPk->tnum=pTab->tnum );
   94851     sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
   94852     sqlite3VdbeSetP4KeyInfo(pParse, pPk);
   94853     VdbeComment((v, "%s", pTab->zName));
   94854   }
   94855 }
   94856 
   94857 /*
   94858 ** Return a pointer to the column affinity string associated with index
   94859 ** pIdx. A column affinity string has one character for each column in
   94860 ** the table, according to the affinity of the column:
   94861 **
   94862 **  Character      Column affinity
   94863 **  ------------------------------
   94864 **  'a'            TEXT
   94865 **  'b'            NONE
   94866 **  'c'            NUMERIC
   94867 **  'd'            INTEGER
   94868 **  'e'            REAL
   94869 **
   94870 ** An extra 'd' is appended to the end of the string to cover the
   94871 ** rowid that appears as the last column in every index.
   94872 **
   94873 ** Memory for the buffer containing the column index affinity string
   94874 ** is managed along with the rest of the Index structure. It will be
   94875 ** released when sqlite3DeleteIndex() is called.
   94876 */
   94877 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
   94878   if( !pIdx->zColAff ){
   94879     /* The first time a column affinity string for a particular index is
   94880     ** required, it is allocated and populated here. It is then stored as
   94881     ** a member of the Index structure for subsequent use.
   94882     **
   94883     ** The column affinity string will eventually be deleted by
   94884     ** sqliteDeleteIndex() when the Index structure itself is cleaned
   94885     ** up.
   94886     */
   94887     int n;
   94888     Table *pTab = pIdx->pTable;
   94889     sqlite3 *db = sqlite3VdbeDb(v);
   94890     pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
   94891     if( !pIdx->zColAff ){
   94892       db->mallocFailed = 1;
   94893       return 0;
   94894     }
   94895     for(n=0; n<pIdx->nColumn; n++){
   94896       i16 x = pIdx->aiColumn[n];
   94897       pIdx->zColAff[n] = x<0 ? SQLITE_AFF_INTEGER : pTab->aCol[x].affinity;
   94898     }
   94899     pIdx->zColAff[n] = 0;
   94900   }
   94901 
   94902   return pIdx->zColAff;
   94903 }
   94904 
   94905 /*
   94906 ** Compute the affinity string for table pTab, if it has not already been
   94907 ** computed.  As an optimization, omit trailing SQLITE_AFF_NONE affinities.
   94908 **
   94909 ** If the affinity exists (if it is no entirely SQLITE_AFF_NONE values) and
   94910 ** if iReg>0 then code an OP_Affinity opcode that will set the affinities
   94911 ** for register iReg and following.  Or if affinities exists and iReg==0,
   94912 ** then just set the P4 operand of the previous opcode (which should  be
   94913 ** an OP_MakeRecord) to the affinity string.
   94914 **
   94915 ** A column affinity string has one character per column:
   94916 **
   94917 **  Character      Column affinity
   94918 **  ------------------------------
   94919 **  'a'            TEXT
   94920 **  'b'            NONE
   94921 **  'c'            NUMERIC
   94922 **  'd'            INTEGER
   94923 **  'e'            REAL
   94924 */
   94925 SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
   94926   int i;
   94927   char *zColAff = pTab->zColAff;
   94928   if( zColAff==0 ){
   94929     sqlite3 *db = sqlite3VdbeDb(v);
   94930     zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
   94931     if( !zColAff ){
   94932       db->mallocFailed = 1;
   94933       return;
   94934     }
   94935 
   94936     for(i=0; i<pTab->nCol; i++){
   94937       zColAff[i] = pTab->aCol[i].affinity;
   94938     }
   94939     do{
   94940       zColAff[i--] = 0;
   94941     }while( i>=0 && zColAff[i]==SQLITE_AFF_NONE );
   94942     pTab->zColAff = zColAff;
   94943   }
   94944   i = sqlite3Strlen30(zColAff);
   94945   if( i ){
   94946     if( iReg ){
   94947       sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
   94948     }else{
   94949       sqlite3VdbeChangeP4(v, -1, zColAff, i);
   94950     }
   94951   }
   94952 }
   94953 
   94954 /*
   94955 ** Return non-zero if the table pTab in database iDb or any of its indices
   94956 ** have been opened at any point in the VDBE program. This is used to see if
   94957 ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
   94958 ** run without using a temporary table for the results of the SELECT.
   94959 */
   94960 static int readsTable(Parse *p, int iDb, Table *pTab){
   94961   Vdbe *v = sqlite3GetVdbe(p);
   94962   int i;
   94963   int iEnd = sqlite3VdbeCurrentAddr(v);
   94964 #ifndef SQLITE_OMIT_VIRTUALTABLE
   94965   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
   94966 #endif
   94967 
   94968   for(i=1; i<iEnd; i++){
   94969     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
   94970     assert( pOp!=0 );
   94971     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
   94972       Index *pIndex;
   94973       int tnum = pOp->p2;
   94974       if( tnum==pTab->tnum ){
   94975         return 1;
   94976       }
   94977       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
   94978         if( tnum==pIndex->tnum ){
   94979           return 1;
   94980         }
   94981       }
   94982     }
   94983 #ifndef SQLITE_OMIT_VIRTUALTABLE
   94984     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
   94985       assert( pOp->p4.pVtab!=0 );
   94986       assert( pOp->p4type==P4_VTAB );
   94987       return 1;
   94988     }
   94989 #endif
   94990   }
   94991   return 0;
   94992 }
   94993 
   94994 #ifndef SQLITE_OMIT_AUTOINCREMENT
   94995 /*
   94996 ** Locate or create an AutoincInfo structure associated with table pTab
   94997 ** which is in database iDb.  Return the register number for the register
   94998 ** that holds the maximum rowid.
   94999 **
   95000 ** There is at most one AutoincInfo structure per table even if the
   95001 ** same table is autoincremented multiple times due to inserts within
   95002 ** triggers.  A new AutoincInfo structure is created if this is the
   95003 ** first use of table pTab.  On 2nd and subsequent uses, the original
   95004 ** AutoincInfo structure is used.
   95005 **
   95006 ** Three memory locations are allocated:
   95007 **
   95008 **   (1)  Register to hold the name of the pTab table.
   95009 **   (2)  Register to hold the maximum ROWID of pTab.
   95010 **   (3)  Register to hold the rowid in sqlite_sequence of pTab
   95011 **
   95012 ** The 2nd register is the one that is returned.  That is all the
   95013 ** insert routine needs to know about.
   95014 */
   95015 static int autoIncBegin(
   95016   Parse *pParse,      /* Parsing context */
   95017   int iDb,            /* Index of the database holding pTab */
   95018   Table *pTab         /* The table we are writing to */
   95019 ){
   95020   int memId = 0;      /* Register holding maximum rowid */
   95021   if( pTab->tabFlags & TF_Autoincrement ){
   95022     Parse *pToplevel = sqlite3ParseToplevel(pParse);
   95023     AutoincInfo *pInfo;
   95024 
   95025     pInfo = pToplevel->pAinc;
   95026     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
   95027     if( pInfo==0 ){
   95028       pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
   95029       if( pInfo==0 ) return 0;
   95030       pInfo->pNext = pToplevel->pAinc;
   95031       pToplevel->pAinc = pInfo;
   95032       pInfo->pTab = pTab;
   95033       pInfo->iDb = iDb;
   95034       pToplevel->nMem++;                  /* Register to hold name of table */
   95035       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
   95036       pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
   95037     }
   95038     memId = pInfo->regCtr;
   95039   }
   95040   return memId;
   95041 }
   95042 
   95043 /*
   95044 ** This routine generates code that will initialize all of the
   95045 ** register used by the autoincrement tracker.
   95046 */
   95047 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
   95048   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
   95049   sqlite3 *db = pParse->db;  /* The database connection */
   95050   Db *pDb;                   /* Database only autoinc table */
   95051   int memId;                 /* Register holding max rowid */
   95052   int addr;                  /* A VDBE address */
   95053   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
   95054 
   95055   /* This routine is never called during trigger-generation.  It is
   95056   ** only called from the top-level */
   95057   assert( pParse->pTriggerTab==0 );
   95058   assert( pParse==sqlite3ParseToplevel(pParse) );
   95059 
   95060   assert( v );   /* We failed long ago if this is not so */
   95061   for(p = pParse->pAinc; p; p = p->pNext){
   95062     pDb = &db->aDb[p->iDb];
   95063     memId = p->regCtr;
   95064     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
   95065     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
   95066     sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
   95067     addr = sqlite3VdbeCurrentAddr(v);
   95068     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
   95069     sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9); VdbeCoverage(v);
   95070     sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
   95071     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId); VdbeCoverage(v);
   95072     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
   95073     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
   95074     sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
   95075     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
   95076     sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2); VdbeCoverage(v);
   95077     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
   95078     sqlite3VdbeAddOp0(v, OP_Close);
   95079   }
   95080 }
   95081 
   95082 /*
   95083 ** Update the maximum rowid for an autoincrement calculation.
   95084 **
   95085 ** This routine should be called when the top of the stack holds a
   95086 ** new rowid that is about to be inserted.  If that new rowid is
   95087 ** larger than the maximum rowid in the memId memory cell, then the
   95088 ** memory cell is updated.  The stack is unchanged.
   95089 */
   95090 static void autoIncStep(Parse *pParse, int memId, int regRowid){
   95091   if( memId>0 ){
   95092     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
   95093   }
   95094 }
   95095 
   95096 /*
   95097 ** This routine generates the code needed to write autoincrement
   95098 ** maximum rowid values back into the sqlite_sequence register.
   95099 ** Every statement that might do an INSERT into an autoincrement
   95100 ** table (either directly or through triggers) needs to call this
   95101 ** routine just before the "exit" code.
   95102 */
   95103 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
   95104   AutoincInfo *p;
   95105   Vdbe *v = pParse->pVdbe;
   95106   sqlite3 *db = pParse->db;
   95107 
   95108   assert( v );
   95109   for(p = pParse->pAinc; p; p = p->pNext){
   95110     Db *pDb = &db->aDb[p->iDb];
   95111     int j1;
   95112     int iRec;
   95113     int memId = p->regCtr;
   95114 
   95115     iRec = sqlite3GetTempReg(pParse);
   95116     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
   95117     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
   95118     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1); VdbeCoverage(v);
   95119     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
   95120     sqlite3VdbeJumpHere(v, j1);
   95121     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
   95122     sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
   95123     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   95124     sqlite3VdbeAddOp0(v, OP_Close);
   95125     sqlite3ReleaseTempReg(pParse, iRec);
   95126   }
   95127 }
   95128 #else
   95129 /*
   95130 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
   95131 ** above are all no-ops
   95132 */
   95133 # define autoIncBegin(A,B,C) (0)
   95134 # define autoIncStep(A,B,C)
   95135 #endif /* SQLITE_OMIT_AUTOINCREMENT */
   95136 
   95137 
   95138 /* Forward declaration */
   95139 static int xferOptimization(
   95140   Parse *pParse,        /* Parser context */
   95141   Table *pDest,         /* The table we are inserting into */
   95142   Select *pSelect,      /* A SELECT statement to use as the data source */
   95143   int onError,          /* How to handle constraint errors */
   95144   int iDbDest           /* The database of pDest */
   95145 );
   95146 
   95147 /*
   95148 ** This routine is called to handle SQL of the following forms:
   95149 **
   95150 **    insert into TABLE (IDLIST) values(EXPRLIST)
   95151 **    insert into TABLE (IDLIST) select
   95152 **
   95153 ** The IDLIST following the table name is always optional.  If omitted,
   95154 ** then a list of all columns for the table is substituted.  The IDLIST
   95155 ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
   95156 **
   95157 ** The pList parameter holds EXPRLIST in the first form of the INSERT
   95158 ** statement above, and pSelect is NULL.  For the second form, pList is
   95159 ** NULL and pSelect is a pointer to the select statement used to generate
   95160 ** data for the insert.
   95161 **
   95162 ** The code generated follows one of four templates.  For a simple
   95163 ** insert with data coming from a VALUES clause, the code executes
   95164 ** once straight down through.  Pseudo-code follows (we call this
   95165 ** the "1st template"):
   95166 **
   95167 **         open write cursor to <table> and its indices
   95168 **         put VALUES clause expressions into registers
   95169 **         write the resulting record into <table>
   95170 **         cleanup
   95171 **
   95172 ** The three remaining templates assume the statement is of the form
   95173 **
   95174 **   INSERT INTO <table> SELECT ...
   95175 **
   95176 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
   95177 ** in other words if the SELECT pulls all columns from a single table
   95178 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
   95179 ** if <table2> and <table1> are distinct tables but have identical
   95180 ** schemas, including all the same indices, then a special optimization
   95181 ** is invoked that copies raw records from <table2> over to <table1>.
   95182 ** See the xferOptimization() function for the implementation of this
   95183 ** template.  This is the 2nd template.
   95184 **
   95185 **         open a write cursor to <table>
   95186 **         open read cursor on <table2>
   95187 **         transfer all records in <table2> over to <table>
   95188 **         close cursors
   95189 **         foreach index on <table>
   95190 **           open a write cursor on the <table> index
   95191 **           open a read cursor on the corresponding <table2> index
   95192 **           transfer all records from the read to the write cursors
   95193 **           close cursors
   95194 **         end foreach
   95195 **
   95196 ** The 3rd template is for when the second template does not apply
   95197 ** and the SELECT clause does not read from <table> at any time.
   95198 ** The generated code follows this template:
   95199 **
   95200 **         X <- A
   95201 **         goto B
   95202 **      A: setup for the SELECT
   95203 **         loop over the rows in the SELECT
   95204 **           load values into registers R..R+n
   95205 **           yield X
   95206 **         end loop
   95207 **         cleanup after the SELECT
   95208 **         end-coroutine X
   95209 **      B: open write cursor to <table> and its indices
   95210 **      C: yield X, at EOF goto D
   95211 **         insert the select result into <table> from R..R+n
   95212 **         goto C
   95213 **      D: cleanup
   95214 **
   95215 ** The 4th template is used if the insert statement takes its
   95216 ** values from a SELECT but the data is being inserted into a table
   95217 ** that is also read as part of the SELECT.  In the third form,
   95218 ** we have to use a intermediate table to store the results of
   95219 ** the select.  The template is like this:
   95220 **
   95221 **         X <- A
   95222 **         goto B
   95223 **      A: setup for the SELECT
   95224 **         loop over the tables in the SELECT
   95225 **           load value into register R..R+n
   95226 **           yield X
   95227 **         end loop
   95228 **         cleanup after the SELECT
   95229 **         end co-routine R
   95230 **      B: open temp table
   95231 **      L: yield X, at EOF goto M
   95232 **         insert row from R..R+n into temp table
   95233 **         goto L
   95234 **      M: open write cursor to <table> and its indices
   95235 **         rewind temp table
   95236 **      C: loop over rows of intermediate table
   95237 **           transfer values form intermediate table into <table>
   95238 **         end loop
   95239 **      D: cleanup
   95240 */
   95241 SQLITE_PRIVATE void sqlite3Insert(
   95242   Parse *pParse,        /* Parser context */
   95243   SrcList *pTabList,    /* Name of table into which we are inserting */
   95244   Select *pSelect,      /* A SELECT statement to use as the data source */
   95245   IdList *pColumn,      /* Column names corresponding to IDLIST. */
   95246   int onError           /* How to handle constraint errors */
   95247 ){
   95248   sqlite3 *db;          /* The main database structure */
   95249   Table *pTab;          /* The table to insert into.  aka TABLE */
   95250   char *zTab;           /* Name of the table into which we are inserting */
   95251   const char *zDb;      /* Name of the database holding this table */
   95252   int i, j, idx;        /* Loop counters */
   95253   Vdbe *v;              /* Generate code into this virtual machine */
   95254   Index *pIdx;          /* For looping over indices of the table */
   95255   int nColumn;          /* Number of columns in the data */
   95256   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
   95257   int iDataCur = 0;     /* VDBE cursor that is the main data repository */
   95258   int iIdxCur = 0;      /* First index cursor */
   95259   int ipkColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
   95260   int endOfLoop;        /* Label for the end of the insertion loop */
   95261   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
   95262   int addrInsTop = 0;   /* Jump to label "D" */
   95263   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
   95264   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
   95265   int iDb;              /* Index of database holding TABLE */
   95266   Db *pDb;              /* The database containing table being inserted into */
   95267   u8 useTempTable = 0;  /* Store SELECT results in intermediate table */
   95268   u8 appendFlag = 0;    /* True if the insert is likely to be an append */
   95269   u8 withoutRowid;      /* 0 for normal table.  1 for WITHOUT ROWID table */
   95270   u8 bIdListInOrder = 1; /* True if IDLIST is in table order */
   95271   ExprList *pList = 0;  /* List of VALUES() to be inserted  */
   95272 
   95273   /* Register allocations */
   95274   int regFromSelect = 0;/* Base register for data coming from SELECT */
   95275   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
   95276   int regRowCount = 0;  /* Memory cell used for the row counter */
   95277   int regIns;           /* Block of regs holding rowid+data being inserted */
   95278   int regRowid;         /* registers holding insert rowid */
   95279   int regData;          /* register holding first column to insert */
   95280   int *aRegIdx = 0;     /* One register allocated to each index */
   95281 
   95282 #ifndef SQLITE_OMIT_TRIGGER
   95283   int isView;                 /* True if attempting to insert into a view */
   95284   Trigger *pTrigger;          /* List of triggers on pTab, if required */
   95285   int tmask;                  /* Mask of trigger times */
   95286 #endif
   95287 
   95288   db = pParse->db;
   95289   memset(&dest, 0, sizeof(dest));
   95290   if( pParse->nErr || db->mallocFailed ){
   95291     goto insert_cleanup;
   95292   }
   95293 
   95294   /* If the Select object is really just a simple VALUES() list with a
   95295   ** single row values (the common case) then keep that one row of values
   95296   ** and go ahead and discard the Select object
   95297   */
   95298   if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
   95299     pList = pSelect->pEList;
   95300     pSelect->pEList = 0;
   95301     sqlite3SelectDelete(db, pSelect);
   95302     pSelect = 0;
   95303   }
   95304 
   95305   /* Locate the table into which we will be inserting new information.
   95306   */
   95307   assert( pTabList->nSrc==1 );
   95308   zTab = pTabList->a[0].zName;
   95309   if( NEVER(zTab==0) ) goto insert_cleanup;
   95310   pTab = sqlite3SrcListLookup(pParse, pTabList);
   95311   if( pTab==0 ){
   95312     goto insert_cleanup;
   95313   }
   95314   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   95315   assert( iDb<db->nDb );
   95316   pDb = &db->aDb[iDb];
   95317   zDb = pDb->zName;
   95318   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
   95319     goto insert_cleanup;
   95320   }
   95321   withoutRowid = !HasRowid(pTab);
   95322 
   95323   /* Figure out if we have any triggers and if the table being
   95324   ** inserted into is a view
   95325   */
   95326 #ifndef SQLITE_OMIT_TRIGGER
   95327   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
   95328   isView = pTab->pSelect!=0;
   95329 #else
   95330 # define pTrigger 0
   95331 # define tmask 0
   95332 # define isView 0
   95333 #endif
   95334 #ifdef SQLITE_OMIT_VIEW
   95335 # undef isView
   95336 # define isView 0
   95337 #endif
   95338   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
   95339 
   95340   /* If pTab is really a view, make sure it has been initialized.
   95341   ** ViewGetColumnNames() is a no-op if pTab is not a view.
   95342   */
   95343   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
   95344     goto insert_cleanup;
   95345   }
   95346 
   95347   /* Cannot insert into a read-only table.
   95348   */
   95349   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
   95350     goto insert_cleanup;
   95351   }
   95352 
   95353   /* Allocate a VDBE
   95354   */
   95355   v = sqlite3GetVdbe(pParse);
   95356   if( v==0 ) goto insert_cleanup;
   95357   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
   95358   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
   95359 
   95360 #ifndef SQLITE_OMIT_XFER_OPT
   95361   /* If the statement is of the form
   95362   **
   95363   **       INSERT INTO <table1> SELECT * FROM <table2>;
   95364   **
   95365   ** Then special optimizations can be applied that make the transfer
   95366   ** very fast and which reduce fragmentation of indices.
   95367   **
   95368   ** This is the 2nd template.
   95369   */
   95370   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
   95371     assert( !pTrigger );
   95372     assert( pList==0 );
   95373     goto insert_end;
   95374   }
   95375 #endif /* SQLITE_OMIT_XFER_OPT */
   95376 
   95377   /* If this is an AUTOINCREMENT table, look up the sequence number in the
   95378   ** sqlite_sequence table and store it in memory cell regAutoinc.
   95379   */
   95380   regAutoinc = autoIncBegin(pParse, iDb, pTab);
   95381 
   95382   /* Allocate registers for holding the rowid of the new row,
   95383   ** the content of the new row, and the assemblied row record.
   95384   */
   95385   regRowid = regIns = pParse->nMem+1;
   95386   pParse->nMem += pTab->nCol + 1;
   95387   if( IsVirtual(pTab) ){
   95388     regRowid++;
   95389     pParse->nMem++;
   95390   }
   95391   regData = regRowid+1;
   95392 
   95393   /* If the INSERT statement included an IDLIST term, then make sure
   95394   ** all elements of the IDLIST really are columns of the table and
   95395   ** remember the column indices.
   95396   **
   95397   ** If the table has an INTEGER PRIMARY KEY column and that column
   95398   ** is named in the IDLIST, then record in the ipkColumn variable
   95399   ** the index into IDLIST of the primary key column.  ipkColumn is
   95400   ** the index of the primary key as it appears in IDLIST, not as
   95401   ** is appears in the original table.  (The index of the INTEGER
   95402   ** PRIMARY KEY in the original table is pTab->iPKey.)
   95403   */
   95404   if( pColumn ){
   95405     for(i=0; i<pColumn->nId; i++){
   95406       pColumn->a[i].idx = -1;
   95407     }
   95408     for(i=0; i<pColumn->nId; i++){
   95409       for(j=0; j<pTab->nCol; j++){
   95410         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
   95411           pColumn->a[i].idx = j;
   95412           if( i!=j ) bIdListInOrder = 0;
   95413           if( j==pTab->iPKey ){
   95414             ipkColumn = i;  assert( !withoutRowid );
   95415           }
   95416           break;
   95417         }
   95418       }
   95419       if( j>=pTab->nCol ){
   95420         if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
   95421           ipkColumn = i;
   95422           bIdListInOrder = 0;
   95423         }else{
   95424           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
   95425               pTabList, 0, pColumn->a[i].zName);
   95426           pParse->checkSchema = 1;
   95427           goto insert_cleanup;
   95428         }
   95429       }
   95430     }
   95431   }
   95432 
   95433   /* Figure out how many columns of data are supplied.  If the data
   95434   ** is coming from a SELECT statement, then generate a co-routine that
   95435   ** produces a single row of the SELECT on each invocation.  The
   95436   ** co-routine is the common header to the 3rd and 4th templates.
   95437   */
   95438   if( pSelect ){
   95439     /* Data is coming from a SELECT.  Generate a co-routine to run the SELECT */
   95440     int regYield;       /* Register holding co-routine entry-point */
   95441     int addrTop;        /* Top of the co-routine */
   95442     int rc;             /* Result code */
   95443 
   95444     regYield = ++pParse->nMem;
   95445     addrTop = sqlite3VdbeCurrentAddr(v) + 1;
   95446     sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
   95447     sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
   95448     dest.iSdst = bIdListInOrder ? regData : 0;
   95449     dest.nSdst = pTab->nCol;
   95450     rc = sqlite3Select(pParse, pSelect, &dest);
   95451     regFromSelect = dest.iSdst;
   95452     assert( pParse->nErr==0 || rc );
   95453     if( rc || db->mallocFailed ) goto insert_cleanup;
   95454     sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
   95455     sqlite3VdbeJumpHere(v, addrTop - 1);                       /* label B: */
   95456     assert( pSelect->pEList );
   95457     nColumn = pSelect->pEList->nExpr;
   95458 
   95459     /* Set useTempTable to TRUE if the result of the SELECT statement
   95460     ** should be written into a temporary table (template 4).  Set to
   95461     ** FALSE if each output row of the SELECT can be written directly into
   95462     ** the destination table (template 3).
   95463     **
   95464     ** A temp table must be used if the table being updated is also one
   95465     ** of the tables being read by the SELECT statement.  Also use a
   95466     ** temp table in the case of row triggers.
   95467     */
   95468     if( pTrigger || readsTable(pParse, iDb, pTab) ){
   95469       useTempTable = 1;
   95470     }
   95471 
   95472     if( useTempTable ){
   95473       /* Invoke the coroutine to extract information from the SELECT
   95474       ** and add it to a transient table srcTab.  The code generated
   95475       ** here is from the 4th template:
   95476       **
   95477       **      B: open temp table
   95478       **      L: yield X, goto M at EOF
   95479       **         insert row from R..R+n into temp table
   95480       **         goto L
   95481       **      M: ...
   95482       */
   95483       int regRec;          /* Register to hold packed record */
   95484       int regTempRowid;    /* Register to hold temp table ROWID */
   95485       int addrL;           /* Label "L" */
   95486 
   95487       srcTab = pParse->nTab++;
   95488       regRec = sqlite3GetTempReg(pParse);
   95489       regTempRowid = sqlite3GetTempReg(pParse);
   95490       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
   95491       addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
   95492       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
   95493       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
   95494       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
   95495       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrL);
   95496       sqlite3VdbeJumpHere(v, addrL);
   95497       sqlite3ReleaseTempReg(pParse, regRec);
   95498       sqlite3ReleaseTempReg(pParse, regTempRowid);
   95499     }
   95500   }else{
   95501     /* This is the case if the data for the INSERT is coming from a VALUES
   95502     ** clause
   95503     */
   95504     NameContext sNC;
   95505     memset(&sNC, 0, sizeof(sNC));
   95506     sNC.pParse = pParse;
   95507     srcTab = -1;
   95508     assert( useTempTable==0 );
   95509     nColumn = pList ? pList->nExpr : 0;
   95510     for(i=0; i<nColumn; i++){
   95511       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
   95512         goto insert_cleanup;
   95513       }
   95514     }
   95515   }
   95516 
   95517   /* If there is no IDLIST term but the table has an integer primary
   95518   ** key, the set the ipkColumn variable to the integer primary key
   95519   ** column index in the original table definition.
   95520   */
   95521   if( pColumn==0 && nColumn>0 ){
   95522     ipkColumn = pTab->iPKey;
   95523   }
   95524 
   95525   /* Make sure the number of columns in the source data matches the number
   95526   ** of columns to be inserted into the table.
   95527   */
   95528   if( IsVirtual(pTab) ){
   95529     for(i=0; i<pTab->nCol; i++){
   95530       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
   95531     }
   95532   }
   95533   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
   95534     sqlite3ErrorMsg(pParse,
   95535        "table %S has %d columns but %d values were supplied",
   95536        pTabList, 0, pTab->nCol-nHidden, nColumn);
   95537     goto insert_cleanup;
   95538   }
   95539   if( pColumn!=0 && nColumn!=pColumn->nId ){
   95540     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
   95541     goto insert_cleanup;
   95542   }
   95543 
   95544   /* Initialize the count of rows to be inserted
   95545   */
   95546   if( db->flags & SQLITE_CountRows ){
   95547     regRowCount = ++pParse->nMem;
   95548     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
   95549   }
   95550 
   95551   /* If this is not a view, open the table and and all indices */
   95552   if( !isView ){
   95553     int nIdx;
   95554     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, -1, 0,
   95555                                       &iDataCur, &iIdxCur);
   95556     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
   95557     if( aRegIdx==0 ){
   95558       goto insert_cleanup;
   95559     }
   95560     for(i=0; i<nIdx; i++){
   95561       aRegIdx[i] = ++pParse->nMem;
   95562     }
   95563   }
   95564 
   95565   /* This is the top of the main insertion loop */
   95566   if( useTempTable ){
   95567     /* This block codes the top of loop only.  The complete loop is the
   95568     ** following pseudocode (template 4):
   95569     **
   95570     **         rewind temp table, if empty goto D
   95571     **      C: loop over rows of intermediate table
   95572     **           transfer values form intermediate table into <table>
   95573     **         end loop
   95574     **      D: ...
   95575     */
   95576     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
   95577     addrCont = sqlite3VdbeCurrentAddr(v);
   95578   }else if( pSelect ){
   95579     /* This block codes the top of loop only.  The complete loop is the
   95580     ** following pseudocode (template 3):
   95581     **
   95582     **      C: yield X, at EOF goto D
   95583     **         insert the select result into <table> from R..R+n
   95584     **         goto C
   95585     **      D: ...
   95586     */
   95587     addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
   95588     VdbeCoverage(v);
   95589   }
   95590 
   95591   /* Run the BEFORE and INSTEAD OF triggers, if there are any
   95592   */
   95593   endOfLoop = sqlite3VdbeMakeLabel(v);
   95594   if( tmask & TRIGGER_BEFORE ){
   95595     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
   95596 
   95597     /* build the NEW.* reference row.  Note that if there is an INTEGER
   95598     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
   95599     ** translated into a unique ID for the row.  But on a BEFORE trigger,
   95600     ** we do not know what the unique ID will be (because the insert has
   95601     ** not happened yet) so we substitute a rowid of -1
   95602     */
   95603     if( ipkColumn<0 ){
   95604       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
   95605     }else{
   95606       int j1;
   95607       assert( !withoutRowid );
   95608       if( useTempTable ){
   95609         sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
   95610       }else{
   95611         assert( pSelect==0 );  /* Otherwise useTempTable is true */
   95612         sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
   95613       }
   95614       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
   95615       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
   95616       sqlite3VdbeJumpHere(v, j1);
   95617       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
   95618     }
   95619 
   95620     /* Cannot have triggers on a virtual table. If it were possible,
   95621     ** this block would have to account for hidden column.
   95622     */
   95623     assert( !IsVirtual(pTab) );
   95624 
   95625     /* Create the new column data
   95626     */
   95627     for(i=0; i<pTab->nCol; i++){
   95628       if( pColumn==0 ){
   95629         j = i;
   95630       }else{
   95631         for(j=0; j<pColumn->nId; j++){
   95632           if( pColumn->a[j].idx==i ) break;
   95633         }
   95634       }
   95635       if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
   95636         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
   95637       }else if( useTempTable ){
   95638         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
   95639       }else{
   95640         assert( pSelect==0 ); /* Otherwise useTempTable is true */
   95641         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
   95642       }
   95643     }
   95644 
   95645     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
   95646     ** do not attempt any conversions before assembling the record.
   95647     ** If this is a real table, attempt conversions as required by the
   95648     ** table column affinities.
   95649     */
   95650     if( !isView ){
   95651       sqlite3TableAffinity(v, pTab, regCols+1);
   95652     }
   95653 
   95654     /* Fire BEFORE or INSTEAD OF triggers */
   95655     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
   95656         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
   95657 
   95658     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
   95659   }
   95660 
   95661   /* Compute the content of the next row to insert into a range of
   95662   ** registers beginning at regIns.
   95663   */
   95664   if( !isView ){
   95665     if( IsVirtual(pTab) ){
   95666       /* The row that the VUpdate opcode will delete: none */
   95667       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
   95668     }
   95669     if( ipkColumn>=0 ){
   95670       if( useTempTable ){
   95671         sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
   95672       }else if( pSelect ){
   95673         sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
   95674       }else{
   95675         VdbeOp *pOp;
   95676         sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
   95677         pOp = sqlite3VdbeGetOp(v, -1);
   95678         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
   95679           appendFlag = 1;
   95680           pOp->opcode = OP_NewRowid;
   95681           pOp->p1 = iDataCur;
   95682           pOp->p2 = regRowid;
   95683           pOp->p3 = regAutoinc;
   95684         }
   95685       }
   95686       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
   95687       ** to generate a unique primary key value.
   95688       */
   95689       if( !appendFlag ){
   95690         int j1;
   95691         if( !IsVirtual(pTab) ){
   95692           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
   95693           sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
   95694           sqlite3VdbeJumpHere(v, j1);
   95695         }else{
   95696           j1 = sqlite3VdbeCurrentAddr(v);
   95697           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2); VdbeCoverage(v);
   95698         }
   95699         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
   95700       }
   95701     }else if( IsVirtual(pTab) || withoutRowid ){
   95702       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
   95703     }else{
   95704       sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
   95705       appendFlag = 1;
   95706     }
   95707     autoIncStep(pParse, regAutoinc, regRowid);
   95708 
   95709     /* Compute data for all columns of the new entry, beginning
   95710     ** with the first column.
   95711     */
   95712     nHidden = 0;
   95713     for(i=0; i<pTab->nCol; i++){
   95714       int iRegStore = regRowid+1+i;
   95715       if( i==pTab->iPKey ){
   95716         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
   95717         ** Whenever this column is read, the rowid will be substituted
   95718         ** in its place.  Hence, fill this column with a NULL to avoid
   95719         ** taking up data space with information that will never be used.
   95720         ** As there may be shallow copies of this value, make it a soft-NULL */
   95721         sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
   95722         continue;
   95723       }
   95724       if( pColumn==0 ){
   95725         if( IsHiddenColumn(&pTab->aCol[i]) ){
   95726           assert( IsVirtual(pTab) );
   95727           j = -1;
   95728           nHidden++;
   95729         }else{
   95730           j = i - nHidden;
   95731         }
   95732       }else{
   95733         for(j=0; j<pColumn->nId; j++){
   95734           if( pColumn->a[j].idx==i ) break;
   95735         }
   95736       }
   95737       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
   95738         sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
   95739       }else if( useTempTable ){
   95740         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
   95741       }else if( pSelect ){
   95742         if( regFromSelect!=regData ){
   95743           sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
   95744         }
   95745       }else{
   95746         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
   95747       }
   95748     }
   95749 
   95750     /* Generate code to check constraints and generate index keys and
   95751     ** do the insertion.
   95752     */
   95753 #ifndef SQLITE_OMIT_VIRTUALTABLE
   95754     if( IsVirtual(pTab) ){
   95755       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
   95756       sqlite3VtabMakeWritable(pParse, pTab);
   95757       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
   95758       sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
   95759       sqlite3MayAbort(pParse);
   95760     }else
   95761 #endif
   95762     {
   95763       int isReplace;    /* Set to true if constraints may cause a replace */
   95764       sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
   95765           regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace
   95766       );
   95767       sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
   95768       sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
   95769                                regIns, aRegIdx, 0, appendFlag, isReplace==0);
   95770     }
   95771   }
   95772 
   95773   /* Update the count of rows that are inserted
   95774   */
   95775   if( (db->flags & SQLITE_CountRows)!=0 ){
   95776     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
   95777   }
   95778 
   95779   if( pTrigger ){
   95780     /* Code AFTER triggers */
   95781     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
   95782         pTab, regData-2-pTab->nCol, onError, endOfLoop);
   95783   }
   95784 
   95785   /* The bottom of the main insertion loop, if the data source
   95786   ** is a SELECT statement.
   95787   */
   95788   sqlite3VdbeResolveLabel(v, endOfLoop);
   95789   if( useTempTable ){
   95790     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
   95791     sqlite3VdbeJumpHere(v, addrInsTop);
   95792     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
   95793   }else if( pSelect ){
   95794     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
   95795     sqlite3VdbeJumpHere(v, addrInsTop);
   95796   }
   95797 
   95798   if( !IsVirtual(pTab) && !isView ){
   95799     /* Close all tables opened */
   95800     if( iDataCur<iIdxCur ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
   95801     for(idx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
   95802       sqlite3VdbeAddOp1(v, OP_Close, idx+iIdxCur);
   95803     }
   95804   }
   95805 
   95806 insert_end:
   95807   /* Update the sqlite_sequence table by storing the content of the
   95808   ** maximum rowid counter values recorded while inserting into
   95809   ** autoincrement tables.
   95810   */
   95811   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
   95812     sqlite3AutoincrementEnd(pParse);
   95813   }
   95814 
   95815   /*
   95816   ** Return the number of rows inserted. If this routine is
   95817   ** generating code because of a call to sqlite3NestedParse(), do not
   95818   ** invoke the callback function.
   95819   */
   95820   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
   95821     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
   95822     sqlite3VdbeSetNumCols(v, 1);
   95823     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
   95824   }
   95825 
   95826 insert_cleanup:
   95827   sqlite3SrcListDelete(db, pTabList);
   95828   sqlite3ExprListDelete(db, pList);
   95829   sqlite3SelectDelete(db, pSelect);
   95830   sqlite3IdListDelete(db, pColumn);
   95831   sqlite3DbFree(db, aRegIdx);
   95832 }
   95833 
   95834 /* Make sure "isView" and other macros defined above are undefined. Otherwise
   95835 ** thely may interfere with compilation of other functions in this file
   95836 ** (or in another file, if this file becomes part of the amalgamation).  */
   95837 #ifdef isView
   95838  #undef isView
   95839 #endif
   95840 #ifdef pTrigger
   95841  #undef pTrigger
   95842 #endif
   95843 #ifdef tmask
   95844  #undef tmask
   95845 #endif
   95846 
   95847 /*
   95848 ** Generate code to do constraint checks prior to an INSERT or an UPDATE
   95849 ** on table pTab.
   95850 **
   95851 ** The regNewData parameter is the first register in a range that contains
   95852 ** the data to be inserted or the data after the update.  There will be
   95853 ** pTab->nCol+1 registers in this range.  The first register (the one
   95854 ** that regNewData points to) will contain the new rowid, or NULL in the
   95855 ** case of a WITHOUT ROWID table.  The second register in the range will
   95856 ** contain the content of the first table column.  The third register will
   95857 ** contain the content of the second table column.  And so forth.
   95858 **
   95859 ** The regOldData parameter is similar to regNewData except that it contains
   95860 ** the data prior to an UPDATE rather than afterwards.  regOldData is zero
   95861 ** for an INSERT.  This routine can distinguish between UPDATE and INSERT by
   95862 ** checking regOldData for zero.
   95863 **
   95864 ** For an UPDATE, the pkChng boolean is true if the true primary key (the
   95865 ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
   95866 ** might be modified by the UPDATE.  If pkChng is false, then the key of
   95867 ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
   95868 **
   95869 ** For an INSERT, the pkChng boolean indicates whether or not the rowid
   95870 ** was explicitly specified as part of the INSERT statement.  If pkChng
   95871 ** is zero, it means that the either rowid is computed automatically or
   95872 ** that the table is a WITHOUT ROWID table and has no rowid.  On an INSERT,
   95873 ** pkChng will only be true if the INSERT statement provides an integer
   95874 ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
   95875 **
   95876 ** The code generated by this routine will store new index entries into
   95877 ** registers identified by aRegIdx[].  No index entry is created for
   95878 ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
   95879 ** the same as the order of indices on the linked list of indices
   95880 ** at pTab->pIndex.
   95881 **
   95882 ** The caller must have already opened writeable cursors on the main
   95883 ** table and all applicable indices (that is to say, all indices for which
   95884 ** aRegIdx[] is not zero).  iDataCur is the cursor for the main table when
   95885 ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
   95886 ** index when operating on a WITHOUT ROWID table.  iIdxCur is the cursor
   95887 ** for the first index in the pTab->pIndex list.  Cursors for other indices
   95888 ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
   95889 **
   95890 ** This routine also generates code to check constraints.  NOT NULL,
   95891 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
   95892 ** then the appropriate action is performed.  There are five possible
   95893 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
   95894 **
   95895 **  Constraint type  Action       What Happens
   95896 **  ---------------  ----------   ----------------------------------------
   95897 **  any              ROLLBACK     The current transaction is rolled back and
   95898 **                                sqlite3_step() returns immediately with a
   95899 **                                return code of SQLITE_CONSTRAINT.
   95900 **
   95901 **  any              ABORT        Back out changes from the current command
   95902 **                                only (do not do a complete rollback) then
   95903 **                                cause sqlite3_step() to return immediately
   95904 **                                with SQLITE_CONSTRAINT.
   95905 **
   95906 **  any              FAIL         Sqlite3_step() returns immediately with a
   95907 **                                return code of SQLITE_CONSTRAINT.  The
   95908 **                                transaction is not rolled back and any
   95909 **                                changes to prior rows are retained.
   95910 **
   95911 **  any              IGNORE       The attempt in insert or update the current
   95912 **                                row is skipped, without throwing an error.
   95913 **                                Processing continues with the next row.
   95914 **                                (There is an immediate jump to ignoreDest.)
   95915 **
   95916 **  NOT NULL         REPLACE      The NULL value is replace by the default
   95917 **                                value for that column.  If the default value
   95918 **                                is NULL, the action is the same as ABORT.
   95919 **
   95920 **  UNIQUE           REPLACE      The other row that conflicts with the row
   95921 **                                being inserted is removed.
   95922 **
   95923 **  CHECK            REPLACE      Illegal.  The results in an exception.
   95924 **
   95925 ** Which action to take is determined by the overrideError parameter.
   95926 ** Or if overrideError==OE_Default, then the pParse->onError parameter
   95927 ** is used.  Or if pParse->onError==OE_Default then the onError value
   95928 ** for the constraint is used.
   95929 */
   95930 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
   95931   Parse *pParse,       /* The parser context */
   95932   Table *pTab,         /* The table being inserted or updated */
   95933   int *aRegIdx,        /* Use register aRegIdx[i] for index i.  0 for unused */
   95934   int iDataCur,        /* Canonical data cursor (main table or PK index) */
   95935   int iIdxCur,         /* First index cursor */
   95936   int regNewData,      /* First register in a range holding values to insert */
   95937   int regOldData,      /* Previous content.  0 for INSERTs */
   95938   u8 pkChng,           /* Non-zero if the rowid or PRIMARY KEY changed */
   95939   u8 overrideError,    /* Override onError to this if not OE_Default */
   95940   int ignoreDest,      /* Jump to this label on an OE_Ignore resolution */
   95941   int *pbMayReplace    /* OUT: Set to true if constraint may cause a replace */
   95942 ){
   95943   Vdbe *v;             /* VDBE under constrution */
   95944   Index *pIdx;         /* Pointer to one of the indices */
   95945   Index *pPk = 0;      /* The PRIMARY KEY index */
   95946   sqlite3 *db;         /* Database connection */
   95947   int i;               /* loop counter */
   95948   int ix;              /* Index loop counter */
   95949   int nCol;            /* Number of columns */
   95950   int onError;         /* Conflict resolution strategy */
   95951   int j1;              /* Addresss of jump instruction */
   95952   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
   95953   int nPkField;        /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
   95954   int ipkTop = 0;      /* Top of the rowid change constraint check */
   95955   int ipkBottom = 0;   /* Bottom of the rowid change constraint check */
   95956   u8 isUpdate;         /* True if this is an UPDATE operation */
   95957   u8 bAffinityDone = 0;  /* True if the OP_Affinity operation has been run */
   95958   int regRowid = -1;   /* Register holding ROWID value */
   95959 
   95960   isUpdate = regOldData!=0;
   95961   db = pParse->db;
   95962   v = sqlite3GetVdbe(pParse);
   95963   assert( v!=0 );
   95964   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
   95965   nCol = pTab->nCol;
   95966 
   95967   /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
   95968   ** normal rowid tables.  nPkField is the number of key fields in the
   95969   ** pPk index or 1 for a rowid table.  In other words, nPkField is the
   95970   ** number of fields in the true primary key of the table. */
   95971   if( HasRowid(pTab) ){
   95972     pPk = 0;
   95973     nPkField = 1;
   95974   }else{
   95975     pPk = sqlite3PrimaryKeyIndex(pTab);
   95976     nPkField = pPk->nKeyCol;
   95977   }
   95978 
   95979   /* Record that this module has started */
   95980   VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
   95981                      iDataCur, iIdxCur, regNewData, regOldData, pkChng));
   95982 
   95983   /* Test all NOT NULL constraints.
   95984   */
   95985   for(i=0; i<nCol; i++){
   95986     if( i==pTab->iPKey ){
   95987       continue;
   95988     }
   95989     onError = pTab->aCol[i].notNull;
   95990     if( onError==OE_None ) continue;
   95991     if( overrideError!=OE_Default ){
   95992       onError = overrideError;
   95993     }else if( onError==OE_Default ){
   95994       onError = OE_Abort;
   95995     }
   95996     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
   95997       onError = OE_Abort;
   95998     }
   95999     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
   96000         || onError==OE_Ignore || onError==OE_Replace );
   96001     switch( onError ){
   96002       case OE_Abort:
   96003         sqlite3MayAbort(pParse);
   96004         /* Fall through */
   96005       case OE_Rollback:
   96006       case OE_Fail: {
   96007         char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
   96008                                     pTab->aCol[i].zName);
   96009         sqlite3VdbeAddOp4(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
   96010                           regNewData+1+i, zMsg, P4_DYNAMIC);
   96011         sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
   96012         VdbeCoverage(v);
   96013         break;
   96014       }
   96015       case OE_Ignore: {
   96016         sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
   96017         VdbeCoverage(v);
   96018         break;
   96019       }
   96020       default: {
   96021         assert( onError==OE_Replace );
   96022         j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i); VdbeCoverage(v);
   96023         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
   96024         sqlite3VdbeJumpHere(v, j1);
   96025         break;
   96026       }
   96027     }
   96028   }
   96029 
   96030   /* Test all CHECK constraints
   96031   */
   96032 #ifndef SQLITE_OMIT_CHECK
   96033   if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
   96034     ExprList *pCheck = pTab->pCheck;
   96035     pParse->ckBase = regNewData+1;
   96036     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
   96037     for(i=0; i<pCheck->nExpr; i++){
   96038       int allOk = sqlite3VdbeMakeLabel(v);
   96039       sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
   96040       if( onError==OE_Ignore ){
   96041         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
   96042       }else{
   96043         char *zName = pCheck->a[i].zName;
   96044         if( zName==0 ) zName = pTab->zName;
   96045         if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
   96046         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
   96047                               onError, zName, P4_TRANSIENT,
   96048                               P5_ConstraintCheck);
   96049       }
   96050       sqlite3VdbeResolveLabel(v, allOk);
   96051     }
   96052   }
   96053 #endif /* !defined(SQLITE_OMIT_CHECK) */
   96054 
   96055   /* If rowid is changing, make sure the new rowid does not previously
   96056   ** exist in the table.
   96057   */
   96058   if( pkChng && pPk==0 ){
   96059     int addrRowidOk = sqlite3VdbeMakeLabel(v);
   96060 
   96061     /* Figure out what action to take in case of a rowid collision */
   96062     onError = pTab->keyConf;
   96063     if( overrideError!=OE_Default ){
   96064       onError = overrideError;
   96065     }else if( onError==OE_Default ){
   96066       onError = OE_Abort;
   96067     }
   96068 
   96069     if( isUpdate ){
   96070       /* pkChng!=0 does not mean that the rowid has change, only that
   96071       ** it might have changed.  Skip the conflict logic below if the rowid
   96072       ** is unchanged. */
   96073       sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
   96074       sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
   96075       VdbeCoverage(v);
   96076     }
   96077 
   96078     /* If the response to a rowid conflict is REPLACE but the response
   96079     ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
   96080     ** to defer the running of the rowid conflict checking until after
   96081     ** the UNIQUE constraints have run.
   96082     */
   96083     if( onError==OE_Replace && overrideError!=OE_Replace ){
   96084       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   96085         if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){
   96086           ipkTop = sqlite3VdbeAddOp0(v, OP_Goto);
   96087           break;
   96088         }
   96089       }
   96090     }
   96091 
   96092     /* Check to see if the new rowid already exists in the table.  Skip
   96093     ** the following conflict logic if it does not. */
   96094     sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
   96095     VdbeCoverage(v);
   96096 
   96097     /* Generate code that deals with a rowid collision */
   96098     switch( onError ){
   96099       default: {
   96100         onError = OE_Abort;
   96101         /* Fall thru into the next case */
   96102       }
   96103       case OE_Rollback:
   96104       case OE_Abort:
   96105       case OE_Fail: {
   96106         sqlite3RowidConstraint(pParse, onError, pTab);
   96107         break;
   96108       }
   96109       case OE_Replace: {
   96110         /* If there are DELETE triggers on this table and the
   96111         ** recursive-triggers flag is set, call GenerateRowDelete() to
   96112         ** remove the conflicting row from the table. This will fire
   96113         ** the triggers and remove both the table and index b-tree entries.
   96114         **
   96115         ** Otherwise, if there are no triggers or the recursive-triggers
   96116         ** flag is not set, but the table has one or more indexes, call
   96117         ** GenerateRowIndexDelete(). This removes the index b-tree entries
   96118         ** only. The table b-tree entry will be replaced by the new entry
   96119         ** when it is inserted.
   96120         **
   96121         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
   96122         ** also invoke MultiWrite() to indicate that this VDBE may require
   96123         ** statement rollback (if the statement is aborted after the delete
   96124         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
   96125         ** but being more selective here allows statements like:
   96126         **
   96127         **   REPLACE INTO t(rowid) VALUES($newrowid)
   96128         **
   96129         ** to run without a statement journal if there are no indexes on the
   96130         ** table.
   96131         */
   96132         Trigger *pTrigger = 0;
   96133         if( db->flags&SQLITE_RecTriggers ){
   96134           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
   96135         }
   96136         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
   96137           sqlite3MultiWrite(pParse);
   96138           sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
   96139                                    regNewData, 1, 0, OE_Replace, 1);
   96140         }else if( pTab->pIndex ){
   96141           sqlite3MultiWrite(pParse);
   96142           sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, 0);
   96143         }
   96144         seenReplace = 1;
   96145         break;
   96146       }
   96147       case OE_Ignore: {
   96148         /*assert( seenReplace==0 );*/
   96149         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
   96150         break;
   96151       }
   96152     }
   96153     sqlite3VdbeResolveLabel(v, addrRowidOk);
   96154     if( ipkTop ){
   96155       ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
   96156       sqlite3VdbeJumpHere(v, ipkTop);
   96157     }
   96158   }
   96159 
   96160   /* Test all UNIQUE constraints by creating entries for each UNIQUE
   96161   ** index and making sure that duplicate entries do not already exist.
   96162   ** Compute the revised record entries for indices as we go.
   96163   **
   96164   ** This loop also handles the case of the PRIMARY KEY index for a
   96165   ** WITHOUT ROWID table.
   96166   */
   96167   for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
   96168     int regIdx;          /* Range of registers hold conent for pIdx */
   96169     int regR;            /* Range of registers holding conflicting PK */
   96170     int iThisCur;        /* Cursor for this UNIQUE index */
   96171     int addrUniqueOk;    /* Jump here if the UNIQUE constraint is satisfied */
   96172 
   96173     if( aRegIdx[ix]==0 ) continue;  /* Skip indices that do not change */
   96174     if( bAffinityDone==0 ){
   96175       sqlite3TableAffinity(v, pTab, regNewData+1);
   96176       bAffinityDone = 1;
   96177     }
   96178     iThisCur = iIdxCur+ix;
   96179     addrUniqueOk = sqlite3VdbeMakeLabel(v);
   96180 
   96181     /* Skip partial indices for which the WHERE clause is not true */
   96182     if( pIdx->pPartIdxWhere ){
   96183       sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
   96184       pParse->ckBase = regNewData+1;
   96185       sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
   96186                          SQLITE_JUMPIFNULL);
   96187       pParse->ckBase = 0;
   96188     }
   96189 
   96190     /* Create a record for this index entry as it should appear after
   96191     ** the insert or update.  Store that record in the aRegIdx[ix] register
   96192     */
   96193     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn);
   96194     for(i=0; i<pIdx->nColumn; i++){
   96195       int iField = pIdx->aiColumn[i];
   96196       int x;
   96197       if( iField<0 || iField==pTab->iPKey ){
   96198         if( regRowid==regIdx+i ) continue; /* ROWID already in regIdx+i */
   96199         x = regNewData;
   96200         regRowid =  pIdx->pPartIdxWhere ? -1 : regIdx+i;
   96201       }else{
   96202         x = iField + regNewData + 1;
   96203       }
   96204       sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i);
   96205       VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
   96206     }
   96207     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
   96208     VdbeComment((v, "for %s", pIdx->zName));
   96209     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn);
   96210 
   96211     /* In an UPDATE operation, if this index is the PRIMARY KEY index
   96212     ** of a WITHOUT ROWID table and there has been no change the
   96213     ** primary key, then no collision is possible.  The collision detection
   96214     ** logic below can all be skipped. */
   96215     if( isUpdate && pPk==pIdx && pkChng==0 ){
   96216       sqlite3VdbeResolveLabel(v, addrUniqueOk);
   96217       continue;
   96218     }
   96219 
   96220     /* Find out what action to take in case there is a uniqueness conflict */
   96221     onError = pIdx->onError;
   96222     if( onError==OE_None ){
   96223       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
   96224       sqlite3VdbeResolveLabel(v, addrUniqueOk);
   96225       continue;  /* pIdx is not a UNIQUE index */
   96226     }
   96227     if( overrideError!=OE_Default ){
   96228       onError = overrideError;
   96229     }else if( onError==OE_Default ){
   96230       onError = OE_Abort;
   96231     }
   96232 
   96233     /* Check to see if the new index entry will be unique */
   96234     sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
   96235                          regIdx, pIdx->nKeyCol); VdbeCoverage(v);
   96236 
   96237     /* Generate code to handle collisions */
   96238     regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
   96239     if( isUpdate || onError==OE_Replace ){
   96240       if( HasRowid(pTab) ){
   96241         sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
   96242         /* Conflict only if the rowid of the existing index entry
   96243         ** is different from old-rowid */
   96244         if( isUpdate ){
   96245           sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
   96246           sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
   96247           VdbeCoverage(v);
   96248         }
   96249       }else{
   96250         int x;
   96251         /* Extract the PRIMARY KEY from the end of the index entry and
   96252         ** store it in registers regR..regR+nPk-1 */
   96253         if( pIdx!=pPk ){
   96254           for(i=0; i<pPk->nKeyCol; i++){
   96255             x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
   96256             sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
   96257             VdbeComment((v, "%s.%s", pTab->zName,
   96258                          pTab->aCol[pPk->aiColumn[i]].zName));
   96259           }
   96260         }
   96261         if( isUpdate ){
   96262           /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
   96263           ** table, only conflict if the new PRIMARY KEY values are actually
   96264           ** different from the old.
   96265           **
   96266           ** For a UNIQUE index, only conflict if the PRIMARY KEY values
   96267           ** of the matched index row are different from the original PRIMARY
   96268           ** KEY values of this row before the update.  */
   96269           int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
   96270           int op = OP_Ne;
   96271           int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
   96272 
   96273           for(i=0; i<pPk->nKeyCol; i++){
   96274             char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
   96275             x = pPk->aiColumn[i];
   96276             if( i==(pPk->nKeyCol-1) ){
   96277               addrJump = addrUniqueOk;
   96278               op = OP_Eq;
   96279             }
   96280             sqlite3VdbeAddOp4(v, op,
   96281                 regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
   96282             );
   96283             sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
   96284             VdbeCoverageIf(v, op==OP_Eq);
   96285             VdbeCoverageIf(v, op==OP_Ne);
   96286           }
   96287         }
   96288       }
   96289     }
   96290 
   96291     /* Generate code that executes if the new index entry is not unique */
   96292     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
   96293         || onError==OE_Ignore || onError==OE_Replace );
   96294     switch( onError ){
   96295       case OE_Rollback:
   96296       case OE_Abort:
   96297       case OE_Fail: {
   96298         sqlite3UniqueConstraint(pParse, onError, pIdx);
   96299         break;
   96300       }
   96301       case OE_Ignore: {
   96302         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
   96303         break;
   96304       }
   96305       default: {
   96306         Trigger *pTrigger = 0;
   96307         assert( onError==OE_Replace );
   96308         sqlite3MultiWrite(pParse);
   96309         if( db->flags&SQLITE_RecTriggers ){
   96310           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
   96311         }
   96312         sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
   96313                                  regR, nPkField, 0, OE_Replace, pIdx==pPk);
   96314         seenReplace = 1;
   96315         break;
   96316       }
   96317     }
   96318     sqlite3VdbeResolveLabel(v, addrUniqueOk);
   96319     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
   96320     if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
   96321   }
   96322   if( ipkTop ){
   96323     sqlite3VdbeAddOp2(v, OP_Goto, 0, ipkTop+1);
   96324     sqlite3VdbeJumpHere(v, ipkBottom);
   96325   }
   96326 
   96327   *pbMayReplace = seenReplace;
   96328   VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
   96329 }
   96330 
   96331 /*
   96332 ** This routine generates code to finish the INSERT or UPDATE operation
   96333 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
   96334 ** A consecutive range of registers starting at regNewData contains the
   96335 ** rowid and the content to be inserted.
   96336 **
   96337 ** The arguments to this routine should be the same as the first six
   96338 ** arguments to sqlite3GenerateConstraintChecks.
   96339 */
   96340 SQLITE_PRIVATE void sqlite3CompleteInsertion(
   96341   Parse *pParse,      /* The parser context */
   96342   Table *pTab,        /* the table into which we are inserting */
   96343   int iDataCur,       /* Cursor of the canonical data source */
   96344   int iIdxCur,        /* First index cursor */
   96345   int regNewData,     /* Range of content */
   96346   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
   96347   int isUpdate,       /* True for UPDATE, False for INSERT */
   96348   int appendBias,     /* True if this is likely to be an append */
   96349   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
   96350 ){
   96351   Vdbe *v;            /* Prepared statements under construction */
   96352   Index *pIdx;        /* An index being inserted or updated */
   96353   u8 pik_flags;       /* flag values passed to the btree insert */
   96354   int regData;        /* Content registers (after the rowid) */
   96355   int regRec;         /* Register holding assemblied record for the table */
   96356   int i;              /* Loop counter */
   96357   u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
   96358 
   96359   v = sqlite3GetVdbe(pParse);
   96360   assert( v!=0 );
   96361   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
   96362   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
   96363     if( aRegIdx[i]==0 ) continue;
   96364     bAffinityDone = 1;
   96365     if( pIdx->pPartIdxWhere ){
   96366       sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
   96367       VdbeCoverage(v);
   96368     }
   96369     sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i]);
   96370     pik_flags = 0;
   96371     if( useSeekResult ) pik_flags = OPFLAG_USESEEKRESULT;
   96372     if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
   96373       assert( pParse->nested==0 );
   96374       pik_flags |= OPFLAG_NCHANGE;
   96375     }
   96376     if( pik_flags )  sqlite3VdbeChangeP5(v, pik_flags);
   96377   }
   96378   if( !HasRowid(pTab) ) return;
   96379   regData = regNewData + 1;
   96380   regRec = sqlite3GetTempReg(pParse);
   96381   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
   96382   if( !bAffinityDone ) sqlite3TableAffinity(v, pTab, 0);
   96383   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
   96384   if( pParse->nested ){
   96385     pik_flags = 0;
   96386   }else{
   96387     pik_flags = OPFLAG_NCHANGE;
   96388     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
   96389   }
   96390   if( appendBias ){
   96391     pik_flags |= OPFLAG_APPEND;
   96392   }
   96393   if( useSeekResult ){
   96394     pik_flags |= OPFLAG_USESEEKRESULT;
   96395   }
   96396   sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
   96397   if( !pParse->nested ){
   96398     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
   96399   }
   96400   sqlite3VdbeChangeP5(v, pik_flags);
   96401 }
   96402 
   96403 /*
   96404 ** Allocate cursors for the pTab table and all its indices and generate
   96405 ** code to open and initialized those cursors.
   96406 **
   96407 ** The cursor for the object that contains the complete data (normally
   96408 ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
   96409 ** ROWID table) is returned in *piDataCur.  The first index cursor is
   96410 ** returned in *piIdxCur.  The number of indices is returned.
   96411 **
   96412 ** Use iBase as the first cursor (either the *piDataCur for rowid tables
   96413 ** or the first index for WITHOUT ROWID tables) if it is non-negative.
   96414 ** If iBase is negative, then allocate the next available cursor.
   96415 **
   96416 ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
   96417 ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
   96418 ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
   96419 ** pTab->pIndex list.
   96420 */
   96421 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
   96422   Parse *pParse,   /* Parsing context */
   96423   Table *pTab,     /* Table to be opened */
   96424   int op,          /* OP_OpenRead or OP_OpenWrite */
   96425   int iBase,       /* Use this for the table cursor, if there is one */
   96426   u8 *aToOpen,     /* If not NULL: boolean for each table and index */
   96427   int *piDataCur,  /* Write the database source cursor number here */
   96428   int *piIdxCur    /* Write the first index cursor number here */
   96429 ){
   96430   int i;
   96431   int iDb;
   96432   int iDataCur;
   96433   Index *pIdx;
   96434   Vdbe *v;
   96435 
   96436   assert( op==OP_OpenRead || op==OP_OpenWrite );
   96437   if( IsVirtual(pTab) ){
   96438     assert( aToOpen==0 );
   96439     *piDataCur = 0;
   96440     *piIdxCur = 1;
   96441     return 0;
   96442   }
   96443   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   96444   v = sqlite3GetVdbe(pParse);
   96445   assert( v!=0 );
   96446   if( iBase<0 ) iBase = pParse->nTab;
   96447   iDataCur = iBase++;
   96448   if( piDataCur ) *piDataCur = iDataCur;
   96449   if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
   96450     sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
   96451   }else{
   96452     sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
   96453   }
   96454   if( piIdxCur ) *piIdxCur = iBase;
   96455   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
   96456     int iIdxCur = iBase++;
   96457     assert( pIdx->pSchema==pTab->pSchema );
   96458     if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) && piDataCur ){
   96459       *piDataCur = iIdxCur;
   96460     }
   96461     if( aToOpen==0 || aToOpen[i+1] ){
   96462       sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
   96463       sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
   96464       VdbeComment((v, "%s", pIdx->zName));
   96465     }
   96466   }
   96467   if( iBase>pParse->nTab ) pParse->nTab = iBase;
   96468   return i;
   96469 }
   96470 
   96471 
   96472 #ifdef SQLITE_TEST
   96473 /*
   96474 ** The following global variable is incremented whenever the
   96475 ** transfer optimization is used.  This is used for testing
   96476 ** purposes only - to make sure the transfer optimization really
   96477 ** is happening when it is suppose to.
   96478 */
   96479 SQLITE_API int sqlite3_xferopt_count;
   96480 #endif /* SQLITE_TEST */
   96481 
   96482 
   96483 #ifndef SQLITE_OMIT_XFER_OPT
   96484 /*
   96485 ** Check to collation names to see if they are compatible.
   96486 */
   96487 static int xferCompatibleCollation(const char *z1, const char *z2){
   96488   if( z1==0 ){
   96489     return z2==0;
   96490   }
   96491   if( z2==0 ){
   96492     return 0;
   96493   }
   96494   return sqlite3StrICmp(z1, z2)==0;
   96495 }
   96496 
   96497 
   96498 /*
   96499 ** Check to see if index pSrc is compatible as a source of data
   96500 ** for index pDest in an insert transfer optimization.  The rules
   96501 ** for a compatible index:
   96502 **
   96503 **    *   The index is over the same set of columns
   96504 **    *   The same DESC and ASC markings occurs on all columns
   96505 **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
   96506 **    *   The same collating sequence on each column
   96507 **    *   The index has the exact same WHERE clause
   96508 */
   96509 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
   96510   int i;
   96511   assert( pDest && pSrc );
   96512   assert( pDest->pTable!=pSrc->pTable );
   96513   if( pDest->nKeyCol!=pSrc->nKeyCol ){
   96514     return 0;   /* Different number of columns */
   96515   }
   96516   if( pDest->onError!=pSrc->onError ){
   96517     return 0;   /* Different conflict resolution strategies */
   96518   }
   96519   for(i=0; i<pSrc->nKeyCol; i++){
   96520     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
   96521       return 0;   /* Different columns indexed */
   96522     }
   96523     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
   96524       return 0;   /* Different sort orders */
   96525     }
   96526     if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
   96527       return 0;   /* Different collating sequences */
   96528     }
   96529   }
   96530   if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
   96531     return 0;     /* Different WHERE clauses */
   96532   }
   96533 
   96534   /* If no test above fails then the indices must be compatible */
   96535   return 1;
   96536 }
   96537 
   96538 /*
   96539 ** Attempt the transfer optimization on INSERTs of the form
   96540 **
   96541 **     INSERT INTO tab1 SELECT * FROM tab2;
   96542 **
   96543 ** The xfer optimization transfers raw records from tab2 over to tab1.
   96544 ** Columns are not decoded and reassemblied, which greatly improves
   96545 ** performance.  Raw index records are transferred in the same way.
   96546 **
   96547 ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
   96548 ** There are lots of rules for determining compatibility - see comments
   96549 ** embedded in the code for details.
   96550 **
   96551 ** This routine returns TRUE if the optimization is guaranteed to be used.
   96552 ** Sometimes the xfer optimization will only work if the destination table
   96553 ** is empty - a factor that can only be determined at run-time.  In that
   96554 ** case, this routine generates code for the xfer optimization but also
   96555 ** does a test to see if the destination table is empty and jumps over the
   96556 ** xfer optimization code if the test fails.  In that case, this routine
   96557 ** returns FALSE so that the caller will know to go ahead and generate
   96558 ** an unoptimized transfer.  This routine also returns FALSE if there
   96559 ** is no chance that the xfer optimization can be applied.
   96560 **
   96561 ** This optimization is particularly useful at making VACUUM run faster.
   96562 */
   96563 static int xferOptimization(
   96564   Parse *pParse,        /* Parser context */
   96565   Table *pDest,         /* The table we are inserting into */
   96566   Select *pSelect,      /* A SELECT statement to use as the data source */
   96567   int onError,          /* How to handle constraint errors */
   96568   int iDbDest           /* The database of pDest */
   96569 ){
   96570   ExprList *pEList;                /* The result set of the SELECT */
   96571   Table *pSrc;                     /* The table in the FROM clause of SELECT */
   96572   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
   96573   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
   96574   int i;                           /* Loop counter */
   96575   int iDbSrc;                      /* The database of pSrc */
   96576   int iSrc, iDest;                 /* Cursors from source and destination */
   96577   int addr1, addr2;                /* Loop addresses */
   96578   int emptyDestTest = 0;           /* Address of test for empty pDest */
   96579   int emptySrcTest = 0;            /* Address of test for empty pSrc */
   96580   Vdbe *v;                         /* The VDBE we are building */
   96581   int regAutoinc;                  /* Memory register used by AUTOINC */
   96582   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
   96583   int regData, regRowid;           /* Registers holding data and rowid */
   96584 
   96585   if( pSelect==0 ){
   96586     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
   96587   }
   96588   if( pParse->pWith || pSelect->pWith ){
   96589     /* Do not attempt to process this query if there are an WITH clauses
   96590     ** attached to it. Proceeding may generate a false "no such table: xxx"
   96591     ** error if pSelect reads from a CTE named "xxx".  */
   96592     return 0;
   96593   }
   96594   if( sqlite3TriggerList(pParse, pDest) ){
   96595     return 0;   /* tab1 must not have triggers */
   96596   }
   96597 #ifndef SQLITE_OMIT_VIRTUALTABLE
   96598   if( pDest->tabFlags & TF_Virtual ){
   96599     return 0;   /* tab1 must not be a virtual table */
   96600   }
   96601 #endif
   96602   if( onError==OE_Default ){
   96603     if( pDest->iPKey>=0 ) onError = pDest->keyConf;
   96604     if( onError==OE_Default ) onError = OE_Abort;
   96605   }
   96606   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
   96607   if( pSelect->pSrc->nSrc!=1 ){
   96608     return 0;   /* FROM clause must have exactly one term */
   96609   }
   96610   if( pSelect->pSrc->a[0].pSelect ){
   96611     return 0;   /* FROM clause cannot contain a subquery */
   96612   }
   96613   if( pSelect->pWhere ){
   96614     return 0;   /* SELECT may not have a WHERE clause */
   96615   }
   96616   if( pSelect->pOrderBy ){
   96617     return 0;   /* SELECT may not have an ORDER BY clause */
   96618   }
   96619   /* Do not need to test for a HAVING clause.  If HAVING is present but
   96620   ** there is no ORDER BY, we will get an error. */
   96621   if( pSelect->pGroupBy ){
   96622     return 0;   /* SELECT may not have a GROUP BY clause */
   96623   }
   96624   if( pSelect->pLimit ){
   96625     return 0;   /* SELECT may not have a LIMIT clause */
   96626   }
   96627   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
   96628   if( pSelect->pPrior ){
   96629     return 0;   /* SELECT may not be a compound query */
   96630   }
   96631   if( pSelect->selFlags & SF_Distinct ){
   96632     return 0;   /* SELECT may not be DISTINCT */
   96633   }
   96634   pEList = pSelect->pEList;
   96635   assert( pEList!=0 );
   96636   if( pEList->nExpr!=1 ){
   96637     return 0;   /* The result set must have exactly one column */
   96638   }
   96639   assert( pEList->a[0].pExpr );
   96640   if( pEList->a[0].pExpr->op!=TK_ALL ){
   96641     return 0;   /* The result set must be the special operator "*" */
   96642   }
   96643 
   96644   /* At this point we have established that the statement is of the
   96645   ** correct syntactic form to participate in this optimization.  Now
   96646   ** we have to check the semantics.
   96647   */
   96648   pItem = pSelect->pSrc->a;
   96649   pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
   96650   if( pSrc==0 ){
   96651     return 0;   /* FROM clause does not contain a real table */
   96652   }
   96653   if( pSrc==pDest ){
   96654     return 0;   /* tab1 and tab2 may not be the same table */
   96655   }
   96656   if( HasRowid(pDest)!=HasRowid(pSrc) ){
   96657     return 0;   /* source and destination must both be WITHOUT ROWID or not */
   96658   }
   96659 #ifndef SQLITE_OMIT_VIRTUALTABLE
   96660   if( pSrc->tabFlags & TF_Virtual ){
   96661     return 0;   /* tab2 must not be a virtual table */
   96662   }
   96663 #endif
   96664   if( pSrc->pSelect ){
   96665     return 0;   /* tab2 may not be a view */
   96666   }
   96667   if( pDest->nCol!=pSrc->nCol ){
   96668     return 0;   /* Number of columns must be the same in tab1 and tab2 */
   96669   }
   96670   if( pDest->iPKey!=pSrc->iPKey ){
   96671     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
   96672   }
   96673   for(i=0; i<pDest->nCol; i++){
   96674     Column *pDestCol = &pDest->aCol[i];
   96675     Column *pSrcCol = &pSrc->aCol[i];
   96676     if( pDestCol->affinity!=pSrcCol->affinity ){
   96677       return 0;    /* Affinity must be the same on all columns */
   96678     }
   96679     if( !xferCompatibleCollation(pDestCol->zColl, pSrcCol->zColl) ){
   96680       return 0;    /* Collating sequence must be the same on all columns */
   96681     }
   96682     if( pDestCol->notNull && !pSrcCol->notNull ){
   96683       return 0;    /* tab2 must be NOT NULL if tab1 is */
   96684     }
   96685     /* Default values for second and subsequent columns need to match. */
   96686     if( i>0
   96687      && ((pDestCol->zDflt==0)!=(pSrcCol->zDflt==0)
   96688          || (pDestCol->zDflt && strcmp(pDestCol->zDflt, pSrcCol->zDflt)!=0))
   96689     ){
   96690       return 0;    /* Default values must be the same for all columns */
   96691     }
   96692   }
   96693   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
   96694     if( IsUniqueIndex(pDestIdx) ){
   96695       destHasUniqueIdx = 1;
   96696     }
   96697     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
   96698       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
   96699     }
   96700     if( pSrcIdx==0 ){
   96701       return 0;    /* pDestIdx has no corresponding index in pSrc */
   96702     }
   96703   }
   96704 #ifndef SQLITE_OMIT_CHECK
   96705   if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
   96706     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
   96707   }
   96708 #endif
   96709 #ifndef SQLITE_OMIT_FOREIGN_KEY
   96710   /* Disallow the transfer optimization if the destination table constains
   96711   ** any foreign key constraints.  This is more restrictive than necessary.
   96712   ** But the main beneficiary of the transfer optimization is the VACUUM
   96713   ** command, and the VACUUM command disables foreign key constraints.  So
   96714   ** the extra complication to make this rule less restrictive is probably
   96715   ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
   96716   */
   96717   if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
   96718     return 0;
   96719   }
   96720 #endif
   96721   if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
   96722     return 0;  /* xfer opt does not play well with PRAGMA count_changes */
   96723   }
   96724 
   96725   /* If we get this far, it means that the xfer optimization is at
   96726   ** least a possibility, though it might only work if the destination
   96727   ** table (tab1) is initially empty.
   96728   */
   96729 #ifdef SQLITE_TEST
   96730   sqlite3_xferopt_count++;
   96731 #endif
   96732   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
   96733   v = sqlite3GetVdbe(pParse);
   96734   sqlite3CodeVerifySchema(pParse, iDbSrc);
   96735   iSrc = pParse->nTab++;
   96736   iDest = pParse->nTab++;
   96737   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
   96738   regData = sqlite3GetTempReg(pParse);
   96739   regRowid = sqlite3GetTempReg(pParse);
   96740   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
   96741   assert( HasRowid(pDest) || destHasUniqueIdx );
   96742   if( (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
   96743    || destHasUniqueIdx                              /* (2) */
   96744    || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
   96745   ){
   96746     /* In some circumstances, we are able to run the xfer optimization
   96747     ** only if the destination table is initially empty.  This code makes
   96748     ** that determination.  Conditions under which the destination must
   96749     ** be empty:
   96750     **
   96751     ** (1) There is no INTEGER PRIMARY KEY but there are indices.
   96752     **     (If the destination is not initially empty, the rowid fields
   96753     **     of index entries might need to change.)
   96754     **
   96755     ** (2) The destination has a unique index.  (The xfer optimization
   96756     **     is unable to test uniqueness.)
   96757     **
   96758     ** (3) onError is something other than OE_Abort and OE_Rollback.
   96759     */
   96760     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
   96761     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
   96762     sqlite3VdbeJumpHere(v, addr1);
   96763   }
   96764   if( HasRowid(pSrc) ){
   96765     sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
   96766     emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
   96767     if( pDest->iPKey>=0 ){
   96768       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
   96769       addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
   96770       VdbeCoverage(v);
   96771       sqlite3RowidConstraint(pParse, onError, pDest);
   96772       sqlite3VdbeJumpHere(v, addr2);
   96773       autoIncStep(pParse, regAutoinc, regRowid);
   96774     }else if( pDest->pIndex==0 ){
   96775       addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
   96776     }else{
   96777       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
   96778       assert( (pDest->tabFlags & TF_Autoincrement)==0 );
   96779     }
   96780     sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
   96781     sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
   96782     sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
   96783     sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
   96784     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
   96785     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
   96786     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
   96787   }else{
   96788     sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
   96789     sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
   96790   }
   96791   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
   96792     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
   96793       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
   96794     }
   96795     assert( pSrcIdx );
   96796     sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
   96797     sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
   96798     VdbeComment((v, "%s", pSrcIdx->zName));
   96799     sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
   96800     sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
   96801     sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
   96802     VdbeComment((v, "%s", pDestIdx->zName));
   96803     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
   96804     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
   96805     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
   96806     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
   96807     sqlite3VdbeJumpHere(v, addr1);
   96808     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
   96809     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
   96810   }
   96811   if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
   96812   sqlite3ReleaseTempReg(pParse, regRowid);
   96813   sqlite3ReleaseTempReg(pParse, regData);
   96814   if( emptyDestTest ){
   96815     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
   96816     sqlite3VdbeJumpHere(v, emptyDestTest);
   96817     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
   96818     return 0;
   96819   }else{
   96820     return 1;
   96821   }
   96822 }
   96823 #endif /* SQLITE_OMIT_XFER_OPT */
   96824 
   96825 /************** End of insert.c **********************************************/
   96826 /************** Begin file legacy.c ******************************************/
   96827 /*
   96828 ** 2001 September 15
   96829 **
   96830 ** The author disclaims copyright to this source code.  In place of
   96831 ** a legal notice, here is a blessing:
   96832 **
   96833 **    May you do good and not evil.
   96834 **    May you find forgiveness for yourself and forgive others.
   96835 **    May you share freely, never taking more than you give.
   96836 **
   96837 *************************************************************************
   96838 ** Main file for the SQLite library.  The routines in this file
   96839 ** implement the programmer interface to the library.  Routines in
   96840 ** other files are for internal use by SQLite and should not be
   96841 ** accessed by users of the library.
   96842 */
   96843 
   96844 
   96845 /*
   96846 ** Execute SQL code.  Return one of the SQLITE_ success/failure
   96847 ** codes.  Also write an error message into memory obtained from
   96848 ** malloc() and make *pzErrMsg point to that message.
   96849 **
   96850 ** If the SQL is a query, then for each row in the query result
   96851 ** the xCallback() function is called.  pArg becomes the first
   96852 ** argument to xCallback().  If xCallback=NULL then no callback
   96853 ** is invoked, even for queries.
   96854 */
   96855 SQLITE_API int sqlite3_exec(
   96856   sqlite3 *db,                /* The database on which the SQL executes */
   96857   const char *zSql,           /* The SQL to be executed */
   96858   sqlite3_callback xCallback, /* Invoke this callback routine */
   96859   void *pArg,                 /* First argument to xCallback() */
   96860   char **pzErrMsg             /* Write error messages here */
   96861 ){
   96862   int rc = SQLITE_OK;         /* Return code */
   96863   const char *zLeftover;      /* Tail of unprocessed SQL */
   96864   sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
   96865   char **azCols = 0;          /* Names of result columns */
   96866   int callbackIsInit;         /* True if callback data is initialized */
   96867 
   96868   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
   96869   if( zSql==0 ) zSql = "";
   96870 
   96871   sqlite3_mutex_enter(db->mutex);
   96872   sqlite3Error(db, SQLITE_OK, 0);
   96873   while( rc==SQLITE_OK && zSql[0] ){
   96874     int nCol;
   96875     char **azVals = 0;
   96876 
   96877     pStmt = 0;
   96878     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
   96879     assert( rc==SQLITE_OK || pStmt==0 );
   96880     if( rc!=SQLITE_OK ){
   96881       continue;
   96882     }
   96883     if( !pStmt ){
   96884       /* this happens for a comment or white-space */
   96885       zSql = zLeftover;
   96886       continue;
   96887     }
   96888 
   96889     callbackIsInit = 0;
   96890     nCol = sqlite3_column_count(pStmt);
   96891 
   96892     while( 1 ){
   96893       int i;
   96894       rc = sqlite3_step(pStmt);
   96895 
   96896       /* Invoke the callback function if required */
   96897       if( xCallback && (SQLITE_ROW==rc ||
   96898           (SQLITE_DONE==rc && !callbackIsInit
   96899                            && db->flags&SQLITE_NullCallback)) ){
   96900         if( !callbackIsInit ){
   96901           azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
   96902           if( azCols==0 ){
   96903             goto exec_out;
   96904           }
   96905           for(i=0; i<nCol; i++){
   96906             azCols[i] = (char *)sqlite3_column_name(pStmt, i);
   96907             /* sqlite3VdbeSetColName() installs column names as UTF8
   96908             ** strings so there is no way for sqlite3_column_name() to fail. */
   96909             assert( azCols[i]!=0 );
   96910           }
   96911           callbackIsInit = 1;
   96912         }
   96913         if( rc==SQLITE_ROW ){
   96914           azVals = &azCols[nCol];
   96915           for(i=0; i<nCol; i++){
   96916             azVals[i] = (char *)sqlite3_column_text(pStmt, i);
   96917             if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
   96918               db->mallocFailed = 1;
   96919               goto exec_out;
   96920             }
   96921           }
   96922         }
   96923         if( xCallback(pArg, nCol, azVals, azCols) ){
   96924           /* EVIDENCE-OF: R-38229-40159 If the callback function to
   96925           ** sqlite3_exec() returns non-zero, then sqlite3_exec() will
   96926           ** return SQLITE_ABORT. */
   96927           rc = SQLITE_ABORT;
   96928           sqlite3VdbeFinalize((Vdbe *)pStmt);
   96929           pStmt = 0;
   96930           sqlite3Error(db, SQLITE_ABORT, 0);
   96931           goto exec_out;
   96932         }
   96933       }
   96934 
   96935       if( rc!=SQLITE_ROW ){
   96936         rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
   96937         pStmt = 0;
   96938         zSql = zLeftover;
   96939         while( sqlite3Isspace(zSql[0]) ) zSql++;
   96940         break;
   96941       }
   96942     }
   96943 
   96944     sqlite3DbFree(db, azCols);
   96945     azCols = 0;
   96946   }
   96947 
   96948 exec_out:
   96949   if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
   96950   sqlite3DbFree(db, azCols);
   96951 
   96952   rc = sqlite3ApiExit(db, rc);
   96953   if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
   96954     int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
   96955     *pzErrMsg = sqlite3Malloc(nErrMsg);
   96956     if( *pzErrMsg ){
   96957       memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
   96958     }else{
   96959       rc = SQLITE_NOMEM;
   96960       sqlite3Error(db, SQLITE_NOMEM, 0);
   96961     }
   96962   }else if( pzErrMsg ){
   96963     *pzErrMsg = 0;
   96964   }
   96965 
   96966   assert( (rc&db->errMask)==rc );
   96967   sqlite3_mutex_leave(db->mutex);
   96968   return rc;
   96969 }
   96970 
   96971 /************** End of legacy.c **********************************************/
   96972 /************** Begin file loadext.c *****************************************/
   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 file contains code used to dynamically load extensions into
   96985 ** the SQLite library.
   96986 */
   96987 
   96988 #ifndef SQLITE_CORE
   96989   #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
   96990 #endif
   96991 /************** Include sqlite3ext.h in the middle of loadext.c **************/
   96992 /************** Begin file sqlite3ext.h **************************************/
   96993 /*
   96994 ** 2006 June 7
   96995 **
   96996 ** The author disclaims copyright to this source code.  In place of
   96997 ** a legal notice, here is a blessing:
   96998 **
   96999 **    May you do good and not evil.
   97000 **    May you find forgiveness for yourself and forgive others.
   97001 **    May you share freely, never taking more than you give.
   97002 **
   97003 *************************************************************************
   97004 ** This header file defines the SQLite interface for use by
   97005 ** shared libraries that want to be imported as extensions into
   97006 ** an SQLite instance.  Shared libraries that intend to be loaded
   97007 ** as extensions by SQLite should #include this file instead of
   97008 ** sqlite3.h.
   97009 */
   97010 #ifndef _SQLITE3EXT_H_
   97011 #define _SQLITE3EXT_H_
   97012 
   97013 typedef struct sqlite3_api_routines sqlite3_api_routines;
   97014 
   97015 /*
   97016 ** The following structure holds pointers to all of the SQLite API
   97017 ** routines.
   97018 **
   97019 ** WARNING:  In order to maintain backwards compatibility, add new
   97020 ** interfaces to the end of this structure only.  If you insert new
   97021 ** interfaces in the middle of this structure, then older different
   97022 ** versions of SQLite will not be able to load each others' shared
   97023 ** libraries!
   97024 */
   97025 struct sqlite3_api_routines {
   97026   void * (*aggregate_context)(sqlite3_context*,int nBytes);
   97027   int  (*aggregate_count)(sqlite3_context*);
   97028   int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
   97029   int  (*bind_double)(sqlite3_stmt*,int,double);
   97030   int  (*bind_int)(sqlite3_stmt*,int,int);
   97031   int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
   97032   int  (*bind_null)(sqlite3_stmt*,int);
   97033   int  (*bind_parameter_count)(sqlite3_stmt*);
   97034   int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
   97035   const char * (*bind_parameter_name)(sqlite3_stmt*,int);
   97036   int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
   97037   int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
   97038   int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
   97039   int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
   97040   int  (*busy_timeout)(sqlite3*,int ms);
   97041   int  (*changes)(sqlite3*);
   97042   int  (*close)(sqlite3*);
   97043   int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
   97044                            int eTextRep,const char*));
   97045   int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
   97046                              int eTextRep,const void*));
   97047   const void * (*column_blob)(sqlite3_stmt*,int iCol);
   97048   int  (*column_bytes)(sqlite3_stmt*,int iCol);
   97049   int  (*column_bytes16)(sqlite3_stmt*,int iCol);
   97050   int  (*column_count)(sqlite3_stmt*pStmt);
   97051   const char * (*column_database_name)(sqlite3_stmt*,int);
   97052   const void * (*column_database_name16)(sqlite3_stmt*,int);
   97053   const char * (*column_decltype)(sqlite3_stmt*,int i);
   97054   const void * (*column_decltype16)(sqlite3_stmt*,int);
   97055   double  (*column_double)(sqlite3_stmt*,int iCol);
   97056   int  (*column_int)(sqlite3_stmt*,int iCol);
   97057   sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
   97058   const char * (*column_name)(sqlite3_stmt*,int);
   97059   const void * (*column_name16)(sqlite3_stmt*,int);
   97060   const char * (*column_origin_name)(sqlite3_stmt*,int);
   97061   const void * (*column_origin_name16)(sqlite3_stmt*,int);
   97062   const char * (*column_table_name)(sqlite3_stmt*,int);
   97063   const void * (*column_table_name16)(sqlite3_stmt*,int);
   97064   const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
   97065   const void * (*column_text16)(sqlite3_stmt*,int iCol);
   97066   int  (*column_type)(sqlite3_stmt*,int iCol);
   97067   sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
   97068   void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
   97069   int  (*complete)(const char*sql);
   97070   int  (*complete16)(const void*sql);
   97071   int  (*create_collation)(sqlite3*,const char*,int,void*,
   97072                            int(*)(void*,int,const void*,int,const void*));
   97073   int  (*create_collation16)(sqlite3*,const void*,int,void*,
   97074                              int(*)(void*,int,const void*,int,const void*));
   97075   int  (*create_function)(sqlite3*,const char*,int,int,void*,
   97076                           void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
   97077                           void (*xStep)(sqlite3_context*,int,sqlite3_value**),
   97078                           void (*xFinal)(sqlite3_context*));
   97079   int  (*create_function16)(sqlite3*,const void*,int,int,void*,
   97080                             void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
   97081                             void (*xStep)(sqlite3_context*,int,sqlite3_value**),
   97082                             void (*xFinal)(sqlite3_context*));
   97083   int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
   97084   int  (*data_count)(sqlite3_stmt*pStmt);
   97085   sqlite3 * (*db_handle)(sqlite3_stmt*);
   97086   int (*declare_vtab)(sqlite3*,const char*);
   97087   int  (*enable_shared_cache)(int);
   97088   int  (*errcode)(sqlite3*db);
   97089   const char * (*errmsg)(sqlite3*);
   97090   const void * (*errmsg16)(sqlite3*);
   97091   int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
   97092   int  (*expired)(sqlite3_stmt*);
   97093   int  (*finalize)(sqlite3_stmt*pStmt);
   97094   void  (*free)(void*);
   97095   void  (*free_table)(char**result);
   97096   int  (*get_autocommit)(sqlite3*);
   97097   void * (*get_auxdata)(sqlite3_context*,int);
   97098   int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
   97099   int  (*global_recover)(void);
   97100   void  (*interruptx)(sqlite3*);
   97101   sqlite_int64  (*last_insert_rowid)(sqlite3*);
   97102   const char * (*libversion)(void);
   97103   int  (*libversion_number)(void);
   97104   void *(*malloc)(int);
   97105   char * (*mprintf)(const char*,...);
   97106   int  (*open)(const char*,sqlite3**);
   97107   int  (*open16)(const void*,sqlite3**);
   97108   int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
   97109   int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
   97110   void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
   97111   void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
   97112   void *(*realloc)(void*,int);
   97113   int  (*reset)(sqlite3_stmt*pStmt);
   97114   void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
   97115   void  (*result_double)(sqlite3_context*,double);
   97116   void  (*result_error)(sqlite3_context*,const char*,int);
   97117   void  (*result_error16)(sqlite3_context*,const void*,int);
   97118   void  (*result_int)(sqlite3_context*,int);
   97119   void  (*result_int64)(sqlite3_context*,sqlite_int64);
   97120   void  (*result_null)(sqlite3_context*);
   97121   void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
   97122   void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
   97123   void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
   97124   void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
   97125   void  (*result_value)(sqlite3_context*,sqlite3_value*);
   97126   void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
   97127   int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
   97128                          const char*,const char*),void*);
   97129   void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
   97130   char * (*snprintf)(int,char*,const char*,...);
   97131   int  (*step)(sqlite3_stmt*);
   97132   int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
   97133                                 char const**,char const**,int*,int*,int*);
   97134   void  (*thread_cleanup)(void);
   97135   int  (*total_changes)(sqlite3*);
   97136   void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
   97137   int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
   97138   void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
   97139                                          sqlite_int64),void*);
   97140   void * (*user_data)(sqlite3_context*);
   97141   const void * (*value_blob)(sqlite3_value*);
   97142   int  (*value_bytes)(sqlite3_value*);
   97143   int  (*value_bytes16)(sqlite3_value*);
   97144   double  (*value_double)(sqlite3_value*);
   97145   int  (*value_int)(sqlite3_value*);
   97146   sqlite_int64  (*value_int64)(sqlite3_value*);
   97147   int  (*value_numeric_type)(sqlite3_value*);
   97148   const unsigned char * (*value_text)(sqlite3_value*);
   97149   const void * (*value_text16)(sqlite3_value*);
   97150   const void * (*value_text16be)(sqlite3_value*);
   97151   const void * (*value_text16le)(sqlite3_value*);
   97152   int  (*value_type)(sqlite3_value*);
   97153   char *(*vmprintf)(const char*,va_list);
   97154   /* Added ??? */
   97155   int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
   97156   /* Added by 3.3.13 */
   97157   int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
   97158   int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
   97159   int (*clear_bindings)(sqlite3_stmt*);
   97160   /* Added by 3.4.1 */
   97161   int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
   97162                           void (*xDestroy)(void *));
   97163   /* Added by 3.5.0 */
   97164   int (*bind_zeroblob)(sqlite3_stmt*,int,int);
   97165   int (*blob_bytes)(sqlite3_blob*);
   97166   int (*blob_close)(sqlite3_blob*);
   97167   int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
   97168                    int,sqlite3_blob**);
   97169   int (*blob_read)(sqlite3_blob*,void*,int,int);
   97170   int (*blob_write)(sqlite3_blob*,const void*,int,int);
   97171   int (*create_collation_v2)(sqlite3*,const char*,int,void*,
   97172                              int(*)(void*,int,const void*,int,const void*),
   97173                              void(*)(void*));
   97174   int (*file_control)(sqlite3*,const char*,int,void*);
   97175   sqlite3_int64 (*memory_highwater)(int);
   97176   sqlite3_int64 (*memory_used)(void);
   97177   sqlite3_mutex *(*mutex_alloc)(int);
   97178   void (*mutex_enter)(sqlite3_mutex*);
   97179   void (*mutex_free)(sqlite3_mutex*);
   97180   void (*mutex_leave)(sqlite3_mutex*);
   97181   int (*mutex_try)(sqlite3_mutex*);
   97182   int (*open_v2)(const char*,sqlite3**,int,const char*);
   97183   int (*release_memory)(int);
   97184   void (*result_error_nomem)(sqlite3_context*);
   97185   void (*result_error_toobig)(sqlite3_context*);
   97186   int (*sleep)(int);
   97187   void (*soft_heap_limit)(int);
   97188   sqlite3_vfs *(*vfs_find)(const char*);
   97189   int (*vfs_register)(sqlite3_vfs*,int);
   97190   int (*vfs_unregister)(sqlite3_vfs*);
   97191   int (*xthreadsafe)(void);
   97192   void (*result_zeroblob)(sqlite3_context*,int);
   97193   void (*result_error_code)(sqlite3_context*,int);
   97194   int (*test_control)(int, ...);
   97195   void (*randomness)(int,void*);
   97196   sqlite3 *(*context_db_handle)(sqlite3_context*);
   97197   int (*extended_result_codes)(sqlite3*,int);
   97198   int (*limit)(sqlite3*,int,int);
   97199   sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
   97200   const char *(*sql)(sqlite3_stmt*);
   97201   int (*status)(int,int*,int*,int);
   97202   int (*backup_finish)(sqlite3_backup*);
   97203   sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
   97204   int (*backup_pagecount)(sqlite3_backup*);
   97205   int (*backup_remaining)(sqlite3_backup*);
   97206   int (*backup_step)(sqlite3_backup*,int);
   97207   const char *(*compileoption_get)(int);
   97208   int (*compileoption_used)(const char*);
   97209   int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
   97210                             void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
   97211                             void (*xStep)(sqlite3_context*,int,sqlite3_value**),
   97212                             void (*xFinal)(sqlite3_context*),
   97213                             void(*xDestroy)(void*));
   97214   int (*db_config)(sqlite3*,int,...);
   97215   sqlite3_mutex *(*db_mutex)(sqlite3*);
   97216   int (*db_status)(sqlite3*,int,int*,int*,int);
   97217   int (*extended_errcode)(sqlite3*);
   97218   void (*log)(int,const char*,...);
   97219   sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
   97220   const char *(*sourceid)(void);
   97221   int (*stmt_status)(sqlite3_stmt*,int,int);
   97222   int (*strnicmp)(const char*,const char*,int);
   97223   int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
   97224   int (*wal_autocheckpoint)(sqlite3*,int);
   97225   int (*wal_checkpoint)(sqlite3*,const char*);
   97226   void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
   97227   int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
   97228   int (*vtab_config)(sqlite3*,int op,...);
   97229   int (*vtab_on_conflict)(sqlite3*);
   97230   /* Version 3.7.16 and later */
   97231   int (*close_v2)(sqlite3*);
   97232   const char *(*db_filename)(sqlite3*,const char*);
   97233   int (*db_readonly)(sqlite3*,const char*);
   97234   int (*db_release_memory)(sqlite3*);
   97235   const char *(*errstr)(int);
   97236   int (*stmt_busy)(sqlite3_stmt*);
   97237   int (*stmt_readonly)(sqlite3_stmt*);
   97238   int (*stricmp)(const char*,const char*);
   97239   int (*uri_boolean)(const char*,const char*,int);
   97240   sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
   97241   const char *(*uri_parameter)(const char*,const char*);
   97242   char *(*vsnprintf)(int,char*,const char*,va_list);
   97243   int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
   97244 };
   97245 
   97246 /*
   97247 ** The following macros redefine the API routines so that they are
   97248 ** redirected throught the global sqlite3_api structure.
   97249 **
   97250 ** This header file is also used by the loadext.c source file
   97251 ** (part of the main SQLite library - not an extension) so that
   97252 ** it can get access to the sqlite3_api_routines structure
   97253 ** definition.  But the main library does not want to redefine
   97254 ** the API.  So the redefinition macros are only valid if the
   97255 ** SQLITE_CORE macros is undefined.
   97256 */
   97257 #ifndef SQLITE_CORE
   97258 #define sqlite3_aggregate_context      sqlite3_api->aggregate_context
   97259 #ifndef SQLITE_OMIT_DEPRECATED
   97260 #define sqlite3_aggregate_count        sqlite3_api->aggregate_count
   97261 #endif
   97262 #define sqlite3_bind_blob              sqlite3_api->bind_blob
   97263 #define sqlite3_bind_double            sqlite3_api->bind_double
   97264 #define sqlite3_bind_int               sqlite3_api->bind_int
   97265 #define sqlite3_bind_int64             sqlite3_api->bind_int64
   97266 #define sqlite3_bind_null              sqlite3_api->bind_null
   97267 #define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
   97268 #define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
   97269 #define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
   97270 #define sqlite3_bind_text              sqlite3_api->bind_text
   97271 #define sqlite3_bind_text16            sqlite3_api->bind_text16
   97272 #define sqlite3_bind_value             sqlite3_api->bind_value
   97273 #define sqlite3_busy_handler           sqlite3_api->busy_handler
   97274 #define sqlite3_busy_timeout           sqlite3_api->busy_timeout
   97275 #define sqlite3_changes                sqlite3_api->changes
   97276 #define sqlite3_close                  sqlite3_api->close
   97277 #define sqlite3_collation_needed       sqlite3_api->collation_needed
   97278 #define sqlite3_collation_needed16     sqlite3_api->collation_needed16
   97279 #define sqlite3_column_blob            sqlite3_api->column_blob
   97280 #define sqlite3_column_bytes           sqlite3_api->column_bytes
   97281 #define sqlite3_column_bytes16         sqlite3_api->column_bytes16
   97282 #define sqlite3_column_count           sqlite3_api->column_count
   97283 #define sqlite3_column_database_name   sqlite3_api->column_database_name
   97284 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
   97285 #define sqlite3_column_decltype        sqlite3_api->column_decltype
   97286 #define sqlite3_column_decltype16      sqlite3_api->column_decltype16
   97287 #define sqlite3_column_double          sqlite3_api->column_double
   97288 #define sqlite3_column_int             sqlite3_api->column_int
   97289 #define sqlite3_column_int64           sqlite3_api->column_int64
   97290 #define sqlite3_column_name            sqlite3_api->column_name
   97291 #define sqlite3_column_name16          sqlite3_api->column_name16
   97292 #define sqlite3_column_origin_name     sqlite3_api->column_origin_name
   97293 #define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
   97294 #define sqlite3_column_table_name      sqlite3_api->column_table_name
   97295 #define sqlite3_column_table_name16    sqlite3_api->column_table_name16
   97296 #define sqlite3_column_text            sqlite3_api->column_text
   97297 #define sqlite3_column_text16          sqlite3_api->column_text16
   97298 #define sqlite3_column_type            sqlite3_api->column_type
   97299 #define sqlite3_column_value           sqlite3_api->column_value
   97300 #define sqlite3_commit_hook            sqlite3_api->commit_hook
   97301 #define sqlite3_complete               sqlite3_api->complete
   97302 #define sqlite3_complete16             sqlite3_api->complete16
   97303 #define sqlite3_create_collation       sqlite3_api->create_collation
   97304 #define sqlite3_create_collation16     sqlite3_api->create_collation16
   97305 #define sqlite3_create_function        sqlite3_api->create_function
   97306 #define sqlite3_create_function16      sqlite3_api->create_function16
   97307 #define sqlite3_create_module          sqlite3_api->create_module
   97308 #define sqlite3_create_module_v2       sqlite3_api->create_module_v2
   97309 #define sqlite3_data_count             sqlite3_api->data_count
   97310 #define sqlite3_db_handle              sqlite3_api->db_handle
   97311 #define sqlite3_declare_vtab           sqlite3_api->declare_vtab
   97312 #define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
   97313 #define sqlite3_errcode                sqlite3_api->errcode
   97314 #define sqlite3_errmsg                 sqlite3_api->errmsg
   97315 #define sqlite3_errmsg16               sqlite3_api->errmsg16
   97316 #define sqlite3_exec                   sqlite3_api->exec
   97317 #ifndef SQLITE_OMIT_DEPRECATED
   97318 #define sqlite3_expired                sqlite3_api->expired
   97319 #endif
   97320 #define sqlite3_finalize               sqlite3_api->finalize
   97321 #define sqlite3_free                   sqlite3_api->free
   97322 #define sqlite3_free_table             sqlite3_api->free_table
   97323 #define sqlite3_get_autocommit         sqlite3_api->get_autocommit
   97324 #define sqlite3_get_auxdata            sqlite3_api->get_auxdata
   97325 #define sqlite3_get_table              sqlite3_api->get_table
   97326 #ifndef SQLITE_OMIT_DEPRECATED
   97327 #define sqlite3_global_recover         sqlite3_api->global_recover
   97328 #endif
   97329 #define sqlite3_interrupt              sqlite3_api->interruptx
   97330 #define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
   97331 #define sqlite3_libversion             sqlite3_api->libversion
   97332 #define sqlite3_libversion_number      sqlite3_api->libversion_number
   97333 #define sqlite3_malloc                 sqlite3_api->malloc
   97334 #define sqlite3_mprintf                sqlite3_api->mprintf
   97335 #define sqlite3_open                   sqlite3_api->open
   97336 #define sqlite3_open16                 sqlite3_api->open16
   97337 #define sqlite3_prepare                sqlite3_api->prepare
   97338 #define sqlite3_prepare16              sqlite3_api->prepare16
   97339 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
   97340 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
   97341 #define sqlite3_profile                sqlite3_api->profile
   97342 #define sqlite3_progress_handler       sqlite3_api->progress_handler
   97343 #define sqlite3_realloc                sqlite3_api->realloc
   97344 #define sqlite3_reset                  sqlite3_api->reset
   97345 #define sqlite3_result_blob            sqlite3_api->result_blob
   97346 #define sqlite3_result_double          sqlite3_api->result_double
   97347 #define sqlite3_result_error           sqlite3_api->result_error
   97348 #define sqlite3_result_error16         sqlite3_api->result_error16
   97349 #define sqlite3_result_int             sqlite3_api->result_int
   97350 #define sqlite3_result_int64           sqlite3_api->result_int64
   97351 #define sqlite3_result_null            sqlite3_api->result_null
   97352 #define sqlite3_result_text            sqlite3_api->result_text
   97353 #define sqlite3_result_text16          sqlite3_api->result_text16
   97354 #define sqlite3_result_text16be        sqlite3_api->result_text16be
   97355 #define sqlite3_result_text16le        sqlite3_api->result_text16le
   97356 #define sqlite3_result_value           sqlite3_api->result_value
   97357 #define sqlite3_rollback_hook          sqlite3_api->rollback_hook
   97358 #define sqlite3_set_authorizer         sqlite3_api->set_authorizer
   97359 #define sqlite3_set_auxdata            sqlite3_api->set_auxdata
   97360 #define sqlite3_snprintf               sqlite3_api->snprintf
   97361 #define sqlite3_step                   sqlite3_api->step
   97362 #define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
   97363 #define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
   97364 #define sqlite3_total_changes          sqlite3_api->total_changes
   97365 #define sqlite3_trace                  sqlite3_api->trace
   97366 #ifndef SQLITE_OMIT_DEPRECATED
   97367 #define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
   97368 #endif
   97369 #define sqlite3_update_hook            sqlite3_api->update_hook
   97370 #define sqlite3_user_data              sqlite3_api->user_data
   97371 #define sqlite3_value_blob             sqlite3_api->value_blob
   97372 #define sqlite3_value_bytes            sqlite3_api->value_bytes
   97373 #define sqlite3_value_bytes16          sqlite3_api->value_bytes16
   97374 #define sqlite3_value_double           sqlite3_api->value_double
   97375 #define sqlite3_value_int              sqlite3_api->value_int
   97376 #define sqlite3_value_int64            sqlite3_api->value_int64
   97377 #define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
   97378 #define sqlite3_value_text             sqlite3_api->value_text
   97379 #define sqlite3_value_text16           sqlite3_api->value_text16
   97380 #define sqlite3_value_text16be         sqlite3_api->value_text16be
   97381 #define sqlite3_value_text16le         sqlite3_api->value_text16le
   97382 #define sqlite3_value_type             sqlite3_api->value_type
   97383 #define sqlite3_vmprintf               sqlite3_api->vmprintf
   97384 #define sqlite3_overload_function      sqlite3_api->overload_function
   97385 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
   97386 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
   97387 #define sqlite3_clear_bindings         sqlite3_api->clear_bindings
   97388 #define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
   97389 #define sqlite3_blob_bytes             sqlite3_api->blob_bytes
   97390 #define sqlite3_blob_close             sqlite3_api->blob_close
   97391 #define sqlite3_blob_open              sqlite3_api->blob_open
   97392 #define sqlite3_blob_read              sqlite3_api->blob_read
   97393 #define sqlite3_blob_write             sqlite3_api->blob_write
   97394 #define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
   97395 #define sqlite3_file_control           sqlite3_api->file_control
   97396 #define sqlite3_memory_highwater       sqlite3_api->memory_highwater
   97397 #define sqlite3_memory_used            sqlite3_api->memory_used
   97398 #define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
   97399 #define sqlite3_mutex_enter            sqlite3_api->mutex_enter
   97400 #define sqlite3_mutex_free             sqlite3_api->mutex_free
   97401 #define sqlite3_mutex_leave            sqlite3_api->mutex_leave
   97402 #define sqlite3_mutex_try              sqlite3_api->mutex_try
   97403 #define sqlite3_open_v2                sqlite3_api->open_v2
   97404 #define sqlite3_release_memory         sqlite3_api->release_memory
   97405 #define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
   97406 #define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
   97407 #define sqlite3_sleep                  sqlite3_api->sleep
   97408 #define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
   97409 #define sqlite3_vfs_find               sqlite3_api->vfs_find
   97410 #define sqlite3_vfs_register           sqlite3_api->vfs_register
   97411 #define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
   97412 #define sqlite3_threadsafe             sqlite3_api->xthreadsafe
   97413 #define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
   97414 #define sqlite3_result_error_code      sqlite3_api->result_error_code
   97415 #define sqlite3_test_control           sqlite3_api->test_control
   97416 #define sqlite3_randomness             sqlite3_api->randomness
   97417 #define sqlite3_context_db_handle      sqlite3_api->context_db_handle
   97418 #define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
   97419 #define sqlite3_limit                  sqlite3_api->limit
   97420 #define sqlite3_next_stmt              sqlite3_api->next_stmt
   97421 #define sqlite3_sql                    sqlite3_api->sql
   97422 #define sqlite3_status                 sqlite3_api->status
   97423 #define sqlite3_backup_finish          sqlite3_api->backup_finish
   97424 #define sqlite3_backup_init            sqlite3_api->backup_init
   97425 #define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount
   97426 #define sqlite3_backup_remaining       sqlite3_api->backup_remaining
   97427 #define sqlite3_backup_step            sqlite3_api->backup_step
   97428 #define sqlite3_compileoption_get      sqlite3_api->compileoption_get
   97429 #define sqlite3_compileoption_used     sqlite3_api->compileoption_used
   97430 #define sqlite3_create_function_v2     sqlite3_api->create_function_v2
   97431 #define sqlite3_db_config              sqlite3_api->db_config
   97432 #define sqlite3_db_mutex               sqlite3_api->db_mutex
   97433 #define sqlite3_db_status              sqlite3_api->db_status
   97434 #define sqlite3_extended_errcode       sqlite3_api->extended_errcode
   97435 #define sqlite3_log                    sqlite3_api->log
   97436 #define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64
   97437 #define sqlite3_sourceid               sqlite3_api->sourceid
   97438 #define sqlite3_stmt_status            sqlite3_api->stmt_status
   97439 #define sqlite3_strnicmp               sqlite3_api->strnicmp
   97440 #define sqlite3_unlock_notify          sqlite3_api->unlock_notify
   97441 #define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint
   97442 #define sqlite3_wal_checkpoint         sqlite3_api->wal_checkpoint
   97443 #define sqlite3_wal_hook               sqlite3_api->wal_hook
   97444 #define sqlite3_blob_reopen            sqlite3_api->blob_reopen
   97445 #define sqlite3_vtab_config            sqlite3_api->vtab_config
   97446 #define sqlite3_vtab_on_conflict       sqlite3_api->vtab_on_conflict
   97447 /* Version 3.7.16 and later */
   97448 #define sqlite3_close_v2               sqlite3_api->close_v2
   97449 #define sqlite3_db_filename            sqlite3_api->db_filename
   97450 #define sqlite3_db_readonly            sqlite3_api->db_readonly
   97451 #define sqlite3_db_release_memory      sqlite3_api->db_release_memory
   97452 #define sqlite3_errstr                 sqlite3_api->errstr
   97453 #define sqlite3_stmt_busy              sqlite3_api->stmt_busy
   97454 #define sqlite3_stmt_readonly          sqlite3_api->stmt_readonly
   97455 #define sqlite3_stricmp                sqlite3_api->stricmp
   97456 #define sqlite3_uri_boolean            sqlite3_api->uri_boolean
   97457 #define sqlite3_uri_int64              sqlite3_api->uri_int64
   97458 #define sqlite3_uri_parameter          sqlite3_api->uri_parameter
   97459 #define sqlite3_uri_vsnprintf          sqlite3_api->vsnprintf
   97460 #define sqlite3_wal_checkpoint_v2      sqlite3_api->wal_checkpoint_v2
   97461 #endif /* SQLITE_CORE */
   97462 
   97463 #ifndef SQLITE_CORE
   97464   /* This case when the file really is being compiled as a loadable
   97465   ** extension */
   97466 # define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api=0;
   97467 # define SQLITE_EXTENSION_INIT2(v)  sqlite3_api=v;
   97468 # define SQLITE_EXTENSION_INIT3     \
   97469     extern const sqlite3_api_routines *sqlite3_api;
   97470 #else
   97471   /* This case when the file is being statically linked into the
   97472   ** application */
   97473 # define SQLITE_EXTENSION_INIT1     /*no-op*/
   97474 # define SQLITE_EXTENSION_INIT2(v)  (void)v; /* unused parameter */
   97475 # define SQLITE_EXTENSION_INIT3     /*no-op*/
   97476 #endif
   97477 
   97478 #endif /* _SQLITE3EXT_H_ */
   97479 
   97480 /************** End of sqlite3ext.h ******************************************/
   97481 /************** Continuing where we left off in loadext.c ********************/
   97482 /* #include <string.h> */
   97483 
   97484 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   97485 
   97486 /*
   97487 ** Some API routines are omitted when various features are
   97488 ** excluded from a build of SQLite.  Substitute a NULL pointer
   97489 ** for any missing APIs.
   97490 */
   97491 #ifndef SQLITE_ENABLE_COLUMN_METADATA
   97492 # define sqlite3_column_database_name   0
   97493 # define sqlite3_column_database_name16 0
   97494 # define sqlite3_column_table_name      0
   97495 # define sqlite3_column_table_name16    0
   97496 # define sqlite3_column_origin_name     0
   97497 # define sqlite3_column_origin_name16   0
   97498 # define sqlite3_table_column_metadata  0
   97499 #endif
   97500 
   97501 #ifdef SQLITE_OMIT_AUTHORIZATION
   97502 # define sqlite3_set_authorizer         0
   97503 #endif
   97504 
   97505 #ifdef SQLITE_OMIT_UTF16
   97506 # define sqlite3_bind_text16            0
   97507 # define sqlite3_collation_needed16     0
   97508 # define sqlite3_column_decltype16      0
   97509 # define sqlite3_column_name16          0
   97510 # define sqlite3_column_text16          0
   97511 # define sqlite3_complete16             0
   97512 # define sqlite3_create_collation16     0
   97513 # define sqlite3_create_function16      0
   97514 # define sqlite3_errmsg16               0
   97515 # define sqlite3_open16                 0
   97516 # define sqlite3_prepare16              0
   97517 # define sqlite3_prepare16_v2           0
   97518 # define sqlite3_result_error16         0
   97519 # define sqlite3_result_text16          0
   97520 # define sqlite3_result_text16be        0
   97521 # define sqlite3_result_text16le        0
   97522 # define sqlite3_value_text16           0
   97523 # define sqlite3_value_text16be         0
   97524 # define sqlite3_value_text16le         0
   97525 # define sqlite3_column_database_name16 0
   97526 # define sqlite3_column_table_name16    0
   97527 # define sqlite3_column_origin_name16   0
   97528 #endif
   97529 
   97530 #ifdef SQLITE_OMIT_COMPLETE
   97531 # define sqlite3_complete 0
   97532 # define sqlite3_complete16 0
   97533 #endif
   97534 
   97535 #ifdef SQLITE_OMIT_DECLTYPE
   97536 # define sqlite3_column_decltype16      0
   97537 # define sqlite3_column_decltype        0
   97538 #endif
   97539 
   97540 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
   97541 # define sqlite3_progress_handler 0
   97542 #endif
   97543 
   97544 #ifdef SQLITE_OMIT_VIRTUALTABLE
   97545 # define sqlite3_create_module 0
   97546 # define sqlite3_create_module_v2 0
   97547 # define sqlite3_declare_vtab 0
   97548 # define sqlite3_vtab_config 0
   97549 # define sqlite3_vtab_on_conflict 0
   97550 #endif
   97551 
   97552 #ifdef SQLITE_OMIT_SHARED_CACHE
   97553 # define sqlite3_enable_shared_cache 0
   97554 #endif
   97555 
   97556 #ifdef SQLITE_OMIT_TRACE
   97557 # define sqlite3_profile       0
   97558 # define sqlite3_trace         0
   97559 #endif
   97560 
   97561 #ifdef SQLITE_OMIT_GET_TABLE
   97562 # define sqlite3_free_table    0
   97563 # define sqlite3_get_table     0
   97564 #endif
   97565 
   97566 #ifdef SQLITE_OMIT_INCRBLOB
   97567 #define sqlite3_bind_zeroblob  0
   97568 #define sqlite3_blob_bytes     0
   97569 #define sqlite3_blob_close     0
   97570 #define sqlite3_blob_open      0
   97571 #define sqlite3_blob_read      0
   97572 #define sqlite3_blob_write     0
   97573 #define sqlite3_blob_reopen    0
   97574 #endif
   97575 
   97576 /*
   97577 ** The following structure contains pointers to all SQLite API routines.
   97578 ** A pointer to this structure is passed into extensions when they are
   97579 ** loaded so that the extension can make calls back into the SQLite
   97580 ** library.
   97581 **
   97582 ** When adding new APIs, add them to the bottom of this structure
   97583 ** in order to preserve backwards compatibility.
   97584 **
   97585 ** Extensions that use newer APIs should first call the
   97586 ** sqlite3_libversion_number() to make sure that the API they
   97587 ** intend to use is supported by the library.  Extensions should
   97588 ** also check to make sure that the pointer to the function is
   97589 ** not NULL before calling it.
   97590 */
   97591 static const sqlite3_api_routines sqlite3Apis = {
   97592   sqlite3_aggregate_context,
   97593 #ifndef SQLITE_OMIT_DEPRECATED
   97594   sqlite3_aggregate_count,
   97595 #else
   97596   0,
   97597 #endif
   97598   sqlite3_bind_blob,
   97599   sqlite3_bind_double,
   97600   sqlite3_bind_int,
   97601   sqlite3_bind_int64,
   97602   sqlite3_bind_null,
   97603   sqlite3_bind_parameter_count,
   97604   sqlite3_bind_parameter_index,
   97605   sqlite3_bind_parameter_name,
   97606   sqlite3_bind_text,
   97607   sqlite3_bind_text16,
   97608   sqlite3_bind_value,
   97609   sqlite3_busy_handler,
   97610   sqlite3_busy_timeout,
   97611   sqlite3_changes,
   97612   sqlite3_close,
   97613   sqlite3_collation_needed,
   97614   sqlite3_collation_needed16,
   97615   sqlite3_column_blob,
   97616   sqlite3_column_bytes,
   97617   sqlite3_column_bytes16,
   97618   sqlite3_column_count,
   97619   sqlite3_column_database_name,
   97620   sqlite3_column_database_name16,
   97621   sqlite3_column_decltype,
   97622   sqlite3_column_decltype16,
   97623   sqlite3_column_double,
   97624   sqlite3_column_int,
   97625   sqlite3_column_int64,
   97626   sqlite3_column_name,
   97627   sqlite3_column_name16,
   97628   sqlite3_column_origin_name,
   97629   sqlite3_column_origin_name16,
   97630   sqlite3_column_table_name,
   97631   sqlite3_column_table_name16,
   97632   sqlite3_column_text,
   97633   sqlite3_column_text16,
   97634   sqlite3_column_type,
   97635   sqlite3_column_value,
   97636   sqlite3_commit_hook,
   97637   sqlite3_complete,
   97638   sqlite3_complete16,
   97639   sqlite3_create_collation,
   97640   sqlite3_create_collation16,
   97641   sqlite3_create_function,
   97642   sqlite3_create_function16,
   97643   sqlite3_create_module,
   97644   sqlite3_data_count,
   97645   sqlite3_db_handle,
   97646   sqlite3_declare_vtab,
   97647   sqlite3_enable_shared_cache,
   97648   sqlite3_errcode,
   97649   sqlite3_errmsg,
   97650   sqlite3_errmsg16,
   97651   sqlite3_exec,
   97652 #ifndef SQLITE_OMIT_DEPRECATED
   97653   sqlite3_expired,
   97654 #else
   97655   0,
   97656 #endif
   97657   sqlite3_finalize,
   97658   sqlite3_free,
   97659   sqlite3_free_table,
   97660   sqlite3_get_autocommit,
   97661   sqlite3_get_auxdata,
   97662   sqlite3_get_table,
   97663   0,     /* Was sqlite3_global_recover(), but that function is deprecated */
   97664   sqlite3_interrupt,
   97665   sqlite3_last_insert_rowid,
   97666   sqlite3_libversion,
   97667   sqlite3_libversion_number,
   97668   sqlite3_malloc,
   97669   sqlite3_mprintf,
   97670   sqlite3_open,
   97671   sqlite3_open16,
   97672   sqlite3_prepare,
   97673   sqlite3_prepare16,
   97674   sqlite3_profile,
   97675   sqlite3_progress_handler,
   97676   sqlite3_realloc,
   97677   sqlite3_reset,
   97678   sqlite3_result_blob,
   97679   sqlite3_result_double,
   97680   sqlite3_result_error,
   97681   sqlite3_result_error16,
   97682   sqlite3_result_int,
   97683   sqlite3_result_int64,
   97684   sqlite3_result_null,
   97685   sqlite3_result_text,
   97686   sqlite3_result_text16,
   97687   sqlite3_result_text16be,
   97688   sqlite3_result_text16le,
   97689   sqlite3_result_value,
   97690   sqlite3_rollback_hook,
   97691   sqlite3_set_authorizer,
   97692   sqlite3_set_auxdata,
   97693   sqlite3_snprintf,
   97694   sqlite3_step,
   97695   sqlite3_table_column_metadata,
   97696 #ifndef SQLITE_OMIT_DEPRECATED
   97697   sqlite3_thread_cleanup,
   97698 #else
   97699   0,
   97700 #endif
   97701   sqlite3_total_changes,
   97702   sqlite3_trace,
   97703 #ifndef SQLITE_OMIT_DEPRECATED
   97704   sqlite3_transfer_bindings,
   97705 #else
   97706   0,
   97707 #endif
   97708   sqlite3_update_hook,
   97709   sqlite3_user_data,
   97710   sqlite3_value_blob,
   97711   sqlite3_value_bytes,
   97712   sqlite3_value_bytes16,
   97713   sqlite3_value_double,
   97714   sqlite3_value_int,
   97715   sqlite3_value_int64,
   97716   sqlite3_value_numeric_type,
   97717   sqlite3_value_text,
   97718   sqlite3_value_text16,
   97719   sqlite3_value_text16be,
   97720   sqlite3_value_text16le,
   97721   sqlite3_value_type,
   97722   sqlite3_vmprintf,
   97723   /*
   97724   ** The original API set ends here.  All extensions can call any
   97725   ** of the APIs above provided that the pointer is not NULL.  But
   97726   ** before calling APIs that follow, extension should check the
   97727   ** sqlite3_libversion_number() to make sure they are dealing with
   97728   ** a library that is new enough to support that API.
   97729   *************************************************************************
   97730   */
   97731   sqlite3_overload_function,
   97732 
   97733   /*
   97734   ** Added after 3.3.13
   97735   */
   97736   sqlite3_prepare_v2,
   97737   sqlite3_prepare16_v2,
   97738   sqlite3_clear_bindings,
   97739 
   97740   /*
   97741   ** Added for 3.4.1
   97742   */
   97743   sqlite3_create_module_v2,
   97744 
   97745   /*
   97746   ** Added for 3.5.0
   97747   */
   97748   sqlite3_bind_zeroblob,
   97749   sqlite3_blob_bytes,
   97750   sqlite3_blob_close,
   97751   sqlite3_blob_open,
   97752   sqlite3_blob_read,
   97753   sqlite3_blob_write,
   97754   sqlite3_create_collation_v2,
   97755   sqlite3_file_control,
   97756   sqlite3_memory_highwater,
   97757   sqlite3_memory_used,
   97758 #ifdef SQLITE_MUTEX_OMIT
   97759   0,
   97760   0,
   97761   0,
   97762   0,
   97763   0,
   97764 #else
   97765   sqlite3_mutex_alloc,
   97766   sqlite3_mutex_enter,
   97767   sqlite3_mutex_free,
   97768   sqlite3_mutex_leave,
   97769   sqlite3_mutex_try,
   97770 #endif
   97771   sqlite3_open_v2,
   97772   sqlite3_release_memory,
   97773   sqlite3_result_error_nomem,
   97774   sqlite3_result_error_toobig,
   97775   sqlite3_sleep,
   97776   sqlite3_soft_heap_limit,
   97777   sqlite3_vfs_find,
   97778   sqlite3_vfs_register,
   97779   sqlite3_vfs_unregister,
   97780 
   97781   /*
   97782   ** Added for 3.5.8
   97783   */
   97784   sqlite3_threadsafe,
   97785   sqlite3_result_zeroblob,
   97786   sqlite3_result_error_code,
   97787   sqlite3_test_control,
   97788   sqlite3_randomness,
   97789   sqlite3_context_db_handle,
   97790 
   97791   /*
   97792   ** Added for 3.6.0
   97793   */
   97794   sqlite3_extended_result_codes,
   97795   sqlite3_limit,
   97796   sqlite3_next_stmt,
   97797   sqlite3_sql,
   97798   sqlite3_status,
   97799 
   97800   /*
   97801   ** Added for 3.7.4
   97802   */
   97803   sqlite3_backup_finish,
   97804   sqlite3_backup_init,
   97805   sqlite3_backup_pagecount,
   97806   sqlite3_backup_remaining,
   97807   sqlite3_backup_step,
   97808 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
   97809   sqlite3_compileoption_get,
   97810   sqlite3_compileoption_used,
   97811 #else
   97812   0,
   97813   0,
   97814 #endif
   97815   sqlite3_create_function_v2,
   97816   sqlite3_db_config,
   97817   sqlite3_db_mutex,
   97818   sqlite3_db_status,
   97819   sqlite3_extended_errcode,
   97820   sqlite3_log,
   97821   sqlite3_soft_heap_limit64,
   97822   sqlite3_sourceid,
   97823   sqlite3_stmt_status,
   97824   sqlite3_strnicmp,
   97825 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
   97826   sqlite3_unlock_notify,
   97827 #else
   97828   0,
   97829 #endif
   97830 #ifndef SQLITE_OMIT_WAL
   97831   sqlite3_wal_autocheckpoint,
   97832   sqlite3_wal_checkpoint,
   97833   sqlite3_wal_hook,
   97834 #else
   97835   0,
   97836   0,
   97837   0,
   97838 #endif
   97839   sqlite3_blob_reopen,
   97840   sqlite3_vtab_config,
   97841   sqlite3_vtab_on_conflict,
   97842   sqlite3_close_v2,
   97843   sqlite3_db_filename,
   97844   sqlite3_db_readonly,
   97845   sqlite3_db_release_memory,
   97846   sqlite3_errstr,
   97847   sqlite3_stmt_busy,
   97848   sqlite3_stmt_readonly,
   97849   sqlite3_stricmp,
   97850   sqlite3_uri_boolean,
   97851   sqlite3_uri_int64,
   97852   sqlite3_uri_parameter,
   97853   sqlite3_vsnprintf,
   97854   sqlite3_wal_checkpoint_v2
   97855 };
   97856 
   97857 /*
   97858 ** Attempt to load an SQLite extension library contained in the file
   97859 ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
   97860 ** default entry point name (sqlite3_extension_init) is used.  Use
   97861 ** of the default name is recommended.
   97862 **
   97863 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
   97864 **
   97865 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
   97866 ** error message text.  The calling function should free this memory
   97867 ** by calling sqlite3DbFree(db, ).
   97868 */
   97869 static int sqlite3LoadExtension(
   97870   sqlite3 *db,          /* Load the extension into this database connection */
   97871   const char *zFile,    /* Name of the shared library containing extension */
   97872   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
   97873   char **pzErrMsg       /* Put error message here if not 0 */
   97874 ){
   97875   sqlite3_vfs *pVfs = db->pVfs;
   97876   void *handle;
   97877   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
   97878   char *zErrmsg = 0;
   97879   const char *zEntry;
   97880   char *zAltEntry = 0;
   97881   void **aHandle;
   97882   int nMsg = 300 + sqlite3Strlen30(zFile);
   97883   int ii;
   97884 
   97885   /* Shared library endings to try if zFile cannot be loaded as written */
   97886   static const char *azEndings[] = {
   97887 #if SQLITE_OS_WIN
   97888      "dll"
   97889 #elif defined(__APPLE__)
   97890      "dylib"
   97891 #else
   97892      "so"
   97893 #endif
   97894   };
   97895 
   97896 
   97897   if( pzErrMsg ) *pzErrMsg = 0;
   97898 
   97899   /* Ticket #1863.  To avoid a creating security problems for older
   97900   ** applications that relink against newer versions of SQLite, the
   97901   ** ability to run load_extension is turned off by default.  One
   97902   ** must call sqlite3_enable_load_extension() to turn on extension
   97903   ** loading.  Otherwise you get the following error.
   97904   */
   97905   if( (db->flags & SQLITE_LoadExtension)==0 ){
   97906     if( pzErrMsg ){
   97907       *pzErrMsg = sqlite3_mprintf("not authorized");
   97908     }
   97909     return SQLITE_ERROR;
   97910   }
   97911 
   97912   zEntry = zProc ? zProc : "sqlite3_extension_init";
   97913 
   97914   handle = sqlite3OsDlOpen(pVfs, zFile);
   97915 #if SQLITE_OS_UNIX || SQLITE_OS_WIN
   97916   for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
   97917     char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
   97918     if( zAltFile==0 ) return SQLITE_NOMEM;
   97919     handle = sqlite3OsDlOpen(pVfs, zAltFile);
   97920     sqlite3_free(zAltFile);
   97921   }
   97922 #endif
   97923   if( handle==0 ){
   97924     if( pzErrMsg ){
   97925       *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
   97926       if( zErrmsg ){
   97927         sqlite3_snprintf(nMsg, zErrmsg,
   97928             "unable to open shared library [%s]", zFile);
   97929         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
   97930       }
   97931     }
   97932     return SQLITE_ERROR;
   97933   }
   97934   xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
   97935                    sqlite3OsDlSym(pVfs, handle, zEntry);
   97936 
   97937   /* If no entry point was specified and the default legacy
   97938   ** entry point name "sqlite3_extension_init" was not found, then
   97939   ** construct an entry point name "sqlite3_X_init" where the X is
   97940   ** replaced by the lowercase value of every ASCII alphabetic
   97941   ** character in the filename after the last "/" upto the first ".",
   97942   ** and eliding the first three characters if they are "lib".
   97943   ** Examples:
   97944   **
   97945   **    /usr/local/lib/libExample5.4.3.so ==>  sqlite3_example_init
   97946   **    C:/lib/mathfuncs.dll              ==>  sqlite3_mathfuncs_init
   97947   */
   97948   if( xInit==0 && zProc==0 ){
   97949     int iFile, iEntry, c;
   97950     int ncFile = sqlite3Strlen30(zFile);
   97951     zAltEntry = sqlite3_malloc(ncFile+30);
   97952     if( zAltEntry==0 ){
   97953       sqlite3OsDlClose(pVfs, handle);
   97954       return SQLITE_NOMEM;
   97955     }
   97956     memcpy(zAltEntry, "sqlite3_", 8);
   97957     for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
   97958     iFile++;
   97959     if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
   97960     for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
   97961       if( sqlite3Isalpha(c) ){
   97962         zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
   97963       }
   97964     }
   97965     memcpy(zAltEntry+iEntry, "_init", 6);
   97966     zEntry = zAltEntry;
   97967     xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
   97968                      sqlite3OsDlSym(pVfs, handle, zEntry);
   97969   }
   97970   if( xInit==0 ){
   97971     if( pzErrMsg ){
   97972       nMsg += sqlite3Strlen30(zEntry);
   97973       *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
   97974       if( zErrmsg ){
   97975         sqlite3_snprintf(nMsg, zErrmsg,
   97976             "no entry point [%s] in shared library [%s]", zEntry, zFile);
   97977         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
   97978       }
   97979     }
   97980     sqlite3OsDlClose(pVfs, handle);
   97981     sqlite3_free(zAltEntry);
   97982     return SQLITE_ERROR;
   97983   }
   97984   sqlite3_free(zAltEntry);
   97985   if( xInit(db, &zErrmsg, &sqlite3Apis) ){
   97986     if( pzErrMsg ){
   97987       *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
   97988     }
   97989     sqlite3_free(zErrmsg);
   97990     sqlite3OsDlClose(pVfs, handle);
   97991     return SQLITE_ERROR;
   97992   }
   97993 
   97994   /* Append the new shared library handle to the db->aExtension array. */
   97995   aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
   97996   if( aHandle==0 ){
   97997     return SQLITE_NOMEM;
   97998   }
   97999   if( db->nExtension>0 ){
   98000     memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
   98001   }
   98002   sqlite3DbFree(db, db->aExtension);
   98003   db->aExtension = aHandle;
   98004 
   98005   db->aExtension[db->nExtension++] = handle;
   98006   return SQLITE_OK;
   98007 }
   98008 SQLITE_API int sqlite3_load_extension(
   98009   sqlite3 *db,          /* Load the extension into this database connection */
   98010   const char *zFile,    /* Name of the shared library containing extension */
   98011   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
   98012   char **pzErrMsg       /* Put error message here if not 0 */
   98013 ){
   98014   int rc;
   98015   sqlite3_mutex_enter(db->mutex);
   98016   rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
   98017   rc = sqlite3ApiExit(db, rc);
   98018   sqlite3_mutex_leave(db->mutex);
   98019   return rc;
   98020 }
   98021 
   98022 /*
   98023 ** Call this routine when the database connection is closing in order
   98024 ** to clean up loaded extensions
   98025 */
   98026 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
   98027   int i;
   98028   assert( sqlite3_mutex_held(db->mutex) );
   98029   for(i=0; i<db->nExtension; i++){
   98030     sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
   98031   }
   98032   sqlite3DbFree(db, db->aExtension);
   98033 }
   98034 
   98035 /*
   98036 ** Enable or disable extension loading.  Extension loading is disabled by
   98037 ** default so as not to open security holes in older applications.
   98038 */
   98039 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
   98040   sqlite3_mutex_enter(db->mutex);
   98041   if( onoff ){
   98042     db->flags |= SQLITE_LoadExtension;
   98043   }else{
   98044     db->flags &= ~SQLITE_LoadExtension;
   98045   }
   98046   sqlite3_mutex_leave(db->mutex);
   98047   return SQLITE_OK;
   98048 }
   98049 
   98050 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
   98051 
   98052 /*
   98053 ** The auto-extension code added regardless of whether or not extension
   98054 ** loading is supported.  We need a dummy sqlite3Apis pointer for that
   98055 ** code if regular extension loading is not available.  This is that
   98056 ** dummy pointer.
   98057 */
   98058 #ifdef SQLITE_OMIT_LOAD_EXTENSION
   98059 static const sqlite3_api_routines sqlite3Apis = { 0 };
   98060 #endif
   98061 
   98062 
   98063 /*
   98064 ** The following object holds the list of automatically loaded
   98065 ** extensions.
   98066 **
   98067 ** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
   98068 ** mutex must be held while accessing this list.
   98069 */
   98070 typedef struct sqlite3AutoExtList sqlite3AutoExtList;
   98071 static SQLITE_WSD struct sqlite3AutoExtList {
   98072   int nExt;              /* Number of entries in aExt[] */
   98073   void (**aExt)(void);   /* Pointers to the extension init functions */
   98074 } sqlite3Autoext = { 0, 0 };
   98075 
   98076 /* The "wsdAutoext" macro will resolve to the autoextension
   98077 ** state vector.  If writable static data is unsupported on the target,
   98078 ** we have to locate the state vector at run-time.  In the more common
   98079 ** case where writable static data is supported, wsdStat can refer directly
   98080 ** to the "sqlite3Autoext" state vector declared above.
   98081 */
   98082 #ifdef SQLITE_OMIT_WSD
   98083 # define wsdAutoextInit \
   98084   sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
   98085 # define wsdAutoext x[0]
   98086 #else
   98087 # define wsdAutoextInit
   98088 # define wsdAutoext sqlite3Autoext
   98089 #endif
   98090 
   98091 
   98092 /*
   98093 ** Register a statically linked extension that is automatically
   98094 ** loaded by every new database connection.
   98095 */
   98096 SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
   98097   int rc = SQLITE_OK;
   98098 #ifndef SQLITE_OMIT_AUTOINIT
   98099   rc = sqlite3_initialize();
   98100   if( rc ){
   98101     return rc;
   98102   }else
   98103 #endif
   98104   {
   98105     int i;
   98106 #if SQLITE_THREADSAFE
   98107     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   98108 #endif
   98109     wsdAutoextInit;
   98110     sqlite3_mutex_enter(mutex);
   98111     for(i=0; i<wsdAutoext.nExt; i++){
   98112       if( wsdAutoext.aExt[i]==xInit ) break;
   98113     }
   98114     if( i==wsdAutoext.nExt ){
   98115       int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
   98116       void (**aNew)(void);
   98117       aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
   98118       if( aNew==0 ){
   98119         rc = SQLITE_NOMEM;
   98120       }else{
   98121         wsdAutoext.aExt = aNew;
   98122         wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
   98123         wsdAutoext.nExt++;
   98124       }
   98125     }
   98126     sqlite3_mutex_leave(mutex);
   98127     assert( (rc&0xff)==rc );
   98128     return rc;
   98129   }
   98130 }
   98131 
   98132 /*
   98133 ** Cancel a prior call to sqlite3_auto_extension.  Remove xInit from the
   98134 ** set of routines that is invoked for each new database connection, if it
   98135 ** is currently on the list.  If xInit is not on the list, then this
   98136 ** routine is a no-op.
   98137 **
   98138 ** Return 1 if xInit was found on the list and removed.  Return 0 if xInit
   98139 ** was not on the list.
   98140 */
   98141 SQLITE_API int sqlite3_cancel_auto_extension(void (*xInit)(void)){
   98142 #if SQLITE_THREADSAFE
   98143   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   98144 #endif
   98145   int i;
   98146   int n = 0;
   98147   wsdAutoextInit;
   98148   sqlite3_mutex_enter(mutex);
   98149   for(i=wsdAutoext.nExt-1; i>=0; i--){
   98150     if( wsdAutoext.aExt[i]==xInit ){
   98151       wsdAutoext.nExt--;
   98152       wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
   98153       n++;
   98154       break;
   98155     }
   98156   }
   98157   sqlite3_mutex_leave(mutex);
   98158   return n;
   98159 }
   98160 
   98161 /*
   98162 ** Reset the automatic extension loading mechanism.
   98163 */
   98164 SQLITE_API void sqlite3_reset_auto_extension(void){
   98165 #ifndef SQLITE_OMIT_AUTOINIT
   98166   if( sqlite3_initialize()==SQLITE_OK )
   98167 #endif
   98168   {
   98169 #if SQLITE_THREADSAFE
   98170     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   98171 #endif
   98172     wsdAutoextInit;
   98173     sqlite3_mutex_enter(mutex);
   98174     sqlite3_free(wsdAutoext.aExt);
   98175     wsdAutoext.aExt = 0;
   98176     wsdAutoext.nExt = 0;
   98177     sqlite3_mutex_leave(mutex);
   98178   }
   98179 }
   98180 
   98181 /*
   98182 ** Load all automatic extensions.
   98183 **
   98184 ** If anything goes wrong, set an error in the database connection.
   98185 */
   98186 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
   98187   int i;
   98188   int go = 1;
   98189   int rc;
   98190   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
   98191 
   98192   wsdAutoextInit;
   98193   if( wsdAutoext.nExt==0 ){
   98194     /* Common case: early out without every having to acquire a mutex */
   98195     return;
   98196   }
   98197   for(i=0; go; i++){
   98198     char *zErrmsg;
   98199 #if SQLITE_THREADSAFE
   98200     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   98201 #endif
   98202     sqlite3_mutex_enter(mutex);
   98203     if( i>=wsdAutoext.nExt ){
   98204       xInit = 0;
   98205       go = 0;
   98206     }else{
   98207       xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
   98208               wsdAutoext.aExt[i];
   98209     }
   98210     sqlite3_mutex_leave(mutex);
   98211     zErrmsg = 0;
   98212     if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
   98213       sqlite3Error(db, rc,
   98214             "automatic extension loading failed: %s", zErrmsg);
   98215       go = 0;
   98216     }
   98217     sqlite3_free(zErrmsg);
   98218   }
   98219 }
   98220 
   98221 /************** End of loadext.c *********************************************/
   98222 /************** Begin file pragma.c ******************************************/
   98223 /*
   98224 ** 2003 April 6
   98225 **
   98226 ** The author disclaims copyright to this source code.  In place of
   98227 ** a legal notice, here is a blessing:
   98228 **
   98229 **    May you do good and not evil.
   98230 **    May you find forgiveness for yourself and forgive others.
   98231 **    May you share freely, never taking more than you give.
   98232 **
   98233 *************************************************************************
   98234 ** This file contains code used to implement the PRAGMA command.
   98235 */
   98236 
   98237 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
   98238 #  if defined(__APPLE__)
   98239 #    define SQLITE_ENABLE_LOCKING_STYLE 1
   98240 #  else
   98241 #    define SQLITE_ENABLE_LOCKING_STYLE 0
   98242 #  endif
   98243 #endif
   98244 
   98245 /***************************************************************************
   98246 ** The next block of code, including the PragTyp_XXXX macro definitions and
   98247 ** the aPragmaName[] object is composed of generated code. DO NOT EDIT.
   98248 **
   98249 ** To add new pragmas, edit the code in ../tool/mkpragmatab.tcl and rerun
   98250 ** that script.  Then copy/paste the output in place of the following:
   98251 */
   98252 #define PragTyp_HEADER_VALUE                   0
   98253 #define PragTyp_AUTO_VACUUM                    1
   98254 #define PragTyp_FLAG                           2
   98255 #define PragTyp_BUSY_TIMEOUT                   3
   98256 #define PragTyp_CACHE_SIZE                     4
   98257 #define PragTyp_CASE_SENSITIVE_LIKE            5
   98258 #define PragTyp_COLLATION_LIST                 6
   98259 #define PragTyp_COMPILE_OPTIONS                7
   98260 #define PragTyp_DATA_STORE_DIRECTORY           8
   98261 #define PragTyp_DATABASE_LIST                  9
   98262 #define PragTyp_DEFAULT_CACHE_SIZE            10
   98263 #define PragTyp_ENCODING                      11
   98264 #define PragTyp_FOREIGN_KEY_CHECK             12
   98265 #define PragTyp_FOREIGN_KEY_LIST              13
   98266 #define PragTyp_INCREMENTAL_VACUUM            14
   98267 #define PragTyp_INDEX_INFO                    15
   98268 #define PragTyp_INDEX_LIST                    16
   98269 #define PragTyp_INTEGRITY_CHECK               17
   98270 #define PragTyp_JOURNAL_MODE                  18
   98271 #define PragTyp_JOURNAL_SIZE_LIMIT            19
   98272 #define PragTyp_LOCK_PROXY_FILE               20
   98273 #define PragTyp_LOCKING_MODE                  21
   98274 #define PragTyp_PAGE_COUNT                    22
   98275 #define PragTyp_MMAP_SIZE                     23
   98276 #define PragTyp_PAGE_SIZE                     24
   98277 #define PragTyp_SECURE_DELETE                 25
   98278 #define PragTyp_SHRINK_MEMORY                 26
   98279 #define PragTyp_SOFT_HEAP_LIMIT               27
   98280 #define PragTyp_STATS                         28
   98281 #define PragTyp_SYNCHRONOUS                   29
   98282 #define PragTyp_TABLE_INFO                    30
   98283 #define PragTyp_TEMP_STORE                    31
   98284 #define PragTyp_TEMP_STORE_DIRECTORY          32
   98285 #define PragTyp_WAL_AUTOCHECKPOINT            33
   98286 #define PragTyp_WAL_CHECKPOINT                34
   98287 #define PragTyp_ACTIVATE_EXTENSIONS           35
   98288 #define PragTyp_HEXKEY                        36
   98289 #define PragTyp_KEY                           37
   98290 #define PragTyp_REKEY                         38
   98291 #define PragTyp_LOCK_STATUS                   39
   98292 #define PragTyp_PARSER_TRACE                  40
   98293 #define PragFlag_NeedSchema           0x01
   98294 static const struct sPragmaNames {
   98295   const char *const zName;  /* Name of pragma */
   98296   u8 ePragTyp;              /* PragTyp_XXX value */
   98297   u8 mPragFlag;             /* Zero or more PragFlag_XXX values */
   98298   u32 iArg;                 /* Extra argument */
   98299 } aPragmaNames[] = {
   98300 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
   98301   { /* zName:     */ "activate_extensions",
   98302     /* ePragTyp:  */ PragTyp_ACTIVATE_EXTENSIONS,
   98303     /* ePragFlag: */ 0,
   98304     /* iArg:      */ 0 },
   98305 #endif
   98306 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
   98307   { /* zName:     */ "application_id",
   98308     /* ePragTyp:  */ PragTyp_HEADER_VALUE,
   98309     /* ePragFlag: */ 0,
   98310     /* iArg:      */ 0 },
   98311 #endif
   98312 #if !defined(SQLITE_OMIT_AUTOVACUUM)
   98313   { /* zName:     */ "auto_vacuum",
   98314     /* ePragTyp:  */ PragTyp_AUTO_VACUUM,
   98315     /* ePragFlag: */ PragFlag_NeedSchema,
   98316     /* iArg:      */ 0 },
   98317 #endif
   98318 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   98319 #if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
   98320   { /* zName:     */ "automatic_index",
   98321     /* ePragTyp:  */ PragTyp_FLAG,
   98322     /* ePragFlag: */ 0,
   98323     /* iArg:      */ SQLITE_AutoIndex },
   98324 #endif
   98325 #endif
   98326   { /* zName:     */ "busy_timeout",
   98327     /* ePragTyp:  */ PragTyp_BUSY_TIMEOUT,
   98328     /* ePragFlag: */ 0,
   98329     /* iArg:      */ 0 },
   98330 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
   98331   { /* zName:     */ "cache_size",
   98332     /* ePragTyp:  */ PragTyp_CACHE_SIZE,
   98333     /* ePragFlag: */ PragFlag_NeedSchema,
   98334     /* iArg:      */ 0 },
   98335 #endif
   98336 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   98337   { /* zName:     */ "cache_spill",
   98338     /* ePragTyp:  */ PragTyp_FLAG,
   98339     /* ePragFlag: */ 0,
   98340     /* iArg:      */ SQLITE_CacheSpill },
   98341 #endif
   98342   { /* zName:     */ "case_sensitive_like",
   98343     /* ePragTyp:  */ PragTyp_CASE_SENSITIVE_LIKE,
   98344     /* ePragFlag: */ 0,
   98345     /* iArg:      */ 0 },
   98346 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   98347   { /* zName:     */ "checkpoint_fullfsync",
   98348     /* ePragTyp:  */ PragTyp_FLAG,
   98349     /* ePragFlag: */ 0,
   98350     /* iArg:      */ SQLITE_CkptFullFSync },
   98351 #endif
   98352 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
   98353   { /* zName:     */ "collation_list",
   98354     /* ePragTyp:  */ PragTyp_COLLATION_LIST,
   98355     /* ePragFlag: */ 0,
   98356     /* iArg:      */ 0 },
   98357 #endif
   98358 #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
   98359   { /* zName:     */ "compile_options",
   98360     /* ePragTyp:  */ PragTyp_COMPILE_OPTIONS,
   98361     /* ePragFlag: */ 0,
   98362     /* iArg:      */ 0 },
   98363 #endif
   98364 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   98365   { /* zName:     */ "count_changes",
   98366     /* ePragTyp:  */ PragTyp_FLAG,
   98367     /* ePragFlag: */ 0,
   98368     /* iArg:      */ SQLITE_CountRows },
   98369 #endif
   98370 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
   98371   { /* zName:     */ "data_store_directory",
   98372     /* ePragTyp:  */ PragTyp_DATA_STORE_DIRECTORY,
   98373     /* ePragFlag: */ 0,
   98374     /* iArg:      */ 0 },
   98375 #endif
   98376 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
   98377   { /* zName:     */ "database_list",
   98378     /* ePragTyp:  */ PragTyp_DATABASE_LIST,
   98379     /* ePragFlag: */ PragFlag_NeedSchema,
   98380     /* iArg:      */ 0 },
   98381 #endif
   98382 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
   98383   { /* zName:     */ "default_cache_size",
   98384     /* ePragTyp:  */ PragTyp_DEFAULT_CACHE_SIZE,
   98385     /* ePragFlag: */ PragFlag_NeedSchema,
   98386     /* iArg:      */ 0 },
   98387 #endif
   98388 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   98389 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
   98390   { /* zName:     */ "defer_foreign_keys",
   98391     /* ePragTyp:  */ PragTyp_FLAG,
   98392     /* ePragFlag: */ 0,
   98393     /* iArg:      */ SQLITE_DeferFKs },
   98394 #endif
   98395 #endif
   98396 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   98397   { /* zName:     */ "empty_result_callbacks",
   98398     /* ePragTyp:  */ PragTyp_FLAG,
   98399     /* ePragFlag: */ 0,
   98400     /* iArg:      */ SQLITE_NullCallback },
   98401 #endif
   98402 #if !defined(SQLITE_OMIT_UTF16)
   98403   { /* zName:     */ "encoding",
   98404     /* ePragTyp:  */ PragTyp_ENCODING,
   98405     /* ePragFlag: */ 0,
   98406     /* iArg:      */ 0 },
   98407 #endif
   98408 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
   98409   { /* zName:     */ "foreign_key_check",
   98410     /* ePragTyp:  */ PragTyp_FOREIGN_KEY_CHECK,
   98411     /* ePragFlag: */ PragFlag_NeedSchema,
   98412     /* iArg:      */ 0 },
   98413 #endif
   98414 #if !defined(SQLITE_OMIT_FOREIGN_KEY)
   98415   { /* zName:     */ "foreign_key_list",
   98416     /* ePragTyp:  */ PragTyp_FOREIGN_KEY_LIST,
   98417     /* ePragFlag: */ PragFlag_NeedSchema,
   98418     /* iArg:      */ 0 },
   98419 #endif
   98420 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   98421 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
   98422   { /* zName:     */ "foreign_keys",
   98423     /* ePragTyp:  */ PragTyp_FLAG,
   98424     /* ePragFlag: */ 0,
   98425     /* iArg:      */ SQLITE_ForeignKeys },
   98426 #endif
   98427 #endif
   98428 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
   98429   { /* zName:     */ "freelist_count",
   98430     /* ePragTyp:  */ PragTyp_HEADER_VALUE,
   98431     /* ePragFlag: */ 0,
   98432     /* iArg:      */ 0 },
   98433 #endif
   98434 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   98435   { /* zName:     */ "full_column_names",
   98436     /* ePragTyp:  */ PragTyp_FLAG,
   98437     /* ePragFlag: */ 0,
   98438     /* iArg:      */ SQLITE_FullColNames },
   98439   { /* zName:     */ "fullfsync",
   98440     /* ePragTyp:  */ PragTyp_FLAG,
   98441     /* ePragFlag: */ 0,
   98442     /* iArg:      */ SQLITE_FullFSync },
   98443 #endif
   98444 #if defined(SQLITE_HAS_CODEC)
   98445   { /* zName:     */ "hexkey",
   98446     /* ePragTyp:  */ PragTyp_HEXKEY,
   98447     /* ePragFlag: */ 0,
   98448     /* iArg:      */ 0 },
   98449   { /* zName:     */ "hexrekey",
   98450     /* ePragTyp:  */ PragTyp_HEXKEY,
   98451     /* ePragFlag: */ 0,
   98452     /* iArg:      */ 0 },
   98453 #endif
   98454 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   98455 #if !defined(SQLITE_OMIT_CHECK)
   98456   { /* zName:     */ "ignore_check_constraints",
   98457     /* ePragTyp:  */ PragTyp_FLAG,
   98458     /* ePragFlag: */ 0,
   98459     /* iArg:      */ SQLITE_IgnoreChecks },
   98460 #endif
   98461 #endif
   98462 #if !defined(SQLITE_OMIT_AUTOVACUUM)
   98463   { /* zName:     */ "incremental_vacuum",
   98464     /* ePragTyp:  */ PragTyp_INCREMENTAL_VACUUM,
   98465     /* ePragFlag: */ PragFlag_NeedSchema,
   98466     /* iArg:      */ 0 },
   98467 #endif
   98468 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
   98469   { /* zName:     */ "index_info",
   98470     /* ePragTyp:  */ PragTyp_INDEX_INFO,
   98471     /* ePragFlag: */ PragFlag_NeedSchema,
   98472     /* iArg:      */ 0 },
   98473   { /* zName:     */ "index_list",
   98474     /* ePragTyp:  */ PragTyp_INDEX_LIST,
   98475     /* ePragFlag: */ PragFlag_NeedSchema,
   98476     /* iArg:      */ 0 },
   98477 #endif
   98478 #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
   98479   { /* zName:     */ "integrity_check",
   98480     /* ePragTyp:  */ PragTyp_INTEGRITY_CHECK,
   98481     /* ePragFlag: */ PragFlag_NeedSchema,
   98482     /* iArg:      */ 0 },
   98483 #endif
   98484 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
   98485   { /* zName:     */ "journal_mode",
   98486     /* ePragTyp:  */ PragTyp_JOURNAL_MODE,
   98487     /* ePragFlag: */ PragFlag_NeedSchema,
   98488     /* iArg:      */ 0 },
   98489   { /* zName:     */ "journal_size_limit",
   98490     /* ePragTyp:  */ PragTyp_JOURNAL_SIZE_LIMIT,
   98491     /* ePragFlag: */ 0,
   98492     /* iArg:      */ 0 },
   98493 #endif
   98494 #if defined(SQLITE_HAS_CODEC)
   98495   { /* zName:     */ "key",
   98496     /* ePragTyp:  */ PragTyp_KEY,
   98497     /* ePragFlag: */ 0,
   98498     /* iArg:      */ 0 },
   98499 #endif
   98500 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   98501   { /* zName:     */ "legacy_file_format",
   98502     /* ePragTyp:  */ PragTyp_FLAG,
   98503     /* ePragFlag: */ 0,
   98504     /* iArg:      */ SQLITE_LegacyFileFmt },
   98505 #endif
   98506 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
   98507   { /* zName:     */ "lock_proxy_file",
   98508     /* ePragTyp:  */ PragTyp_LOCK_PROXY_FILE,
   98509     /* ePragFlag: */ 0,
   98510     /* iArg:      */ 0 },
   98511 #endif
   98512 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
   98513   { /* zName:     */ "lock_status",
   98514     /* ePragTyp:  */ PragTyp_LOCK_STATUS,
   98515     /* ePragFlag: */ 0,
   98516     /* iArg:      */ 0 },
   98517 #endif
   98518 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
   98519   { /* zName:     */ "locking_mode",
   98520     /* ePragTyp:  */ PragTyp_LOCKING_MODE,
   98521     /* ePragFlag: */ 0,
   98522     /* iArg:      */ 0 },
   98523   { /* zName:     */ "max_page_count",
   98524     /* ePragTyp:  */ PragTyp_PAGE_COUNT,
   98525     /* ePragFlag: */ PragFlag_NeedSchema,
   98526     /* iArg:      */ 0 },
   98527   { /* zName:     */ "mmap_size",
   98528     /* ePragTyp:  */ PragTyp_MMAP_SIZE,
   98529     /* ePragFlag: */ 0,
   98530     /* iArg:      */ 0 },
   98531   { /* zName:     */ "page_count",
   98532     /* ePragTyp:  */ PragTyp_PAGE_COUNT,
   98533     /* ePragFlag: */ PragFlag_NeedSchema,
   98534     /* iArg:      */ 0 },
   98535   { /* zName:     */ "page_size",
   98536     /* ePragTyp:  */ PragTyp_PAGE_SIZE,
   98537     /* ePragFlag: */ 0,
   98538     /* iArg:      */ 0 },
   98539 #endif
   98540 #if defined(SQLITE_DEBUG)
   98541   { /* zName:     */ "parser_trace",
   98542     /* ePragTyp:  */ PragTyp_PARSER_TRACE,
   98543     /* ePragFlag: */ 0,
   98544     /* iArg:      */ 0 },
   98545 #endif
   98546 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   98547   { /* zName:     */ "query_only",
   98548     /* ePragTyp:  */ PragTyp_FLAG,
   98549     /* ePragFlag: */ 0,
   98550     /* iArg:      */ SQLITE_QueryOnly },
   98551 #endif
   98552 #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
   98553   { /* zName:     */ "quick_check",
   98554     /* ePragTyp:  */ PragTyp_INTEGRITY_CHECK,
   98555     /* ePragFlag: */ PragFlag_NeedSchema,
   98556     /* iArg:      */ 0 },
   98557 #endif
   98558 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   98559   { /* zName:     */ "read_uncommitted",
   98560     /* ePragTyp:  */ PragTyp_FLAG,
   98561     /* ePragFlag: */ 0,
   98562     /* iArg:      */ SQLITE_ReadUncommitted },
   98563   { /* zName:     */ "recursive_triggers",
   98564     /* ePragTyp:  */ PragTyp_FLAG,
   98565     /* ePragFlag: */ 0,
   98566     /* iArg:      */ SQLITE_RecTriggers },
   98567 #endif
   98568 #if defined(SQLITE_HAS_CODEC)
   98569   { /* zName:     */ "rekey",
   98570     /* ePragTyp:  */ PragTyp_REKEY,
   98571     /* ePragFlag: */ 0,
   98572     /* iArg:      */ 0 },
   98573 #endif
   98574 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   98575   { /* zName:     */ "reverse_unordered_selects",
   98576     /* ePragTyp:  */ PragTyp_FLAG,
   98577     /* ePragFlag: */ 0,
   98578     /* iArg:      */ SQLITE_ReverseOrder },
   98579 #endif
   98580 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
   98581   { /* zName:     */ "schema_version",
   98582     /* ePragTyp:  */ PragTyp_HEADER_VALUE,
   98583     /* ePragFlag: */ 0,
   98584     /* iArg:      */ 0 },
   98585 #endif
   98586 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
   98587   { /* zName:     */ "secure_delete",
   98588     /* ePragTyp:  */ PragTyp_SECURE_DELETE,
   98589     /* ePragFlag: */ 0,
   98590     /* iArg:      */ 0 },
   98591 #endif
   98592 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   98593   { /* zName:     */ "short_column_names",
   98594     /* ePragTyp:  */ PragTyp_FLAG,
   98595     /* ePragFlag: */ 0,
   98596     /* iArg:      */ SQLITE_ShortColNames },
   98597 #endif
   98598   { /* zName:     */ "shrink_memory",
   98599     /* ePragTyp:  */ PragTyp_SHRINK_MEMORY,
   98600     /* ePragFlag: */ 0,
   98601     /* iArg:      */ 0 },
   98602   { /* zName:     */ "soft_heap_limit",
   98603     /* ePragTyp:  */ PragTyp_SOFT_HEAP_LIMIT,
   98604     /* ePragFlag: */ 0,
   98605     /* iArg:      */ 0 },
   98606 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   98607 #if defined(SQLITE_DEBUG)
   98608   { /* zName:     */ "sql_trace",
   98609     /* ePragTyp:  */ PragTyp_FLAG,
   98610     /* ePragFlag: */ 0,
   98611     /* iArg:      */ SQLITE_SqlTrace },
   98612 #endif
   98613 #endif
   98614 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
   98615   { /* zName:     */ "stats",
   98616     /* ePragTyp:  */ PragTyp_STATS,
   98617     /* ePragFlag: */ PragFlag_NeedSchema,
   98618     /* iArg:      */ 0 },
   98619 #endif
   98620 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
   98621   { /* zName:     */ "synchronous",
   98622     /* ePragTyp:  */ PragTyp_SYNCHRONOUS,
   98623     /* ePragFlag: */ PragFlag_NeedSchema,
   98624     /* iArg:      */ 0 },
   98625 #endif
   98626 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
   98627   { /* zName:     */ "table_info",
   98628     /* ePragTyp:  */ PragTyp_TABLE_INFO,
   98629     /* ePragFlag: */ PragFlag_NeedSchema,
   98630     /* iArg:      */ 0 },
   98631 #endif
   98632 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
   98633   { /* zName:     */ "temp_store",
   98634     /* ePragTyp:  */ PragTyp_TEMP_STORE,
   98635     /* ePragFlag: */ 0,
   98636     /* iArg:      */ 0 },
   98637   { /* zName:     */ "temp_store_directory",
   98638     /* ePragTyp:  */ PragTyp_TEMP_STORE_DIRECTORY,
   98639     /* ePragFlag: */ 0,
   98640     /* iArg:      */ 0 },
   98641 #endif
   98642 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
   98643   { /* zName:     */ "user_version",
   98644     /* ePragTyp:  */ PragTyp_HEADER_VALUE,
   98645     /* ePragFlag: */ 0,
   98646     /* iArg:      */ 0 },
   98647 #endif
   98648 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   98649 #if defined(SQLITE_DEBUG)
   98650   { /* zName:     */ "vdbe_addoptrace",
   98651     /* ePragTyp:  */ PragTyp_FLAG,
   98652     /* ePragFlag: */ 0,
   98653     /* iArg:      */ SQLITE_VdbeAddopTrace },
   98654   { /* zName:     */ "vdbe_debug",
   98655     /* ePragTyp:  */ PragTyp_FLAG,
   98656     /* ePragFlag: */ 0,
   98657     /* iArg:      */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
   98658   { /* zName:     */ "vdbe_eqp",
   98659     /* ePragTyp:  */ PragTyp_FLAG,
   98660     /* ePragFlag: */ 0,
   98661     /* iArg:      */ SQLITE_VdbeEQP },
   98662   { /* zName:     */ "vdbe_listing",
   98663     /* ePragTyp:  */ PragTyp_FLAG,
   98664     /* ePragFlag: */ 0,
   98665     /* iArg:      */ SQLITE_VdbeListing },
   98666   { /* zName:     */ "vdbe_trace",
   98667     /* ePragTyp:  */ PragTyp_FLAG,
   98668     /* ePragFlag: */ 0,
   98669     /* iArg:      */ SQLITE_VdbeTrace },
   98670 #endif
   98671 #endif
   98672 #if !defined(SQLITE_OMIT_WAL)
   98673   { /* zName:     */ "wal_autocheckpoint",
   98674     /* ePragTyp:  */ PragTyp_WAL_AUTOCHECKPOINT,
   98675     /* ePragFlag: */ 0,
   98676     /* iArg:      */ 0 },
   98677   { /* zName:     */ "wal_checkpoint",
   98678     /* ePragTyp:  */ PragTyp_WAL_CHECKPOINT,
   98679     /* ePragFlag: */ PragFlag_NeedSchema,
   98680     /* iArg:      */ 0 },
   98681 #endif
   98682 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   98683   { /* zName:     */ "writable_schema",
   98684     /* ePragTyp:  */ PragTyp_FLAG,
   98685     /* ePragFlag: */ 0,
   98686     /* iArg:      */ SQLITE_WriteSchema|SQLITE_RecoveryMode },
   98687 #endif
   98688 };
   98689 /* Number of pragmas: 56 on by default, 69 total. */
   98690 /* End of the automatically generated pragma table.
   98691 ***************************************************************************/
   98692 
   98693 /*
   98694 ** Interpret the given string as a safety level.  Return 0 for OFF,
   98695 ** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or
   98696 ** unrecognized string argument.  The FULL option is disallowed
   98697 ** if the omitFull parameter it 1.
   98698 **
   98699 ** Note that the values returned are one less that the values that
   98700 ** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
   98701 ** to support legacy SQL code.  The safety level used to be boolean
   98702 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
   98703 */
   98704 static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){
   98705                              /* 123456789 123456789 */
   98706   static const char zText[] = "onoffalseyestruefull";
   98707   static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
   98708   static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
   98709   static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
   98710   int i, n;
   98711   if( sqlite3Isdigit(*z) ){
   98712     return (u8)sqlite3Atoi(z);
   98713   }
   98714   n = sqlite3Strlen30(z);
   98715   for(i=0; i<ArraySize(iLength)-omitFull; i++){
   98716     if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
   98717       return iValue[i];
   98718     }
   98719   }
   98720   return dflt;
   98721 }
   98722 
   98723 /*
   98724 ** Interpret the given string as a boolean value.
   98725 */
   98726 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8 dflt){
   98727   return getSafetyLevel(z,1,dflt)!=0;
   98728 }
   98729 
   98730 /* The sqlite3GetBoolean() function is used by other modules but the
   98731 ** remainder of this file is specific to PRAGMA processing.  So omit
   98732 ** the rest of the file if PRAGMAs are omitted from the build.
   98733 */
   98734 #if !defined(SQLITE_OMIT_PRAGMA)
   98735 
   98736 /*
   98737 ** Interpret the given string as a locking mode value.
   98738 */
   98739 static int getLockingMode(const char *z){
   98740   if( z ){
   98741     if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
   98742     if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
   98743   }
   98744   return PAGER_LOCKINGMODE_QUERY;
   98745 }
   98746 
   98747 #ifndef SQLITE_OMIT_AUTOVACUUM
   98748 /*
   98749 ** Interpret the given string as an auto-vacuum mode value.
   98750 **
   98751 ** The following strings, "none", "full" and "incremental" are
   98752 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
   98753 */
   98754 static int getAutoVacuum(const char *z){
   98755   int i;
   98756   if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
   98757   if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
   98758   if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
   98759   i = sqlite3Atoi(z);
   98760   return (u8)((i>=0&&i<=2)?i:0);
   98761 }
   98762 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
   98763 
   98764 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   98765 /*
   98766 ** Interpret the given string as a temp db location. Return 1 for file
   98767 ** backed temporary databases, 2 for the Red-Black tree in memory database
   98768 ** and 0 to use the compile-time default.
   98769 */
   98770 static int getTempStore(const char *z){
   98771   if( z[0]>='0' && z[0]<='2' ){
   98772     return z[0] - '0';
   98773   }else if( sqlite3StrICmp(z, "file")==0 ){
   98774     return 1;
   98775   }else if( sqlite3StrICmp(z, "memory")==0 ){
   98776     return 2;
   98777   }else{
   98778     return 0;
   98779   }
   98780 }
   98781 #endif /* SQLITE_PAGER_PRAGMAS */
   98782 
   98783 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   98784 /*
   98785 ** Invalidate temp storage, either when the temp storage is changed
   98786 ** from default, or when 'file' and the temp_store_directory has changed
   98787 */
   98788 static int invalidateTempStorage(Parse *pParse){
   98789   sqlite3 *db = pParse->db;
   98790   if( db->aDb[1].pBt!=0 ){
   98791     if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
   98792       sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
   98793         "from within a transaction");
   98794       return SQLITE_ERROR;
   98795     }
   98796     sqlite3BtreeClose(db->aDb[1].pBt);
   98797     db->aDb[1].pBt = 0;
   98798     sqlite3ResetAllSchemasOfConnection(db);
   98799   }
   98800   return SQLITE_OK;
   98801 }
   98802 #endif /* SQLITE_PAGER_PRAGMAS */
   98803 
   98804 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   98805 /*
   98806 ** If the TEMP database is open, close it and mark the database schema
   98807 ** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
   98808 ** or DEFAULT_TEMP_STORE pragmas.
   98809 */
   98810 static int changeTempStorage(Parse *pParse, const char *zStorageType){
   98811   int ts = getTempStore(zStorageType);
   98812   sqlite3 *db = pParse->db;
   98813   if( db->temp_store==ts ) return SQLITE_OK;
   98814   if( invalidateTempStorage( pParse ) != SQLITE_OK ){
   98815     return SQLITE_ERROR;
   98816   }
   98817   db->temp_store = (u8)ts;
   98818   return SQLITE_OK;
   98819 }
   98820 #endif /* SQLITE_PAGER_PRAGMAS */
   98821 
   98822 /*
   98823 ** Generate code to return a single integer value.
   98824 */
   98825 static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
   98826   Vdbe *v = sqlite3GetVdbe(pParse);
   98827   int mem = ++pParse->nMem;
   98828   i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
   98829   if( pI64 ){
   98830     memcpy(pI64, &value, sizeof(value));
   98831   }
   98832   sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
   98833   sqlite3VdbeSetNumCols(v, 1);
   98834   sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
   98835   sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
   98836 }
   98837 
   98838 
   98839 /*
   98840 ** Set the safety_level and pager flags for pager iDb.  Or if iDb<0
   98841 ** set these values for all pagers.
   98842 */
   98843 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   98844 static void setAllPagerFlags(sqlite3 *db){
   98845   if( db->autoCommit ){
   98846     Db *pDb = db->aDb;
   98847     int n = db->nDb;
   98848     assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
   98849     assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
   98850     assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
   98851     assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
   98852              ==  PAGER_FLAGS_MASK );
   98853     assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
   98854     while( (n--) > 0 ){
   98855       if( pDb->pBt ){
   98856         sqlite3BtreeSetPagerFlags(pDb->pBt,
   98857                  pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
   98858       }
   98859       pDb++;
   98860     }
   98861   }
   98862 }
   98863 #else
   98864 # define setAllPagerFlags(X)  /* no-op */
   98865 #endif
   98866 
   98867 
   98868 /*
   98869 ** Return a human-readable name for a constraint resolution action.
   98870 */
   98871 #ifndef SQLITE_OMIT_FOREIGN_KEY
   98872 static const char *actionName(u8 action){
   98873   const char *zName;
   98874   switch( action ){
   98875     case OE_SetNull:  zName = "SET NULL";        break;
   98876     case OE_SetDflt:  zName = "SET DEFAULT";     break;
   98877     case OE_Cascade:  zName = "CASCADE";         break;
   98878     case OE_Restrict: zName = "RESTRICT";        break;
   98879     default:          zName = "NO ACTION";
   98880                       assert( action==OE_None ); break;
   98881   }
   98882   return zName;
   98883 }
   98884 #endif
   98885 
   98886 
   98887 /*
   98888 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
   98889 ** defined in pager.h. This function returns the associated lowercase
   98890 ** journal-mode name.
   98891 */
   98892 SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
   98893   static char * const azModeName[] = {
   98894     "delete", "persist", "off", "truncate", "memory"
   98895 #ifndef SQLITE_OMIT_WAL
   98896      , "wal"
   98897 #endif
   98898   };
   98899   assert( PAGER_JOURNALMODE_DELETE==0 );
   98900   assert( PAGER_JOURNALMODE_PERSIST==1 );
   98901   assert( PAGER_JOURNALMODE_OFF==2 );
   98902   assert( PAGER_JOURNALMODE_TRUNCATE==3 );
   98903   assert( PAGER_JOURNALMODE_MEMORY==4 );
   98904   assert( PAGER_JOURNALMODE_WAL==5 );
   98905   assert( eMode>=0 && eMode<=ArraySize(azModeName) );
   98906 
   98907   if( eMode==ArraySize(azModeName) ) return 0;
   98908   return azModeName[eMode];
   98909 }
   98910 
   98911 /*
   98912 ** Process a pragma statement.
   98913 **
   98914 ** Pragmas are of this form:
   98915 **
   98916 **      PRAGMA [database.]id [= value]
   98917 **
   98918 ** The identifier might also be a string.  The value is a string, and
   98919 ** identifier, or a number.  If minusFlag is true, then the value is
   98920 ** a number that was preceded by a minus sign.
   98921 **
   98922 ** If the left side is "database.id" then pId1 is the database name
   98923 ** and pId2 is the id.  If the left side is just "id" then pId1 is the
   98924 ** id and pId2 is any empty string.
   98925 */
   98926 SQLITE_PRIVATE void sqlite3Pragma(
   98927   Parse *pParse,
   98928   Token *pId1,        /* First part of [database.]id field */
   98929   Token *pId2,        /* Second part of [database.]id field, or NULL */
   98930   Token *pValue,      /* Token for <value>, or NULL */
   98931   int minusFlag       /* True if a '-' sign preceded <value> */
   98932 ){
   98933   char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
   98934   char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
   98935   const char *zDb = 0;   /* The database name */
   98936   Token *pId;            /* Pointer to <id> token */
   98937   char *aFcntl[4];       /* Argument to SQLITE_FCNTL_PRAGMA */
   98938   int iDb;               /* Database index for <database> */
   98939   int lwr, upr, mid;           /* Binary search bounds */
   98940   int rc;                      /* return value form SQLITE_FCNTL_PRAGMA */
   98941   sqlite3 *db = pParse->db;    /* The database connection */
   98942   Db *pDb;                     /* The specific database being pragmaed */
   98943   Vdbe *v = sqlite3GetVdbe(pParse);  /* Prepared statement */
   98944 
   98945   if( v==0 ) return;
   98946   sqlite3VdbeRunOnlyOnce(v);
   98947   pParse->nMem = 2;
   98948 
   98949   /* Interpret the [database.] part of the pragma statement. iDb is the
   98950   ** index of the database this pragma is being applied to in db.aDb[]. */
   98951   iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
   98952   if( iDb<0 ) return;
   98953   pDb = &db->aDb[iDb];
   98954 
   98955   /* If the temp database has been explicitly named as part of the
   98956   ** pragma, make sure it is open.
   98957   */
   98958   if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
   98959     return;
   98960   }
   98961 
   98962   zLeft = sqlite3NameFromToken(db, pId);
   98963   if( !zLeft ) return;
   98964   if( minusFlag ){
   98965     zRight = sqlite3MPrintf(db, "-%T", pValue);
   98966   }else{
   98967     zRight = sqlite3NameFromToken(db, pValue);
   98968   }
   98969 
   98970   assert( pId2 );
   98971   zDb = pId2->n>0 ? pDb->zName : 0;
   98972   if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
   98973     goto pragma_out;
   98974   }
   98975 
   98976   /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
   98977   ** connection.  If it returns SQLITE_OK, then assume that the VFS
   98978   ** handled the pragma and generate a no-op prepared statement.
   98979   */
   98980   aFcntl[0] = 0;
   98981   aFcntl[1] = zLeft;
   98982   aFcntl[2] = zRight;
   98983   aFcntl[3] = 0;
   98984   db->busyHandler.nBusy = 0;
   98985   rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
   98986   if( rc==SQLITE_OK ){
   98987     if( aFcntl[0] ){
   98988       int mem = ++pParse->nMem;
   98989       sqlite3VdbeAddOp4(v, OP_String8, 0, mem, 0, aFcntl[0], 0);
   98990       sqlite3VdbeSetNumCols(v, 1);
   98991       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "result", SQLITE_STATIC);
   98992       sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
   98993       sqlite3_free(aFcntl[0]);
   98994     }
   98995     goto pragma_out;
   98996   }
   98997   if( rc!=SQLITE_NOTFOUND ){
   98998     if( aFcntl[0] ){
   98999       sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
   99000       sqlite3_free(aFcntl[0]);
   99001     }
   99002     pParse->nErr++;
   99003     pParse->rc = rc;
   99004     goto pragma_out;
   99005   }
   99006 
   99007   /* Locate the pragma in the lookup table */
   99008   lwr = 0;
   99009   upr = ArraySize(aPragmaNames)-1;
   99010   while( lwr<=upr ){
   99011     mid = (lwr+upr)/2;
   99012     rc = sqlite3_stricmp(zLeft, aPragmaNames[mid].zName);
   99013     if( rc==0 ) break;
   99014     if( rc<0 ){
   99015       upr = mid - 1;
   99016     }else{
   99017       lwr = mid + 1;
   99018     }
   99019   }
   99020   if( lwr>upr ) goto pragma_out;
   99021 
   99022   /* Make sure the database schema is loaded if the pragma requires that */
   99023   if( (aPragmaNames[mid].mPragFlag & PragFlag_NeedSchema)!=0 ){
   99024     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   99025   }
   99026 
   99027   /* Jump to the appropriate pragma handler */
   99028   switch( aPragmaNames[mid].ePragTyp ){
   99029 
   99030 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
   99031   /*
   99032   **  PRAGMA [database.]default_cache_size
   99033   **  PRAGMA [database.]default_cache_size=N
   99034   **
   99035   ** The first form reports the current persistent setting for the
   99036   ** page cache size.  The value returned is the maximum number of
   99037   ** pages in the page cache.  The second form sets both the current
   99038   ** page cache size value and the persistent page cache size value
   99039   ** stored in the database file.
   99040   **
   99041   ** Older versions of SQLite would set the default cache size to a
   99042   ** negative number to indicate synchronous=OFF.  These days, synchronous
   99043   ** is always on by default regardless of the sign of the default cache
   99044   ** size.  But continue to take the absolute value of the default cache
   99045   ** size of historical compatibility.
   99046   */
   99047   case PragTyp_DEFAULT_CACHE_SIZE: {
   99048     static const int iLn = VDBE_OFFSET_LINENO(2);
   99049     static const VdbeOpList getCacheSize[] = {
   99050       { OP_Transaction, 0, 0,        0},                         /* 0 */
   99051       { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
   99052       { OP_IfPos,       1, 8,        0},
   99053       { OP_Integer,     0, 2,        0},
   99054       { OP_Subtract,    1, 2,        1},
   99055       { OP_IfPos,       1, 8,        0},
   99056       { OP_Integer,     0, 1,        0},                         /* 6 */
   99057       { OP_Noop,        0, 0,        0},
   99058       { OP_ResultRow,   1, 1,        0},
   99059     };
   99060     int addr;
   99061     sqlite3VdbeUsesBtree(v, iDb);
   99062     if( !zRight ){
   99063       sqlite3VdbeSetNumCols(v, 1);
   99064       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
   99065       pParse->nMem += 2;
   99066       addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize,iLn);
   99067       sqlite3VdbeChangeP1(v, addr, iDb);
   99068       sqlite3VdbeChangeP1(v, addr+1, iDb);
   99069       sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
   99070     }else{
   99071       int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
   99072       sqlite3BeginWriteOperation(pParse, 0, iDb);
   99073       sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
   99074       sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
   99075       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   99076       pDb->pSchema->cache_size = size;
   99077       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
   99078     }
   99079     break;
   99080   }
   99081 #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
   99082 
   99083 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
   99084   /*
   99085   **  PRAGMA [database.]page_size
   99086   **  PRAGMA [database.]page_size=N
   99087   **
   99088   ** The first form reports the current setting for the
   99089   ** database page size in bytes.  The second form sets the
   99090   ** database page size value.  The value can only be set if
   99091   ** the database has not yet been created.
   99092   */
   99093   case PragTyp_PAGE_SIZE: {
   99094     Btree *pBt = pDb->pBt;
   99095     assert( pBt!=0 );
   99096     if( !zRight ){
   99097       int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
   99098       returnSingleInt(pParse, "page_size", size);
   99099     }else{
   99100       /* Malloc may fail when setting the page-size, as there is an internal
   99101       ** buffer that the pager module resizes using sqlite3_realloc().
   99102       */
   99103       db->nextPagesize = sqlite3Atoi(zRight);
   99104       if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
   99105         db->mallocFailed = 1;
   99106       }
   99107     }
   99108     break;
   99109   }
   99110 
   99111   /*
   99112   **  PRAGMA [database.]secure_delete
   99113   **  PRAGMA [database.]secure_delete=ON/OFF
   99114   **
   99115   ** The first form reports the current setting for the
   99116   ** secure_delete flag.  The second form changes the secure_delete
   99117   ** flag setting and reports thenew value.
   99118   */
   99119   case PragTyp_SECURE_DELETE: {
   99120     Btree *pBt = pDb->pBt;
   99121     int b = -1;
   99122     assert( pBt!=0 );
   99123     if( zRight ){
   99124       b = sqlite3GetBoolean(zRight, 0);
   99125     }
   99126     if( pId2->n==0 && b>=0 ){
   99127       int ii;
   99128       for(ii=0; ii<db->nDb; ii++){
   99129         sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
   99130       }
   99131     }
   99132     b = sqlite3BtreeSecureDelete(pBt, b);
   99133     returnSingleInt(pParse, "secure_delete", b);
   99134     break;
   99135   }
   99136 
   99137   /*
   99138   **  PRAGMA [database.]max_page_count
   99139   **  PRAGMA [database.]max_page_count=N
   99140   **
   99141   ** The first form reports the current setting for the
   99142   ** maximum number of pages in the database file.  The
   99143   ** second form attempts to change this setting.  Both
   99144   ** forms return the current setting.
   99145   **
   99146   ** The absolute value of N is used.  This is undocumented and might
   99147   ** change.  The only purpose is to provide an easy way to test
   99148   ** the sqlite3AbsInt32() function.
   99149   **
   99150   **  PRAGMA [database.]page_count
   99151   **
   99152   ** Return the number of pages in the specified database.
   99153   */
   99154   case PragTyp_PAGE_COUNT: {
   99155     int iReg;
   99156     sqlite3CodeVerifySchema(pParse, iDb);
   99157     iReg = ++pParse->nMem;
   99158     if( sqlite3Tolower(zLeft[0])=='p' ){
   99159       sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
   99160     }else{
   99161       sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
   99162                         sqlite3AbsInt32(sqlite3Atoi(zRight)));
   99163     }
   99164     sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
   99165     sqlite3VdbeSetNumCols(v, 1);
   99166     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
   99167     break;
   99168   }
   99169 
   99170   /*
   99171   **  PRAGMA [database.]locking_mode
   99172   **  PRAGMA [database.]locking_mode = (normal|exclusive)
   99173   */
   99174   case PragTyp_LOCKING_MODE: {
   99175     const char *zRet = "normal";
   99176     int eMode = getLockingMode(zRight);
   99177 
   99178     if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
   99179       /* Simple "PRAGMA locking_mode;" statement. This is a query for
   99180       ** the current default locking mode (which may be different to
   99181       ** the locking-mode of the main database).
   99182       */
   99183       eMode = db->dfltLockMode;
   99184     }else{
   99185       Pager *pPager;
   99186       if( pId2->n==0 ){
   99187         /* This indicates that no database name was specified as part
   99188         ** of the PRAGMA command. In this case the locking-mode must be
   99189         ** set on all attached databases, as well as the main db file.
   99190         **
   99191         ** Also, the sqlite3.dfltLockMode variable is set so that
   99192         ** any subsequently attached databases also use the specified
   99193         ** locking mode.
   99194         */
   99195         int ii;
   99196         assert(pDb==&db->aDb[0]);
   99197         for(ii=2; ii<db->nDb; ii++){
   99198           pPager = sqlite3BtreePager(db->aDb[ii].pBt);
   99199           sqlite3PagerLockingMode(pPager, eMode);
   99200         }
   99201         db->dfltLockMode = (u8)eMode;
   99202       }
   99203       pPager = sqlite3BtreePager(pDb->pBt);
   99204       eMode = sqlite3PagerLockingMode(pPager, eMode);
   99205     }
   99206 
   99207     assert( eMode==PAGER_LOCKINGMODE_NORMAL
   99208             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
   99209     if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
   99210       zRet = "exclusive";
   99211     }
   99212     sqlite3VdbeSetNumCols(v, 1);
   99213     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
   99214     sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
   99215     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
   99216     break;
   99217   }
   99218 
   99219   /*
   99220   **  PRAGMA [database.]journal_mode
   99221   **  PRAGMA [database.]journal_mode =
   99222   **                      (delete|persist|off|truncate|memory|wal|off)
   99223   */
   99224   case PragTyp_JOURNAL_MODE: {
   99225     int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
   99226     int ii;           /* Loop counter */
   99227 
   99228     sqlite3VdbeSetNumCols(v, 1);
   99229     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
   99230 
   99231     if( zRight==0 ){
   99232       /* If there is no "=MODE" part of the pragma, do a query for the
   99233       ** current mode */
   99234       eMode = PAGER_JOURNALMODE_QUERY;
   99235     }else{
   99236       const char *zMode;
   99237       int n = sqlite3Strlen30(zRight);
   99238       for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
   99239         if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
   99240       }
   99241       if( !zMode ){
   99242         /* If the "=MODE" part does not match any known journal mode,
   99243         ** then do a query */
   99244         eMode = PAGER_JOURNALMODE_QUERY;
   99245       }
   99246     }
   99247     if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
   99248       /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
   99249       iDb = 0;
   99250       pId2->n = 1;
   99251     }
   99252     for(ii=db->nDb-1; ii>=0; ii--){
   99253       if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
   99254         sqlite3VdbeUsesBtree(v, ii);
   99255         sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
   99256       }
   99257     }
   99258     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
   99259     break;
   99260   }
   99261 
   99262   /*
   99263   **  PRAGMA [database.]journal_size_limit
   99264   **  PRAGMA [database.]journal_size_limit=N
   99265   **
   99266   ** Get or set the size limit on rollback journal files.
   99267   */
   99268   case PragTyp_JOURNAL_SIZE_LIMIT: {
   99269     Pager *pPager = sqlite3BtreePager(pDb->pBt);
   99270     i64 iLimit = -2;
   99271     if( zRight ){
   99272       sqlite3DecOrHexToI64(zRight, &iLimit);
   99273       if( iLimit<-1 ) iLimit = -1;
   99274     }
   99275     iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
   99276     returnSingleInt(pParse, "journal_size_limit", iLimit);
   99277     break;
   99278   }
   99279 
   99280 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
   99281 
   99282   /*
   99283   **  PRAGMA [database.]auto_vacuum
   99284   **  PRAGMA [database.]auto_vacuum=N
   99285   **
   99286   ** Get or set the value of the database 'auto-vacuum' parameter.
   99287   ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
   99288   */
   99289 #ifndef SQLITE_OMIT_AUTOVACUUM
   99290   case PragTyp_AUTO_VACUUM: {
   99291     Btree *pBt = pDb->pBt;
   99292     assert( pBt!=0 );
   99293     if( !zRight ){
   99294       returnSingleInt(pParse, "auto_vacuum", sqlite3BtreeGetAutoVacuum(pBt));
   99295     }else{
   99296       int eAuto = getAutoVacuum(zRight);
   99297       assert( eAuto>=0 && eAuto<=2 );
   99298       db->nextAutovac = (u8)eAuto;
   99299       /* Call SetAutoVacuum() to set initialize the internal auto and
   99300       ** incr-vacuum flags. This is required in case this connection
   99301       ** creates the database file. It is important that it is created
   99302       ** as an auto-vacuum capable db.
   99303       */
   99304       rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
   99305       if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
   99306         /* When setting the auto_vacuum mode to either "full" or
   99307         ** "incremental", write the value of meta[6] in the database
   99308         ** file. Before writing to meta[6], check that meta[3] indicates
   99309         ** that this really is an auto-vacuum capable database.
   99310         */
   99311         static const int iLn = VDBE_OFFSET_LINENO(2);
   99312         static const VdbeOpList setMeta6[] = {
   99313           { OP_Transaction,    0,         1,                 0},    /* 0 */
   99314           { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
   99315           { OP_If,             1,         0,                 0},    /* 2 */
   99316           { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
   99317           { OP_Integer,        0,         1,                 0},    /* 4 */
   99318           { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
   99319         };
   99320         int iAddr;
   99321         iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
   99322         sqlite3VdbeChangeP1(v, iAddr, iDb);
   99323         sqlite3VdbeChangeP1(v, iAddr+1, iDb);
   99324         sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
   99325         sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
   99326         sqlite3VdbeChangeP1(v, iAddr+5, iDb);
   99327         sqlite3VdbeUsesBtree(v, iDb);
   99328       }
   99329     }
   99330     break;
   99331   }
   99332 #endif
   99333 
   99334   /*
   99335   **  PRAGMA [database.]incremental_vacuum(N)
   99336   **
   99337   ** Do N steps of incremental vacuuming on a database.
   99338   */
   99339 #ifndef SQLITE_OMIT_AUTOVACUUM
   99340   case PragTyp_INCREMENTAL_VACUUM: {
   99341     int iLimit, addr;
   99342     if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
   99343       iLimit = 0x7fffffff;
   99344     }
   99345     sqlite3BeginWriteOperation(pParse, 0, iDb);
   99346     sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
   99347     addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
   99348     sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
   99349     sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
   99350     sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
   99351     sqlite3VdbeJumpHere(v, addr);
   99352     break;
   99353   }
   99354 #endif
   99355 
   99356 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   99357   /*
   99358   **  PRAGMA [database.]cache_size
   99359   **  PRAGMA [database.]cache_size=N
   99360   **
   99361   ** The first form reports the current local setting for the
   99362   ** page cache size. The second form sets the local
   99363   ** page cache size value.  If N is positive then that is the
   99364   ** number of pages in the cache.  If N is negative, then the
   99365   ** number of pages is adjusted so that the cache uses -N kibibytes
   99366   ** of memory.
   99367   */
   99368   case PragTyp_CACHE_SIZE: {
   99369     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   99370     if( !zRight ){
   99371       returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
   99372     }else{
   99373       int size = sqlite3Atoi(zRight);
   99374       pDb->pSchema->cache_size = size;
   99375       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
   99376     }
   99377     break;
   99378   }
   99379 
   99380   /*
   99381   **  PRAGMA [database.]mmap_size(N)
   99382   **
   99383   ** Used to set mapping size limit. The mapping size limit is
   99384   ** used to limit the aggregate size of all memory mapped regions of the
   99385   ** database file. If this parameter is set to zero, then memory mapping
   99386   ** is not used at all.  If N is negative, then the default memory map
   99387   ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
   99388   ** The parameter N is measured in bytes.
   99389   **
   99390   ** This value is advisory.  The underlying VFS is free to memory map
   99391   ** as little or as much as it wants.  Except, if N is set to 0 then the
   99392   ** upper layers will never invoke the xFetch interfaces to the VFS.
   99393   */
   99394   case PragTyp_MMAP_SIZE: {
   99395     sqlite3_int64 sz;
   99396 #if SQLITE_MAX_MMAP_SIZE>0
   99397     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   99398     if( zRight ){
   99399       int ii;
   99400       sqlite3DecOrHexToI64(zRight, &sz);
   99401       if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
   99402       if( pId2->n==0 ) db->szMmap = sz;
   99403       for(ii=db->nDb-1; ii>=0; ii--){
   99404         if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
   99405           sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
   99406         }
   99407       }
   99408     }
   99409     sz = -1;
   99410     rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
   99411 #else
   99412     sz = 0;
   99413     rc = SQLITE_OK;
   99414 #endif
   99415     if( rc==SQLITE_OK ){
   99416       returnSingleInt(pParse, "mmap_size", sz);
   99417     }else if( rc!=SQLITE_NOTFOUND ){
   99418       pParse->nErr++;
   99419       pParse->rc = rc;
   99420     }
   99421     break;
   99422   }
   99423 
   99424   /*
   99425   **   PRAGMA temp_store
   99426   **   PRAGMA temp_store = "default"|"memory"|"file"
   99427   **
   99428   ** Return or set the local value of the temp_store flag.  Changing
   99429   ** the local value does not make changes to the disk file and the default
   99430   ** value will be restored the next time the database is opened.
   99431   **
   99432   ** Note that it is possible for the library compile-time options to
   99433   ** override this setting
   99434   */
   99435   case PragTyp_TEMP_STORE: {
   99436     if( !zRight ){
   99437       returnSingleInt(pParse, "temp_store", db->temp_store);
   99438     }else{
   99439       changeTempStorage(pParse, zRight);
   99440     }
   99441     break;
   99442   }
   99443 
   99444   /*
   99445   **   PRAGMA temp_store_directory
   99446   **   PRAGMA temp_store_directory = ""|"directory_name"
   99447   **
   99448   ** Return or set the local value of the temp_store_directory flag.  Changing
   99449   ** the value sets a specific directory to be used for temporary files.
   99450   ** Setting to a null string reverts to the default temporary directory search.
   99451   ** If temporary directory is changed, then invalidateTempStorage.
   99452   **
   99453   */
   99454   case PragTyp_TEMP_STORE_DIRECTORY: {
   99455     if( !zRight ){
   99456       if( sqlite3_temp_directory ){
   99457         sqlite3VdbeSetNumCols(v, 1);
   99458         sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
   99459             "temp_store_directory", SQLITE_STATIC);
   99460         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
   99461         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
   99462       }
   99463     }else{
   99464 #ifndef SQLITE_OMIT_WSD
   99465       if( zRight[0] ){
   99466         int res;
   99467         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
   99468         if( rc!=SQLITE_OK || res==0 ){
   99469           sqlite3ErrorMsg(pParse, "not a writable directory");
   99470           goto pragma_out;
   99471         }
   99472       }
   99473       if( SQLITE_TEMP_STORE==0
   99474        || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
   99475        || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
   99476       ){
   99477         invalidateTempStorage(pParse);
   99478       }
   99479       sqlite3_free(sqlite3_temp_directory);
   99480       if( zRight[0] ){
   99481         sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
   99482       }else{
   99483         sqlite3_temp_directory = 0;
   99484       }
   99485 #endif /* SQLITE_OMIT_WSD */
   99486     }
   99487     break;
   99488   }
   99489 
   99490 #if SQLITE_OS_WIN
   99491   /*
   99492   **   PRAGMA data_store_directory
   99493   **   PRAGMA data_store_directory = ""|"directory_name"
   99494   **
   99495   ** Return or set the local value of the data_store_directory flag.  Changing
   99496   ** the value sets a specific directory to be used for database files that
   99497   ** were specified with a relative pathname.  Setting to a null string reverts
   99498   ** to the default database directory, which for database files specified with
   99499   ** a relative path will probably be based on the current directory for the
   99500   ** process.  Database file specified with an absolute path are not impacted
   99501   ** by this setting, regardless of its value.
   99502   **
   99503   */
   99504   case PragTyp_DATA_STORE_DIRECTORY: {
   99505     if( !zRight ){
   99506       if( sqlite3_data_directory ){
   99507         sqlite3VdbeSetNumCols(v, 1);
   99508         sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
   99509             "data_store_directory", SQLITE_STATIC);
   99510         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_data_directory, 0);
   99511         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
   99512       }
   99513     }else{
   99514 #ifndef SQLITE_OMIT_WSD
   99515       if( zRight[0] ){
   99516         int res;
   99517         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
   99518         if( rc!=SQLITE_OK || res==0 ){
   99519           sqlite3ErrorMsg(pParse, "not a writable directory");
   99520           goto pragma_out;
   99521         }
   99522       }
   99523       sqlite3_free(sqlite3_data_directory);
   99524       if( zRight[0] ){
   99525         sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
   99526       }else{
   99527         sqlite3_data_directory = 0;
   99528       }
   99529 #endif /* SQLITE_OMIT_WSD */
   99530     }
   99531     break;
   99532   }
   99533 #endif
   99534 
   99535 #if SQLITE_ENABLE_LOCKING_STYLE
   99536   /*
   99537   **   PRAGMA [database.]lock_proxy_file
   99538   **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
   99539   **
   99540   ** Return or set the value of the lock_proxy_file flag.  Changing
   99541   ** the value sets a specific file to be used for database access locks.
   99542   **
   99543   */
   99544   case PragTyp_LOCK_PROXY_FILE: {
   99545     if( !zRight ){
   99546       Pager *pPager = sqlite3BtreePager(pDb->pBt);
   99547       char *proxy_file_path = NULL;
   99548       sqlite3_file *pFile = sqlite3PagerFile(pPager);
   99549       sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
   99550                            &proxy_file_path);
   99551 
   99552       if( proxy_file_path ){
   99553         sqlite3VdbeSetNumCols(v, 1);
   99554         sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
   99555                               "lock_proxy_file", SQLITE_STATIC);
   99556         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
   99557         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
   99558       }
   99559     }else{
   99560       Pager *pPager = sqlite3BtreePager(pDb->pBt);
   99561       sqlite3_file *pFile = sqlite3PagerFile(pPager);
   99562       int res;
   99563       if( zRight[0] ){
   99564         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
   99565                                      zRight);
   99566       } else {
   99567         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
   99568                                      NULL);
   99569       }
   99570       if( res!=SQLITE_OK ){
   99571         sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
   99572         goto pragma_out;
   99573       }
   99574     }
   99575     break;
   99576   }
   99577 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
   99578 
   99579   /*
   99580   **   PRAGMA [database.]synchronous
   99581   **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
   99582   **
   99583   ** Return or set the local value of the synchronous flag.  Changing
   99584   ** the local value does not make changes to the disk file and the
   99585   ** default value will be restored the next time the database is
   99586   ** opened.
   99587   */
   99588   case PragTyp_SYNCHRONOUS: {
   99589     if( !zRight ){
   99590       returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
   99591     }else{
   99592       if( !db->autoCommit ){
   99593         sqlite3ErrorMsg(pParse,
   99594             "Safety level may not be changed inside a transaction");
   99595       }else{
   99596         pDb->safety_level = getSafetyLevel(zRight,0,1)+1;
   99597         setAllPagerFlags(db);
   99598       }
   99599     }
   99600     break;
   99601   }
   99602 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
   99603 
   99604 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
   99605   case PragTyp_FLAG: {
   99606     if( zRight==0 ){
   99607       returnSingleInt(pParse, aPragmaNames[mid].zName,
   99608                      (db->flags & aPragmaNames[mid].iArg)!=0 );
   99609     }else{
   99610       int mask = aPragmaNames[mid].iArg;    /* Mask of bits to set or clear. */
   99611       if( db->autoCommit==0 ){
   99612         /* Foreign key support may not be enabled or disabled while not
   99613         ** in auto-commit mode.  */
   99614         mask &= ~(SQLITE_ForeignKeys);
   99615       }
   99616 
   99617       if( sqlite3GetBoolean(zRight, 0) ){
   99618         db->flags |= mask;
   99619       }else{
   99620         db->flags &= ~mask;
   99621         if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
   99622       }
   99623 
   99624       /* Many of the flag-pragmas modify the code generated by the SQL
   99625       ** compiler (eg. count_changes). So add an opcode to expire all
   99626       ** compiled SQL statements after modifying a pragma value.
   99627       */
   99628       sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
   99629       setAllPagerFlags(db);
   99630     }
   99631     break;
   99632   }
   99633 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
   99634 
   99635 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
   99636   /*
   99637   **   PRAGMA table_info(<table>)
   99638   **
   99639   ** Return a single row for each column of the named table. The columns of
   99640   ** the returned data set are:
   99641   **
   99642   ** cid:        Column id (numbered from left to right, starting at 0)
   99643   ** name:       Column name
   99644   ** type:       Column declaration type.
   99645   ** notnull:    True if 'NOT NULL' is part of column declaration
   99646   ** dflt_value: The default value for the column, if any.
   99647   */
   99648   case PragTyp_TABLE_INFO: if( zRight ){
   99649     Table *pTab;
   99650     pTab = sqlite3FindTable(db, zRight, zDb);
   99651     if( pTab ){
   99652       int i, k;
   99653       int nHidden = 0;
   99654       Column *pCol;
   99655       Index *pPk = sqlite3PrimaryKeyIndex(pTab);
   99656       sqlite3VdbeSetNumCols(v, 6);
   99657       pParse->nMem = 6;
   99658       sqlite3CodeVerifySchema(pParse, iDb);
   99659       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
   99660       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
   99661       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
   99662       sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
   99663       sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
   99664       sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
   99665       sqlite3ViewGetColumnNames(pParse, pTab);
   99666       for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
   99667         if( IsHiddenColumn(pCol) ){
   99668           nHidden++;
   99669           continue;
   99670         }
   99671         sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
   99672         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
   99673         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
   99674            pCol->zType ? pCol->zType : "", 0);
   99675         sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
   99676         if( pCol->zDflt ){
   99677           sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
   99678         }else{
   99679           sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
   99680         }
   99681         if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
   99682           k = 0;
   99683         }else if( pPk==0 ){
   99684           k = 1;
   99685         }else{
   99686           for(k=1; ALWAYS(k<=pTab->nCol) && pPk->aiColumn[k-1]!=i; k++){}
   99687         }
   99688         sqlite3VdbeAddOp2(v, OP_Integer, k, 6);
   99689         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
   99690       }
   99691     }
   99692   }
   99693   break;
   99694 
   99695   case PragTyp_STATS: {
   99696     Index *pIdx;
   99697     HashElem *i;
   99698     v = sqlite3GetVdbe(pParse);
   99699     sqlite3VdbeSetNumCols(v, 4);
   99700     pParse->nMem = 4;
   99701     sqlite3CodeVerifySchema(pParse, iDb);
   99702     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
   99703     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "index", SQLITE_STATIC);
   99704     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "width", SQLITE_STATIC);
   99705     sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "height", SQLITE_STATIC);
   99706     for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
   99707       Table *pTab = sqliteHashData(i);
   99708       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, pTab->zName, 0);
   99709       sqlite3VdbeAddOp2(v, OP_Null, 0, 2);
   99710       sqlite3VdbeAddOp2(v, OP_Integer,
   99711                            (int)sqlite3LogEstToInt(pTab->szTabRow), 3);
   99712       sqlite3VdbeAddOp2(v, OP_Integer,
   99713           (int)sqlite3LogEstToInt(pTab->nRowLogEst), 4);
   99714       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
   99715       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   99716         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
   99717         sqlite3VdbeAddOp2(v, OP_Integer,
   99718                              (int)sqlite3LogEstToInt(pIdx->szIdxRow), 3);
   99719         sqlite3VdbeAddOp2(v, OP_Integer,
   99720             (int)sqlite3LogEstToInt(pIdx->aiRowLogEst[0]), 4);
   99721         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
   99722       }
   99723     }
   99724   }
   99725   break;
   99726 
   99727   case PragTyp_INDEX_INFO: if( zRight ){
   99728     Index *pIdx;
   99729     Table *pTab;
   99730     pIdx = sqlite3FindIndex(db, zRight, zDb);
   99731     if( pIdx ){
   99732       int i;
   99733       pTab = pIdx->pTable;
   99734       sqlite3VdbeSetNumCols(v, 3);
   99735       pParse->nMem = 3;
   99736       sqlite3CodeVerifySchema(pParse, iDb);
   99737       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
   99738       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
   99739       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
   99740       for(i=0; i<pIdx->nKeyCol; i++){
   99741         i16 cnum = pIdx->aiColumn[i];
   99742         sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
   99743         sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
   99744         assert( pTab->nCol>cnum );
   99745         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
   99746         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
   99747       }
   99748     }
   99749   }
   99750   break;
   99751 
   99752   case PragTyp_INDEX_LIST: if( zRight ){
   99753     Index *pIdx;
   99754     Table *pTab;
   99755     int i;
   99756     pTab = sqlite3FindTable(db, zRight, zDb);
   99757     if( pTab ){
   99758       v = sqlite3GetVdbe(pParse);
   99759       sqlite3VdbeSetNumCols(v, 3);
   99760       pParse->nMem = 3;
   99761       sqlite3CodeVerifySchema(pParse, iDb);
   99762       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
   99763       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
   99764       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
   99765       for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
   99766         sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
   99767         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
   99768         sqlite3VdbeAddOp2(v, OP_Integer, IsUniqueIndex(pIdx), 3);
   99769         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
   99770       }
   99771     }
   99772   }
   99773   break;
   99774 
   99775   case PragTyp_DATABASE_LIST: {
   99776     int i;
   99777     sqlite3VdbeSetNumCols(v, 3);
   99778     pParse->nMem = 3;
   99779     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
   99780     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
   99781     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
   99782     for(i=0; i<db->nDb; i++){
   99783       if( db->aDb[i].pBt==0 ) continue;
   99784       assert( db->aDb[i].zName!=0 );
   99785       sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
   99786       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
   99787       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
   99788            sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
   99789       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
   99790     }
   99791   }
   99792   break;
   99793 
   99794   case PragTyp_COLLATION_LIST: {
   99795     int i = 0;
   99796     HashElem *p;
   99797     sqlite3VdbeSetNumCols(v, 2);
   99798     pParse->nMem = 2;
   99799     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
   99800     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
   99801     for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
   99802       CollSeq *pColl = (CollSeq *)sqliteHashData(p);
   99803       sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
   99804       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
   99805       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
   99806     }
   99807   }
   99808   break;
   99809 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
   99810 
   99811 #ifndef SQLITE_OMIT_FOREIGN_KEY
   99812   case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
   99813     FKey *pFK;
   99814     Table *pTab;
   99815     pTab = sqlite3FindTable(db, zRight, zDb);
   99816     if( pTab ){
   99817       v = sqlite3GetVdbe(pParse);
   99818       pFK = pTab->pFKey;
   99819       if( pFK ){
   99820         int i = 0;
   99821         sqlite3VdbeSetNumCols(v, 8);
   99822         pParse->nMem = 8;
   99823         sqlite3CodeVerifySchema(pParse, iDb);
   99824         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
   99825         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
   99826         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
   99827         sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
   99828         sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
   99829         sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
   99830         sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
   99831         sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
   99832         while(pFK){
   99833           int j;
   99834           for(j=0; j<pFK->nCol; j++){
   99835             char *zCol = pFK->aCol[j].zCol;
   99836             char *zOnDelete = (char *)actionName(pFK->aAction[0]);
   99837             char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
   99838             sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
   99839             sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
   99840             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
   99841             sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
   99842                               pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
   99843             sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
   99844             sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
   99845             sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
   99846             sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
   99847             sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
   99848           }
   99849           ++i;
   99850           pFK = pFK->pNextFrom;
   99851         }
   99852       }
   99853     }
   99854   }
   99855   break;
   99856 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
   99857 
   99858 #ifndef SQLITE_OMIT_FOREIGN_KEY
   99859 #ifndef SQLITE_OMIT_TRIGGER
   99860   case PragTyp_FOREIGN_KEY_CHECK: {
   99861     FKey *pFK;             /* A foreign key constraint */
   99862     Table *pTab;           /* Child table contain "REFERENCES" keyword */
   99863     Table *pParent;        /* Parent table that child points to */
   99864     Index *pIdx;           /* Index in the parent table */
   99865     int i;                 /* Loop counter:  Foreign key number for pTab */
   99866     int j;                 /* Loop counter:  Field of the foreign key */
   99867     HashElem *k;           /* Loop counter:  Next table in schema */
   99868     int x;                 /* result variable */
   99869     int regResult;         /* 3 registers to hold a result row */
   99870     int regKey;            /* Register to hold key for checking the FK */
   99871     int regRow;            /* Registers to hold a row from pTab */
   99872     int addrTop;           /* Top of a loop checking foreign keys */
   99873     int addrOk;            /* Jump here if the key is OK */
   99874     int *aiCols;           /* child to parent column mapping */
   99875 
   99876     regResult = pParse->nMem+1;
   99877     pParse->nMem += 4;
   99878     regKey = ++pParse->nMem;
   99879     regRow = ++pParse->nMem;
   99880     v = sqlite3GetVdbe(pParse);
   99881     sqlite3VdbeSetNumCols(v, 4);
   99882     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
   99883     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "rowid", SQLITE_STATIC);
   99884     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "parent", SQLITE_STATIC);
   99885     sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "fkid", SQLITE_STATIC);
   99886     sqlite3CodeVerifySchema(pParse, iDb);
   99887     k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
   99888     while( k ){
   99889       if( zRight ){
   99890         pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
   99891         k = 0;
   99892       }else{
   99893         pTab = (Table*)sqliteHashData(k);
   99894         k = sqliteHashNext(k);
   99895       }
   99896       if( pTab==0 || pTab->pFKey==0 ) continue;
   99897       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
   99898       if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
   99899       sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
   99900       sqlite3VdbeAddOp4(v, OP_String8, 0, regResult, 0, pTab->zName,
   99901                         P4_TRANSIENT);
   99902       for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
   99903         pParent = sqlite3FindTable(db, pFK->zTo, zDb);
   99904         if( pParent==0 ) continue;
   99905         pIdx = 0;
   99906         sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
   99907         x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
   99908         if( x==0 ){
   99909           if( pIdx==0 ){
   99910             sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
   99911           }else{
   99912             sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
   99913             sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
   99914           }
   99915         }else{
   99916           k = 0;
   99917           break;
   99918         }
   99919       }
   99920       assert( pParse->nErr>0 || pFK==0 );
   99921       if( pFK ) break;
   99922       if( pParse->nTab<i ) pParse->nTab = i;
   99923       addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
   99924       for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
   99925         pParent = sqlite3FindTable(db, pFK->zTo, zDb);
   99926         pIdx = 0;
   99927         aiCols = 0;
   99928         if( pParent ){
   99929           x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
   99930           assert( x==0 );
   99931         }
   99932         addrOk = sqlite3VdbeMakeLabel(v);
   99933         if( pParent && pIdx==0 ){
   99934           int iKey = pFK->aCol[0].iFrom;
   99935           assert( iKey>=0 && iKey<pTab->nCol );
   99936           if( iKey!=pTab->iPKey ){
   99937             sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow);
   99938             sqlite3ColumnDefault(v, pTab, iKey, regRow);
   99939             sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk); VdbeCoverage(v);
   99940             sqlite3VdbeAddOp2(v, OP_MustBeInt, regRow,
   99941                sqlite3VdbeCurrentAddr(v)+3); VdbeCoverage(v);
   99942           }else{
   99943             sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow);
   99944           }
   99945           sqlite3VdbeAddOp3(v, OP_NotExists, i, 0, regRow); VdbeCoverage(v);
   99946           sqlite3VdbeAddOp2(v, OP_Goto, 0, addrOk);
   99947           sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
   99948         }else{
   99949           for(j=0; j<pFK->nCol; j++){
   99950             sqlite3ExprCodeGetColumnOfTable(v, pTab, 0,
   99951                             aiCols ? aiCols[j] : pFK->aCol[j].iFrom, regRow+j);
   99952             sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
   99953           }
   99954           if( pParent ){
   99955             sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
   99956                               sqlite3IndexAffinityStr(v,pIdx), pFK->nCol);
   99957             sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
   99958             VdbeCoverage(v);
   99959           }
   99960         }
   99961         sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
   99962         sqlite3VdbeAddOp4(v, OP_String8, 0, regResult+2, 0,
   99963                           pFK->zTo, P4_TRANSIENT);
   99964         sqlite3VdbeAddOp2(v, OP_Integer, i-1, regResult+3);
   99965         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
   99966         sqlite3VdbeResolveLabel(v, addrOk);
   99967         sqlite3DbFree(db, aiCols);
   99968       }
   99969       sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
   99970       sqlite3VdbeJumpHere(v, addrTop);
   99971     }
   99972   }
   99973   break;
   99974 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
   99975 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
   99976 
   99977 #ifndef NDEBUG
   99978   case PragTyp_PARSER_TRACE: {
   99979     if( zRight ){
   99980       if( sqlite3GetBoolean(zRight, 0) ){
   99981         sqlite3ParserTrace(stderr, "parser: ");
   99982       }else{
   99983         sqlite3ParserTrace(0, 0);
   99984       }
   99985     }
   99986   }
   99987   break;
   99988 #endif
   99989 
   99990   /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
   99991   ** used will be case sensitive or not depending on the RHS.
   99992   */
   99993   case PragTyp_CASE_SENSITIVE_LIKE: {
   99994     if( zRight ){
   99995       sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
   99996     }
   99997   }
   99998   break;
   99999 
   100000 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
   100001 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
   100002 #endif
   100003 
   100004 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
   100005   /* Pragma "quick_check" is reduced version of
   100006   ** integrity_check designed to detect most database corruption
   100007   ** without most of the overhead of a full integrity-check.
   100008   */
   100009   case PragTyp_INTEGRITY_CHECK: {
   100010     int i, j, addr, mxErr;
   100011 
   100012     /* Code that appears at the end of the integrity check.  If no error
   100013     ** messages have been generated, output OK.  Otherwise output the
   100014     ** error message
   100015     */
   100016     static const int iLn = VDBE_OFFSET_LINENO(2);
   100017     static const VdbeOpList endCode[] = {
   100018       { OP_IfNeg,       1, 0,        0},    /* 0 */
   100019       { OP_String8,     0, 3,        0},    /* 1 */
   100020       { OP_ResultRow,   3, 1,        0},
   100021     };
   100022 
   100023     int isQuick = (sqlite3Tolower(zLeft[0])=='q');
   100024 
   100025     /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
   100026     ** then iDb is set to the index of the database identified by <db>.
   100027     ** In this case, the integrity of database iDb only is verified by
   100028     ** the VDBE created below.
   100029     **
   100030     ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
   100031     ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
   100032     ** to -1 here, to indicate that the VDBE should verify the integrity
   100033     ** of all attached databases.  */
   100034     assert( iDb>=0 );
   100035     assert( iDb==0 || pId2->z );
   100036     if( pId2->z==0 ) iDb = -1;
   100037 
   100038     /* Initialize the VDBE program */
   100039     pParse->nMem = 6;
   100040     sqlite3VdbeSetNumCols(v, 1);
   100041     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
   100042 
   100043     /* Set the maximum error count */
   100044     mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
   100045     if( zRight ){
   100046       sqlite3GetInt32(zRight, &mxErr);
   100047       if( mxErr<=0 ){
   100048         mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
   100049       }
   100050     }
   100051     sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
   100052 
   100053     /* Do an integrity check on each database file */
   100054     for(i=0; i<db->nDb; i++){
   100055       HashElem *x;
   100056       Hash *pTbls;
   100057       int cnt = 0;
   100058 
   100059       if( OMIT_TEMPDB && i==1 ) continue;
   100060       if( iDb>=0 && i!=iDb ) continue;
   100061 
   100062       sqlite3CodeVerifySchema(pParse, i);
   100063       addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
   100064       VdbeCoverage(v);
   100065       sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
   100066       sqlite3VdbeJumpHere(v, addr);
   100067 
   100068       /* Do an integrity check of the B-Tree
   100069       **
   100070       ** Begin by filling registers 2, 3, ... with the root pages numbers
   100071       ** for all tables and indices in the database.
   100072       */
   100073       assert( sqlite3SchemaMutexHeld(db, i, 0) );
   100074       pTbls = &db->aDb[i].pSchema->tblHash;
   100075       for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
   100076         Table *pTab = sqliteHashData(x);
   100077         Index *pIdx;
   100078         if( HasRowid(pTab) ){
   100079           sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
   100080           VdbeComment((v, "%s", pTab->zName));
   100081           cnt++;
   100082         }
   100083         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   100084           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
   100085           VdbeComment((v, "%s", pIdx->zName));
   100086           cnt++;
   100087         }
   100088       }
   100089 
   100090       /* Make sure sufficient number of registers have been allocated */
   100091       pParse->nMem = MAX( pParse->nMem, cnt+8 );
   100092 
   100093       /* Do the b-tree integrity checks */
   100094       sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
   100095       sqlite3VdbeChangeP5(v, (u8)i);
   100096       addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
   100097       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
   100098          sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
   100099          P4_DYNAMIC);
   100100       sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
   100101       sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
   100102       sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
   100103       sqlite3VdbeJumpHere(v, addr);
   100104 
   100105       /* Make sure all the indices are constructed correctly.
   100106       */
   100107       for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
   100108         Table *pTab = sqliteHashData(x);
   100109         Index *pIdx, *pPk;
   100110         Index *pPrior = 0;
   100111         int loopTop;
   100112         int iDataCur, iIdxCur;
   100113         int r1 = -1;
   100114 
   100115         if( pTab->pIndex==0 ) continue;
   100116         pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
   100117         addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
   100118         VdbeCoverage(v);
   100119         sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
   100120         sqlite3VdbeJumpHere(v, addr);
   100121         sqlite3ExprCacheClear(pParse);
   100122         sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead,
   100123                                    1, 0, &iDataCur, &iIdxCur);
   100124         sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
   100125         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
   100126           sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
   100127         }
   100128         pParse->nMem = MAX(pParse->nMem, 8+j);
   100129         sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
   100130         loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
   100131         /* Verify that all NOT NULL columns really are NOT NULL */
   100132         for(j=0; j<pTab->nCol; j++){
   100133           char *zErr;
   100134           int jmp2, jmp3;
   100135           if( j==pTab->iPKey ) continue;
   100136           if( pTab->aCol[j].notNull==0 ) continue;
   100137           sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
   100138           sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
   100139           jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
   100140           sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
   100141           zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
   100142                               pTab->aCol[j].zName);
   100143           sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
   100144           sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
   100145           jmp3 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
   100146           sqlite3VdbeAddOp0(v, OP_Halt);
   100147           sqlite3VdbeJumpHere(v, jmp2);
   100148           sqlite3VdbeJumpHere(v, jmp3);
   100149         }
   100150         /* Validate index entries for the current row */
   100151         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
   100152           int jmp2, jmp3, jmp4, jmp5;
   100153           int ckUniq = sqlite3VdbeMakeLabel(v);
   100154           if( pPk==pIdx ) continue;
   100155           r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
   100156                                        pPrior, r1);
   100157           pPrior = pIdx;
   100158           sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);  /* increment entry count */
   100159           /* Verify that an index entry exists for the current table row */
   100160           jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
   100161                                       pIdx->nColumn); VdbeCoverage(v);
   100162           sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
   100163           sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, "row ", P4_STATIC);
   100164           sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
   100165           sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
   100166                             " missing from index ", P4_STATIC);
   100167           sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
   100168           jmp5 = sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
   100169                                    pIdx->zName, P4_TRANSIENT);
   100170           sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
   100171           sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
   100172           jmp4 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
   100173           sqlite3VdbeAddOp0(v, OP_Halt);
   100174           sqlite3VdbeJumpHere(v, jmp2);
   100175           /* For UNIQUE indexes, verify that only one entry exists with the
   100176           ** current key.  The entry is unique if (1) any column is NULL
   100177           ** or (2) the next entry has a different key */
   100178           if( IsUniqueIndex(pIdx) ){
   100179             int uniqOk = sqlite3VdbeMakeLabel(v);
   100180             int jmp6;
   100181             int kk;
   100182             for(kk=0; kk<pIdx->nKeyCol; kk++){
   100183               int iCol = pIdx->aiColumn[kk];
   100184               assert( iCol>=0 && iCol<pTab->nCol );
   100185               if( pTab->aCol[iCol].notNull ) continue;
   100186               sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
   100187               VdbeCoverage(v);
   100188             }
   100189             jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
   100190             sqlite3VdbeAddOp2(v, OP_Goto, 0, uniqOk);
   100191             sqlite3VdbeJumpHere(v, jmp6);
   100192             sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
   100193                                  pIdx->nKeyCol); VdbeCoverage(v);
   100194             sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
   100195             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
   100196                               "non-unique entry in index ", P4_STATIC);
   100197             sqlite3VdbeAddOp2(v, OP_Goto, 0, jmp5);
   100198             sqlite3VdbeResolveLabel(v, uniqOk);
   100199           }
   100200           sqlite3VdbeJumpHere(v, jmp4);
   100201           sqlite3ResolvePartIdxLabel(pParse, jmp3);
   100202         }
   100203         sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
   100204         sqlite3VdbeJumpHere(v, loopTop-1);
   100205 #ifndef SQLITE_OMIT_BTREECOUNT
   100206         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0,
   100207                      "wrong # of entries in index ", P4_STATIC);
   100208         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
   100209           if( pPk==pIdx ) continue;
   100210           addr = sqlite3VdbeCurrentAddr(v);
   100211           sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr+2); VdbeCoverage(v);
   100212           sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
   100213           sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
   100214           sqlite3VdbeAddOp3(v, OP_Eq, 8+j, addr+8, 3); VdbeCoverage(v);
   100215           sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
   100216           sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
   100217           sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pIdx->zName, P4_TRANSIENT);
   100218           sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7);
   100219           sqlite3VdbeAddOp2(v, OP_ResultRow, 7, 1);
   100220         }
   100221 #endif /* SQLITE_OMIT_BTREECOUNT */
   100222       }
   100223     }
   100224     addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
   100225     sqlite3VdbeChangeP3(v, addr, -mxErr);
   100226     sqlite3VdbeJumpHere(v, addr);
   100227     sqlite3VdbeChangeP4(v, addr+1, "ok", P4_STATIC);
   100228   }
   100229   break;
   100230 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
   100231 
   100232 #ifndef SQLITE_OMIT_UTF16
   100233   /*
   100234   **   PRAGMA encoding
   100235   **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
   100236   **
   100237   ** In its first form, this pragma returns the encoding of the main
   100238   ** database. If the database is not initialized, it is initialized now.
   100239   **
   100240   ** The second form of this pragma is a no-op if the main database file
   100241   ** has not already been initialized. In this case it sets the default
   100242   ** encoding that will be used for the main database file if a new file
   100243   ** is created. If an existing main database file is opened, then the
   100244   ** default text encoding for the existing database is used.
   100245   **
   100246   ** In all cases new databases created using the ATTACH command are
   100247   ** created to use the same default text encoding as the main database. If
   100248   ** the main database has not been initialized and/or created when ATTACH
   100249   ** is executed, this is done before the ATTACH operation.
   100250   **
   100251   ** In the second form this pragma sets the text encoding to be used in
   100252   ** new database files created using this database handle. It is only
   100253   ** useful if invoked immediately after the main database i
   100254   */
   100255   case PragTyp_ENCODING: {
   100256     static const struct EncName {
   100257       char *zName;
   100258       u8 enc;
   100259     } encnames[] = {
   100260       { "UTF8",     SQLITE_UTF8        },
   100261       { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
   100262       { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
   100263       { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
   100264       { "UTF16le",  SQLITE_UTF16LE     },
   100265       { "UTF16be",  SQLITE_UTF16BE     },
   100266       { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
   100267       { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
   100268       { 0, 0 }
   100269     };
   100270     const struct EncName *pEnc;
   100271     if( !zRight ){    /* "PRAGMA encoding" */
   100272       if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   100273       sqlite3VdbeSetNumCols(v, 1);
   100274       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
   100275       sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
   100276       assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
   100277       assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
   100278       assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
   100279       sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
   100280       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
   100281     }else{                        /* "PRAGMA encoding = XXX" */
   100282       /* Only change the value of sqlite.enc if the database handle is not
   100283       ** initialized. If the main database exists, the new sqlite.enc value
   100284       ** will be overwritten when the schema is next loaded. If it does not
   100285       ** already exists, it will be created to use the new encoding value.
   100286       */
   100287       if(
   100288         !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
   100289         DbHasProperty(db, 0, DB_Empty)
   100290       ){
   100291         for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
   100292           if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
   100293             ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
   100294             break;
   100295           }
   100296         }
   100297         if( !pEnc->zName ){
   100298           sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
   100299         }
   100300       }
   100301     }
   100302   }
   100303   break;
   100304 #endif /* SQLITE_OMIT_UTF16 */
   100305 
   100306 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
   100307   /*
   100308   **   PRAGMA [database.]schema_version
   100309   **   PRAGMA [database.]schema_version = <integer>
   100310   **
   100311   **   PRAGMA [database.]user_version
   100312   **   PRAGMA [database.]user_version = <integer>
   100313   **
   100314   **   PRAGMA [database.]freelist_count = <integer>
   100315   **
   100316   **   PRAGMA [database.]application_id
   100317   **   PRAGMA [database.]application_id = <integer>
   100318   **
   100319   ** The pragma's schema_version and user_version are used to set or get
   100320   ** the value of the schema-version and user-version, respectively. Both
   100321   ** the schema-version and the user-version are 32-bit signed integers
   100322   ** stored in the database header.
   100323   **
   100324   ** The schema-cookie is usually only manipulated internally by SQLite. It
   100325   ** is incremented by SQLite whenever the database schema is modified (by
   100326   ** creating or dropping a table or index). The schema version is used by
   100327   ** SQLite each time a query is executed to ensure that the internal cache
   100328   ** of the schema used when compiling the SQL query matches the schema of
   100329   ** the database against which the compiled query is actually executed.
   100330   ** Subverting this mechanism by using "PRAGMA schema_version" to modify
   100331   ** the schema-version is potentially dangerous and may lead to program
   100332   ** crashes or database corruption. Use with caution!
   100333   **
   100334   ** The user-version is not used internally by SQLite. It may be used by
   100335   ** applications for any purpose.
   100336   */
   100337   case PragTyp_HEADER_VALUE: {
   100338     int iCookie;   /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
   100339     sqlite3VdbeUsesBtree(v, iDb);
   100340     switch( zLeft[0] ){
   100341       case 'a': case 'A':
   100342         iCookie = BTREE_APPLICATION_ID;
   100343         break;
   100344       case 'f': case 'F':
   100345         iCookie = BTREE_FREE_PAGE_COUNT;
   100346         break;
   100347       case 's': case 'S':
   100348         iCookie = BTREE_SCHEMA_VERSION;
   100349         break;
   100350       default:
   100351         iCookie = BTREE_USER_VERSION;
   100352         break;
   100353     }
   100354 
   100355     if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
   100356       /* Write the specified cookie value */
   100357       static const VdbeOpList setCookie[] = {
   100358         { OP_Transaction,    0,  1,  0},    /* 0 */
   100359         { OP_Integer,        0,  1,  0},    /* 1 */
   100360         { OP_SetCookie,      0,  0,  1},    /* 2 */
   100361       };
   100362       int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
   100363       sqlite3VdbeChangeP1(v, addr, iDb);
   100364       sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
   100365       sqlite3VdbeChangeP1(v, addr+2, iDb);
   100366       sqlite3VdbeChangeP2(v, addr+2, iCookie);
   100367     }else{
   100368       /* Read the specified cookie value */
   100369       static const VdbeOpList readCookie[] = {
   100370         { OP_Transaction,     0,  0,  0},    /* 0 */
   100371         { OP_ReadCookie,      0,  1,  0},    /* 1 */
   100372         { OP_ResultRow,       1,  1,  0}
   100373       };
   100374       int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie, 0);
   100375       sqlite3VdbeChangeP1(v, addr, iDb);
   100376       sqlite3VdbeChangeP1(v, addr+1, iDb);
   100377       sqlite3VdbeChangeP3(v, addr+1, iCookie);
   100378       sqlite3VdbeSetNumCols(v, 1);
   100379       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
   100380     }
   100381   }
   100382   break;
   100383 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
   100384 
   100385 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
   100386   /*
   100387   **   PRAGMA compile_options
   100388   **
   100389   ** Return the names of all compile-time options used in this build,
   100390   ** one option per row.
   100391   */
   100392   case PragTyp_COMPILE_OPTIONS: {
   100393     int i = 0;
   100394     const char *zOpt;
   100395     sqlite3VdbeSetNumCols(v, 1);
   100396     pParse->nMem = 1;
   100397     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
   100398     while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
   100399       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
   100400       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
   100401     }
   100402   }
   100403   break;
   100404 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
   100405 
   100406 #ifndef SQLITE_OMIT_WAL
   100407   /*
   100408   **   PRAGMA [database.]wal_checkpoint = passive|full|restart
   100409   **
   100410   ** Checkpoint the database.
   100411   */
   100412   case PragTyp_WAL_CHECKPOINT: {
   100413     int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
   100414     int eMode = SQLITE_CHECKPOINT_PASSIVE;
   100415     if( zRight ){
   100416       if( sqlite3StrICmp(zRight, "full")==0 ){
   100417         eMode = SQLITE_CHECKPOINT_FULL;
   100418       }else if( sqlite3StrICmp(zRight, "restart")==0 ){
   100419         eMode = SQLITE_CHECKPOINT_RESTART;
   100420       }
   100421     }
   100422     sqlite3VdbeSetNumCols(v, 3);
   100423     pParse->nMem = 3;
   100424     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
   100425     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
   100426     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
   100427 
   100428     sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
   100429     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
   100430   }
   100431   break;
   100432 
   100433   /*
   100434   **   PRAGMA wal_autocheckpoint
   100435   **   PRAGMA wal_autocheckpoint = N
   100436   **
   100437   ** Configure a database connection to automatically checkpoint a database
   100438   ** after accumulating N frames in the log. Or query for the current value
   100439   ** of N.
   100440   */
   100441   case PragTyp_WAL_AUTOCHECKPOINT: {
   100442     if( zRight ){
   100443       sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
   100444     }
   100445     returnSingleInt(pParse, "wal_autocheckpoint",
   100446        db->xWalCallback==sqlite3WalDefaultHook ?
   100447            SQLITE_PTR_TO_INT(db->pWalArg) : 0);
   100448   }
   100449   break;
   100450 #endif
   100451 
   100452   /*
   100453   **  PRAGMA shrink_memory
   100454   **
   100455   ** This pragma attempts to free as much memory as possible from the
   100456   ** current database connection.
   100457   */
   100458   case PragTyp_SHRINK_MEMORY: {
   100459     sqlite3_db_release_memory(db);
   100460     break;
   100461   }
   100462 
   100463   /*
   100464   **   PRAGMA busy_timeout
   100465   **   PRAGMA busy_timeout = N
   100466   **
   100467   ** Call sqlite3_busy_timeout(db, N).  Return the current timeout value
   100468   ** if one is set.  If no busy handler or a different busy handler is set
   100469   ** then 0 is returned.  Setting the busy_timeout to 0 or negative
   100470   ** disables the timeout.
   100471   */
   100472   /*case PragTyp_BUSY_TIMEOUT*/ default: {
   100473     assert( aPragmaNames[mid].ePragTyp==PragTyp_BUSY_TIMEOUT );
   100474     if( zRight ){
   100475       sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
   100476     }
   100477     returnSingleInt(pParse, "timeout",  db->busyTimeout);
   100478     break;
   100479   }
   100480 
   100481   /*
   100482   **   PRAGMA soft_heap_limit
   100483   **   PRAGMA soft_heap_limit = N
   100484   **
   100485   ** Call sqlite3_soft_heap_limit64(N).  Return the result.  If N is omitted,
   100486   ** use -1.
   100487   */
   100488   case PragTyp_SOFT_HEAP_LIMIT: {
   100489     sqlite3_int64 N;
   100490     if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
   100491       sqlite3_soft_heap_limit64(N);
   100492     }
   100493     returnSingleInt(pParse, "soft_heap_limit",  sqlite3_soft_heap_limit64(-1));
   100494     break;
   100495   }
   100496 
   100497 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
   100498   /*
   100499   ** Report the current state of file logs for all databases
   100500   */
   100501   case PragTyp_LOCK_STATUS: {
   100502     static const char *const azLockName[] = {
   100503       "unlocked", "shared", "reserved", "pending", "exclusive"
   100504     };
   100505     int i;
   100506     sqlite3VdbeSetNumCols(v, 2);
   100507     pParse->nMem = 2;
   100508     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
   100509     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
   100510     for(i=0; i<db->nDb; i++){
   100511       Btree *pBt;
   100512       const char *zState = "unknown";
   100513       int j;
   100514       if( db->aDb[i].zName==0 ) continue;
   100515       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
   100516       pBt = db->aDb[i].pBt;
   100517       if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
   100518         zState = "closed";
   100519       }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
   100520                                      SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
   100521          zState = azLockName[j];
   100522       }
   100523       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
   100524       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
   100525     }
   100526     break;
   100527   }
   100528 #endif
   100529 
   100530 #ifdef SQLITE_HAS_CODEC
   100531   case PragTyp_KEY: {
   100532     if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
   100533     break;
   100534   }
   100535   case PragTyp_REKEY: {
   100536     if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
   100537     break;
   100538   }
   100539   case PragTyp_HEXKEY: {
   100540     if( zRight ){
   100541       u8 iByte;
   100542       int i;
   100543       char zKey[40];
   100544       for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
   100545         iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
   100546         if( (i&1)!=0 ) zKey[i/2] = iByte;
   100547       }
   100548       if( (zLeft[3] & 0xf)==0xb ){
   100549         sqlite3_key_v2(db, zDb, zKey, i/2);
   100550       }else{
   100551         sqlite3_rekey_v2(db, zDb, zKey, i/2);
   100552       }
   100553     }
   100554     break;
   100555   }
   100556 #endif
   100557 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
   100558   case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
   100559 #ifdef SQLITE_HAS_CODEC
   100560     if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
   100561       sqlite3_activate_see(&zRight[4]);
   100562     }
   100563 #endif
   100564 #ifdef SQLITE_ENABLE_CEROD
   100565     if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
   100566       sqlite3_activate_cerod(&zRight[6]);
   100567     }
   100568 #endif
   100569   }
   100570   break;
   100571 #endif
   100572 
   100573   } /* End of the PRAGMA switch */
   100574 
   100575 pragma_out:
   100576   sqlite3DbFree(db, zLeft);
   100577   sqlite3DbFree(db, zRight);
   100578 }
   100579 
   100580 #endif /* SQLITE_OMIT_PRAGMA */
   100581 
   100582 /************** End of pragma.c **********************************************/
   100583 /************** Begin file prepare.c *****************************************/
   100584 /*
   100585 ** 2005 May 25
   100586 **
   100587 ** The author disclaims copyright to this source code.  In place of
   100588 ** a legal notice, here is a blessing:
   100589 **
   100590 **    May you do good and not evil.
   100591 **    May you find forgiveness for yourself and forgive others.
   100592 **    May you share freely, never taking more than you give.
   100593 **
   100594 *************************************************************************
   100595 ** This file contains the implementation of the sqlite3_prepare()
   100596 ** interface, and routines that contribute to loading the database schema
   100597 ** from disk.
   100598 */
   100599 
   100600 /*
   100601 ** Fill the InitData structure with an error message that indicates
   100602 ** that the database is corrupt.
   100603 */
   100604 static void corruptSchema(
   100605   InitData *pData,     /* Initialization context */
   100606   const char *zObj,    /* Object being parsed at the point of error */
   100607   const char *zExtra   /* Error information */
   100608 ){
   100609   sqlite3 *db = pData->db;
   100610   if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
   100611     if( zObj==0 ) zObj = "?";
   100612     sqlite3SetString(pData->pzErrMsg, db,
   100613       "malformed database schema (%s)", zObj);
   100614     if( zExtra ){
   100615       *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg,
   100616                                  "%s - %s", *pData->pzErrMsg, zExtra);
   100617     }
   100618   }
   100619   pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
   100620 }
   100621 
   100622 /*
   100623 ** This is the callback routine for the code that initializes the
   100624 ** database.  See sqlite3Init() below for additional information.
   100625 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
   100626 **
   100627 ** Each callback contains the following information:
   100628 **
   100629 **     argv[0] = name of thing being created
   100630 **     argv[1] = root page number for table or index. 0 for trigger or view.
   100631 **     argv[2] = SQL text for the CREATE statement.
   100632 **
   100633 */
   100634 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
   100635   InitData *pData = (InitData*)pInit;
   100636   sqlite3 *db = pData->db;
   100637   int iDb = pData->iDb;
   100638 
   100639   assert( argc==3 );
   100640   UNUSED_PARAMETER2(NotUsed, argc);
   100641   assert( sqlite3_mutex_held(db->mutex) );
   100642   DbClearProperty(db, iDb, DB_Empty);
   100643   if( db->mallocFailed ){
   100644     corruptSchema(pData, argv[0], 0);
   100645     return 1;
   100646   }
   100647 
   100648   assert( iDb>=0 && iDb<db->nDb );
   100649   if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
   100650   if( argv[1]==0 ){
   100651     corruptSchema(pData, argv[0], 0);
   100652   }else if( argv[2] && argv[2][0] ){
   100653     /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
   100654     ** But because db->init.busy is set to 1, no VDBE code is generated
   100655     ** or executed.  All the parser does is build the internal data
   100656     ** structures that describe the table, index, or view.
   100657     */
   100658     int rc;
   100659     sqlite3_stmt *pStmt;
   100660     TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
   100661 
   100662     assert( db->init.busy );
   100663     db->init.iDb = iDb;
   100664     db->init.newTnum = sqlite3Atoi(argv[1]);
   100665     db->init.orphanTrigger = 0;
   100666     TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
   100667     rc = db->errCode;
   100668     assert( (rc&0xFF)==(rcp&0xFF) );
   100669     db->init.iDb = 0;
   100670     if( SQLITE_OK!=rc ){
   100671       if( db->init.orphanTrigger ){
   100672         assert( iDb==1 );
   100673       }else{
   100674         pData->rc = rc;
   100675         if( rc==SQLITE_NOMEM ){
   100676           db->mallocFailed = 1;
   100677         }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
   100678           corruptSchema(pData, argv[0], sqlite3_errmsg(db));
   100679         }
   100680       }
   100681     }
   100682     sqlite3_finalize(pStmt);
   100683   }else if( argv[0]==0 ){
   100684     corruptSchema(pData, 0, 0);
   100685   }else{
   100686     /* If the SQL column is blank it means this is an index that
   100687     ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
   100688     ** constraint for a CREATE TABLE.  The index should have already
   100689     ** been created when we processed the CREATE TABLE.  All we have
   100690     ** to do here is record the root page number for that index.
   100691     */
   100692     Index *pIndex;
   100693     pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
   100694     if( pIndex==0 ){
   100695       /* This can occur if there exists an index on a TEMP table which
   100696       ** has the same name as another index on a permanent index.  Since
   100697       ** the permanent table is hidden by the TEMP table, we can also
   100698       ** safely ignore the index on the permanent table.
   100699       */
   100700       /* Do Nothing */;
   100701     }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
   100702       corruptSchema(pData, argv[0], "invalid rootpage");
   100703     }
   100704   }
   100705   return 0;
   100706 }
   100707 
   100708 /*
   100709 ** Attempt to read the database schema and initialize internal
   100710 ** data structures for a single database file.  The index of the
   100711 ** database file is given by iDb.  iDb==0 is used for the main
   100712 ** database.  iDb==1 should never be used.  iDb>=2 is used for
   100713 ** auxiliary databases.  Return one of the SQLITE_ error codes to
   100714 ** indicate success or failure.
   100715 */
   100716 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
   100717   int rc;
   100718   int i;
   100719 #ifndef SQLITE_OMIT_DEPRECATED
   100720   int size;
   100721 #endif
   100722   Table *pTab;
   100723   Db *pDb;
   100724   char const *azArg[4];
   100725   int meta[5];
   100726   InitData initData;
   100727   char const *zMasterSchema;
   100728   char const *zMasterName;
   100729   int openedTransaction = 0;
   100730 
   100731   /*
   100732   ** The master database table has a structure like this
   100733   */
   100734   static const char master_schema[] =
   100735      "CREATE TABLE sqlite_master(\n"
   100736      "  type text,\n"
   100737      "  name text,\n"
   100738      "  tbl_name text,\n"
   100739      "  rootpage integer,\n"
   100740      "  sql text\n"
   100741      ")"
   100742   ;
   100743 #ifndef SQLITE_OMIT_TEMPDB
   100744   static const char temp_master_schema[] =
   100745      "CREATE TEMP TABLE sqlite_temp_master(\n"
   100746      "  type text,\n"
   100747      "  name text,\n"
   100748      "  tbl_name text,\n"
   100749      "  rootpage integer,\n"
   100750      "  sql text\n"
   100751      ")"
   100752   ;
   100753 #else
   100754   #define temp_master_schema 0
   100755 #endif
   100756 
   100757   assert( iDb>=0 && iDb<db->nDb );
   100758   assert( db->aDb[iDb].pSchema );
   100759   assert( sqlite3_mutex_held(db->mutex) );
   100760   assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
   100761 
   100762   /* zMasterSchema and zInitScript are set to point at the master schema
   100763   ** and initialisation script appropriate for the database being
   100764   ** initialized. zMasterName is the name of the master table.
   100765   */
   100766   if( !OMIT_TEMPDB && iDb==1 ){
   100767     zMasterSchema = temp_master_schema;
   100768   }else{
   100769     zMasterSchema = master_schema;
   100770   }
   100771   zMasterName = SCHEMA_TABLE(iDb);
   100772 
   100773   /* Construct the schema tables.  */
   100774   azArg[0] = zMasterName;
   100775   azArg[1] = "1";
   100776   azArg[2] = zMasterSchema;
   100777   azArg[3] = 0;
   100778   initData.db = db;
   100779   initData.iDb = iDb;
   100780   initData.rc = SQLITE_OK;
   100781   initData.pzErrMsg = pzErrMsg;
   100782   sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
   100783   if( initData.rc ){
   100784     rc = initData.rc;
   100785     goto error_out;
   100786   }
   100787   pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
   100788   if( ALWAYS(pTab) ){
   100789     pTab->tabFlags |= TF_Readonly;
   100790   }
   100791 
   100792   /* Create a cursor to hold the database open
   100793   */
   100794   pDb = &db->aDb[iDb];
   100795   if( pDb->pBt==0 ){
   100796     if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
   100797       DbSetProperty(db, 1, DB_SchemaLoaded);
   100798     }
   100799     return SQLITE_OK;
   100800   }
   100801 
   100802   /* If there is not already a read-only (or read-write) transaction opened
   100803   ** on the b-tree database, open one now. If a transaction is opened, it
   100804   ** will be closed before this function returns.  */
   100805   sqlite3BtreeEnter(pDb->pBt);
   100806   if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
   100807     rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
   100808     if( rc!=SQLITE_OK ){
   100809       sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
   100810       goto initone_error_out;
   100811     }
   100812     openedTransaction = 1;
   100813   }
   100814 
   100815   /* Get the database meta information.
   100816   **
   100817   ** Meta values are as follows:
   100818   **    meta[0]   Schema cookie.  Changes with each schema change.
   100819   **    meta[1]   File format of schema layer.
   100820   **    meta[2]   Size of the page cache.
   100821   **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
   100822   **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
   100823   **    meta[5]   User version
   100824   **    meta[6]   Incremental vacuum mode
   100825   **    meta[7]   unused
   100826   **    meta[8]   unused
   100827   **    meta[9]   unused
   100828   **
   100829   ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
   100830   ** the possible values of meta[4].
   100831   */
   100832   for(i=0; i<ArraySize(meta); i++){
   100833     sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
   100834   }
   100835   pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
   100836 
   100837   /* If opening a non-empty database, check the text encoding. For the
   100838   ** main database, set sqlite3.enc to the encoding of the main database.
   100839   ** For an attached db, it is an error if the encoding is not the same
   100840   ** as sqlite3.enc.
   100841   */
   100842   if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
   100843     if( iDb==0 ){
   100844 #ifndef SQLITE_OMIT_UTF16
   100845       u8 encoding;
   100846       /* If opening the main database, set ENC(db). */
   100847       encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
   100848       if( encoding==0 ) encoding = SQLITE_UTF8;
   100849       ENC(db) = encoding;
   100850 #else
   100851       ENC(db) = SQLITE_UTF8;
   100852 #endif
   100853     }else{
   100854       /* If opening an attached database, the encoding much match ENC(db) */
   100855       if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
   100856         sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
   100857             " text encoding as main database");
   100858         rc = SQLITE_ERROR;
   100859         goto initone_error_out;
   100860       }
   100861     }
   100862   }else{
   100863     DbSetProperty(db, iDb, DB_Empty);
   100864   }
   100865   pDb->pSchema->enc = ENC(db);
   100866 
   100867   if( pDb->pSchema->cache_size==0 ){
   100868 #ifndef SQLITE_OMIT_DEPRECATED
   100869     size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
   100870     if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
   100871     pDb->pSchema->cache_size = size;
   100872 #else
   100873     pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
   100874 #endif
   100875     sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
   100876   }
   100877 
   100878   /*
   100879   ** file_format==1    Version 3.0.0.
   100880   ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
   100881   ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
   100882   ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
   100883   */
   100884   pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
   100885   if( pDb->pSchema->file_format==0 ){
   100886     pDb->pSchema->file_format = 1;
   100887   }
   100888   if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
   100889     sqlite3SetString(pzErrMsg, db, "unsupported file format");
   100890     rc = SQLITE_CORRUPT_BKPT; // Android Change from "rc = SQLITE_ERROR;"
   100891     goto initone_error_out;
   100892   }
   100893 
   100894   /* Ticket #2804:  When we open a database in the newer file format,
   100895   ** clear the legacy_file_format pragma flag so that a VACUUM will
   100896   ** not downgrade the database and thus invalidate any descending
   100897   ** indices that the user might have created.
   100898   */
   100899   if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
   100900     db->flags &= ~SQLITE_LegacyFileFmt;
   100901   }
   100902 
   100903   /* Read the schema information out of the schema tables
   100904   */
   100905   assert( db->init.busy );
   100906   {
   100907     char *zSql;
   100908     zSql = sqlite3MPrintf(db,
   100909         "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
   100910         db->aDb[iDb].zName, zMasterName);
   100911 #ifndef SQLITE_OMIT_AUTHORIZATION
   100912     {
   100913       int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
   100914       xAuth = db->xAuth;
   100915       db->xAuth = 0;
   100916 #endif
   100917       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
   100918 #ifndef SQLITE_OMIT_AUTHORIZATION
   100919       db->xAuth = xAuth;
   100920     }
   100921 #endif
   100922     if( rc==SQLITE_OK ) rc = initData.rc;
   100923     sqlite3DbFree(db, zSql);
   100924 #ifndef SQLITE_OMIT_ANALYZE
   100925     if( rc==SQLITE_OK ){
   100926       sqlite3AnalysisLoad(db, iDb);
   100927     }
   100928 #endif
   100929   }
   100930   if( db->mallocFailed ){
   100931     rc = SQLITE_NOMEM;
   100932     sqlite3ResetAllSchemasOfConnection(db);
   100933   }
   100934   if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
   100935     /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
   100936     ** the schema loaded, even if errors occurred. In this situation the
   100937     ** current sqlite3_prepare() operation will fail, but the following one
   100938     ** will attempt to compile the supplied statement against whatever subset
   100939     ** of the schema was loaded before the error occurred. The primary
   100940     ** purpose of this is to allow access to the sqlite_master table
   100941     ** even when its contents have been corrupted.
   100942     */
   100943     DbSetProperty(db, iDb, DB_SchemaLoaded);
   100944     rc = SQLITE_OK;
   100945   }
   100946 
   100947   /* Jump here for an error that occurs after successfully allocating
   100948   ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
   100949   ** before that point, jump to error_out.
   100950   */
   100951 initone_error_out:
   100952   if( openedTransaction ){
   100953     sqlite3BtreeCommit(pDb->pBt);
   100954   }
   100955   sqlite3BtreeLeave(pDb->pBt);
   100956 
   100957 error_out:
   100958   if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
   100959     db->mallocFailed = 1;
   100960   }
   100961   return rc;
   100962 }
   100963 
   100964 /*
   100965 ** Initialize all database files - the main database file, the file
   100966 ** used to store temporary tables, and any additional database files
   100967 ** created using ATTACH statements.  Return a success code.  If an
   100968 ** error occurs, write an error message into *pzErrMsg.
   100969 **
   100970 ** After a database is initialized, the DB_SchemaLoaded bit is set
   100971 ** bit is set in the flags field of the Db structure. If the database
   100972 ** file was of zero-length, then the DB_Empty flag is also set.
   100973 */
   100974 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
   100975   int i, rc;
   100976   int commit_internal = !(db->flags&SQLITE_InternChanges);
   100977 
   100978   assert( sqlite3_mutex_held(db->mutex) );
   100979   rc = SQLITE_OK;
   100980   db->init.busy = 1;
   100981   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
   100982     if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
   100983     rc = sqlite3InitOne(db, i, pzErrMsg);
   100984     if( rc ){
   100985       sqlite3ResetOneSchema(db, i);
   100986     }
   100987   }
   100988 
   100989   /* Once all the other databases have been initialized, load the schema
   100990   ** for the TEMP database. This is loaded last, as the TEMP database
   100991   ** schema may contain references to objects in other databases.
   100992   */
   100993 #ifndef SQLITE_OMIT_TEMPDB
   100994   if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
   100995                     && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
   100996     rc = sqlite3InitOne(db, 1, pzErrMsg);
   100997     if( rc ){
   100998       sqlite3ResetOneSchema(db, 1);
   100999     }
   101000   }
   101001 #endif
   101002 
   101003   db->init.busy = 0;
   101004   if( rc==SQLITE_OK && commit_internal ){
   101005     sqlite3CommitInternalChanges(db);
   101006   }
   101007 
   101008   return rc;
   101009 }
   101010 
   101011 /*
   101012 ** This routine is a no-op if the database schema is already initialized.
   101013 ** Otherwise, the schema is loaded. An error code is returned.
   101014 */
   101015 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
   101016   int rc = SQLITE_OK;
   101017   sqlite3 *db = pParse->db;
   101018   assert( sqlite3_mutex_held(db->mutex) );
   101019   if( !db->init.busy ){
   101020     rc = sqlite3Init(db, &pParse->zErrMsg);
   101021   }
   101022   if( rc!=SQLITE_OK ){
   101023     pParse->rc = rc;
   101024     pParse->nErr++;
   101025   }
   101026   return rc;
   101027 }
   101028 
   101029 
   101030 /*
   101031 ** Check schema cookies in all databases.  If any cookie is out
   101032 ** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
   101033 ** make no changes to pParse->rc.
   101034 */
   101035 static void schemaIsValid(Parse *pParse){
   101036   sqlite3 *db = pParse->db;
   101037   int iDb;
   101038   int rc;
   101039   int cookie;
   101040 
   101041   assert( pParse->checkSchema );
   101042   assert( sqlite3_mutex_held(db->mutex) );
   101043   for(iDb=0; iDb<db->nDb; iDb++){
   101044     int openedTransaction = 0;         /* True if a transaction is opened */
   101045     Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
   101046     if( pBt==0 ) continue;
   101047 
   101048     /* If there is not already a read-only (or read-write) transaction opened
   101049     ** on the b-tree database, open one now. If a transaction is opened, it
   101050     ** will be closed immediately after reading the meta-value. */
   101051     if( !sqlite3BtreeIsInReadTrans(pBt) ){
   101052       rc = sqlite3BtreeBeginTrans(pBt, 0);
   101053       if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
   101054         db->mallocFailed = 1;
   101055       }
   101056       if( rc!=SQLITE_OK ) return;
   101057       openedTransaction = 1;
   101058     }
   101059 
   101060     /* Read the schema cookie from the database. If it does not match the
   101061     ** value stored as part of the in-memory schema representation,
   101062     ** set Parse.rc to SQLITE_SCHEMA. */
   101063     sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
   101064     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   101065     if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
   101066       sqlite3ResetOneSchema(db, iDb);
   101067       pParse->rc = SQLITE_SCHEMA;
   101068     }
   101069 
   101070     /* Close the transaction, if one was opened. */
   101071     if( openedTransaction ){
   101072       sqlite3BtreeCommit(pBt);
   101073     }
   101074   }
   101075 }
   101076 
   101077 /*
   101078 ** Convert a schema pointer into the iDb index that indicates
   101079 ** which database file in db->aDb[] the schema refers to.
   101080 **
   101081 ** If the same database is attached more than once, the first
   101082 ** attached database is returned.
   101083 */
   101084 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
   101085   int i = -1000000;
   101086 
   101087   /* If pSchema is NULL, then return -1000000. This happens when code in
   101088   ** expr.c is trying to resolve a reference to a transient table (i.e. one
   101089   ** created by a sub-select). In this case the return value of this
   101090   ** function should never be used.
   101091   **
   101092   ** We return -1000000 instead of the more usual -1 simply because using
   101093   ** -1000000 as the incorrect index into db->aDb[] is much
   101094   ** more likely to cause a segfault than -1 (of course there are assert()
   101095   ** statements too, but it never hurts to play the odds).
   101096   */
   101097   assert( sqlite3_mutex_held(db->mutex) );
   101098   if( pSchema ){
   101099     for(i=0; ALWAYS(i<db->nDb); i++){
   101100       if( db->aDb[i].pSchema==pSchema ){
   101101         break;
   101102       }
   101103     }
   101104     assert( i>=0 && i<db->nDb );
   101105   }
   101106   return i;
   101107 }
   101108 
   101109 /*
   101110 ** Free all memory allocations in the pParse object
   101111 */
   101112 SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
   101113   if( pParse ){
   101114     sqlite3 *db = pParse->db;
   101115     sqlite3DbFree(db, pParse->aLabel);
   101116     sqlite3ExprListDelete(db, pParse->pConstExpr);
   101117   }
   101118 }
   101119 
   101120 /*
   101121 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
   101122 */
   101123 static int sqlite3Prepare(
   101124   sqlite3 *db,              /* Database handle. */
   101125   const char *zSql,         /* UTF-8 encoded SQL statement. */
   101126   int nBytes,               /* Length of zSql in bytes. */
   101127   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
   101128   Vdbe *pReprepare,         /* VM being reprepared */
   101129   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   101130   const char **pzTail       /* OUT: End of parsed string */
   101131 ){
   101132   Parse *pParse;            /* Parsing context */
   101133   char *zErrMsg = 0;        /* Error message */
   101134   int rc = SQLITE_OK;       /* Result code */
   101135   int i;                    /* Loop counter */
   101136 
   101137   /* Allocate the parsing context */
   101138   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
   101139   if( pParse==0 ){
   101140     rc = SQLITE_NOMEM;
   101141     goto end_prepare;
   101142   }
   101143   pParse->pReprepare = pReprepare;
   101144   assert( ppStmt && *ppStmt==0 );
   101145   assert( !db->mallocFailed );
   101146   assert( sqlite3_mutex_held(db->mutex) );
   101147 
   101148   /* Check to verify that it is possible to get a read lock on all
   101149   ** database schemas.  The inability to get a read lock indicates that
   101150   ** some other database connection is holding a write-lock, which in
   101151   ** turn means that the other connection has made uncommitted changes
   101152   ** to the schema.
   101153   **
   101154   ** Were we to proceed and prepare the statement against the uncommitted
   101155   ** schema changes and if those schema changes are subsequently rolled
   101156   ** back and different changes are made in their place, then when this
   101157   ** prepared statement goes to run the schema cookie would fail to detect
   101158   ** the schema change.  Disaster would follow.
   101159   **
   101160   ** This thread is currently holding mutexes on all Btrees (because
   101161   ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
   101162   ** is not possible for another thread to start a new schema change
   101163   ** while this routine is running.  Hence, we do not need to hold
   101164   ** locks on the schema, we just need to make sure nobody else is
   101165   ** holding them.
   101166   **
   101167   ** Note that setting READ_UNCOMMITTED overrides most lock detection,
   101168   ** but it does *not* override schema lock detection, so this all still
   101169   ** works even if READ_UNCOMMITTED is set.
   101170   */
   101171   for(i=0; i<db->nDb; i++) {
   101172     Btree *pBt = db->aDb[i].pBt;
   101173     if( pBt ){
   101174       assert( sqlite3BtreeHoldsMutex(pBt) );
   101175       rc = sqlite3BtreeSchemaLocked(pBt);
   101176       if( rc ){
   101177         const char *zDb = db->aDb[i].zName;
   101178         sqlite3Error(db, rc, "database schema is locked: %s", zDb);
   101179         testcase( db->flags & SQLITE_ReadUncommitted );
   101180         goto end_prepare;
   101181       }
   101182     }
   101183   }
   101184 
   101185   sqlite3VtabUnlockList(db);
   101186 
   101187   pParse->db = db;
   101188   pParse->nQueryLoop = 0;  /* Logarithmic, so 0 really means 1 */
   101189   if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
   101190     char *zSqlCopy;
   101191     int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
   101192     testcase( nBytes==mxLen );
   101193     testcase( nBytes==mxLen+1 );
   101194     if( nBytes>mxLen ){
   101195       sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
   101196       rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
   101197       goto end_prepare;
   101198     }
   101199     zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
   101200     if( zSqlCopy ){
   101201       sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
   101202       sqlite3DbFree(db, zSqlCopy);
   101203       pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
   101204     }else{
   101205       pParse->zTail = &zSql[nBytes];
   101206     }
   101207   }else{
   101208     sqlite3RunParser(pParse, zSql, &zErrMsg);
   101209   }
   101210   assert( 0==pParse->nQueryLoop );
   101211 
   101212   if( db->mallocFailed ){
   101213     pParse->rc = SQLITE_NOMEM;
   101214   }
   101215   if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
   101216   if( pParse->checkSchema ){
   101217     schemaIsValid(pParse);
   101218   }
   101219   if( db->mallocFailed ){
   101220     pParse->rc = SQLITE_NOMEM;
   101221   }
   101222   if( pzTail ){
   101223     *pzTail = pParse->zTail;
   101224   }
   101225   rc = pParse->rc;
   101226 
   101227 #ifndef SQLITE_OMIT_EXPLAIN
   101228   if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
   101229     static const char * const azColName[] = {
   101230        "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
   101231        "selectid", "order", "from", "detail"
   101232     };
   101233     int iFirst, mx;
   101234     if( pParse->explain==2 ){
   101235       sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
   101236       iFirst = 8;
   101237       mx = 12;
   101238     }else{
   101239       sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
   101240       iFirst = 0;
   101241       mx = 8;
   101242     }
   101243     for(i=iFirst; i<mx; i++){
   101244       sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
   101245                             azColName[i], SQLITE_STATIC);
   101246     }
   101247   }
   101248 #endif
   101249 
   101250   if( db->init.busy==0 ){
   101251     Vdbe *pVdbe = pParse->pVdbe;
   101252     sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
   101253   }
   101254   if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
   101255     sqlite3VdbeFinalize(pParse->pVdbe);
   101256     assert(!(*ppStmt));
   101257   }else{
   101258     *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
   101259   }
   101260 
   101261   if( zErrMsg ){
   101262     sqlite3Error(db, rc, "%s", zErrMsg);
   101263     sqlite3DbFree(db, zErrMsg);
   101264   }else{
   101265     sqlite3Error(db, rc, 0);
   101266   }
   101267 
   101268   /* Delete any TriggerPrg structures allocated while parsing this statement. */
   101269   while( pParse->pTriggerPrg ){
   101270     TriggerPrg *pT = pParse->pTriggerPrg;
   101271     pParse->pTriggerPrg = pT->pNext;
   101272     sqlite3DbFree(db, pT);
   101273   }
   101274 
   101275 end_prepare:
   101276 
   101277   sqlite3ParserReset(pParse);
   101278   sqlite3StackFree(db, pParse);
   101279   rc = sqlite3ApiExit(db, rc);
   101280   assert( (rc&db->errMask)==rc );
   101281   return rc;
   101282 }
   101283 static int sqlite3LockAndPrepare(
   101284   sqlite3 *db,              /* Database handle. */
   101285   const char *zSql,         /* UTF-8 encoded SQL statement. */
   101286   int nBytes,               /* Length of zSql in bytes. */
   101287   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
   101288   Vdbe *pOld,               /* VM being reprepared */
   101289   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   101290   const char **pzTail       /* OUT: End of parsed string */
   101291 ){
   101292   int rc;
   101293   assert( ppStmt!=0 );
   101294   *ppStmt = 0;
   101295   if( !sqlite3SafetyCheckOk(db) ){
   101296     return SQLITE_MISUSE_BKPT;
   101297   }
   101298   sqlite3_mutex_enter(db->mutex);
   101299   sqlite3BtreeEnterAll(db);
   101300   rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
   101301   if( rc==SQLITE_SCHEMA ){
   101302     sqlite3_finalize(*ppStmt);
   101303     rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
   101304   }
   101305   sqlite3BtreeLeaveAll(db);
   101306   sqlite3_mutex_leave(db->mutex);
   101307   assert( rc==SQLITE_OK || *ppStmt==0 );
   101308   return rc;
   101309 }
   101310 
   101311 /*
   101312 ** Rerun the compilation of a statement after a schema change.
   101313 **
   101314 ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
   101315 ** if the statement cannot be recompiled because another connection has
   101316 ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
   101317 ** occurs, return SQLITE_SCHEMA.
   101318 */
   101319 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
   101320   int rc;
   101321   sqlite3_stmt *pNew;
   101322   const char *zSql;
   101323   sqlite3 *db;
   101324 
   101325   assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
   101326   zSql = sqlite3_sql((sqlite3_stmt *)p);
   101327   assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
   101328   db = sqlite3VdbeDb(p);
   101329   assert( sqlite3_mutex_held(db->mutex) );
   101330   rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
   101331   if( rc ){
   101332     if( rc==SQLITE_NOMEM ){
   101333       db->mallocFailed = 1;
   101334     }
   101335     assert( pNew==0 );
   101336     return rc;
   101337   }else{
   101338     assert( pNew!=0 );
   101339   }
   101340   sqlite3VdbeSwap((Vdbe*)pNew, p);
   101341   sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
   101342   sqlite3VdbeResetStepResult((Vdbe*)pNew);
   101343   sqlite3VdbeFinalize((Vdbe*)pNew);
   101344   return SQLITE_OK;
   101345 }
   101346 
   101347 
   101348 /*
   101349 ** Two versions of the official API.  Legacy and new use.  In the legacy
   101350 ** version, the original SQL text is not saved in the prepared statement
   101351 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
   101352 ** sqlite3_step().  In the new version, the original SQL text is retained
   101353 ** and the statement is automatically recompiled if an schema change
   101354 ** occurs.
   101355 */
   101356 SQLITE_API int sqlite3_prepare(
   101357   sqlite3 *db,              /* Database handle. */
   101358   const char *zSql,         /* UTF-8 encoded SQL statement. */
   101359   int nBytes,               /* Length of zSql in bytes. */
   101360   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   101361   const char **pzTail       /* OUT: End of parsed string */
   101362 ){
   101363   int rc;
   101364   rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
   101365   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
   101366   return rc;
   101367 }
   101368 SQLITE_API int sqlite3_prepare_v2(
   101369   sqlite3 *db,              /* Database handle. */
   101370   const char *zSql,         /* UTF-8 encoded SQL statement. */
   101371   int nBytes,               /* Length of zSql in bytes. */
   101372   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   101373   const char **pzTail       /* OUT: End of parsed string */
   101374 ){
   101375   int rc;
   101376   rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
   101377   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
   101378   return rc;
   101379 }
   101380 
   101381 
   101382 #ifndef SQLITE_OMIT_UTF16
   101383 /*
   101384 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
   101385 */
   101386 static int sqlite3Prepare16(
   101387   sqlite3 *db,              /* Database handle. */
   101388   const void *zSql,         /* UTF-16 encoded SQL statement. */
   101389   int nBytes,               /* Length of zSql in bytes. */
   101390   int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
   101391   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   101392   const void **pzTail       /* OUT: End of parsed string */
   101393 ){
   101394   /* This function currently works by first transforming the UTF-16
   101395   ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
   101396   ** tricky bit is figuring out the pointer to return in *pzTail.
   101397   */
   101398   char *zSql8;
   101399   const char *zTail8 = 0;
   101400   int rc = SQLITE_OK;
   101401 
   101402   assert( ppStmt );
   101403   *ppStmt = 0;
   101404   if( !sqlite3SafetyCheckOk(db) ){
   101405     return SQLITE_MISUSE_BKPT;
   101406   }
   101407   if( nBytes>=0 ){
   101408     int sz;
   101409     const char *z = (const char*)zSql;
   101410     for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
   101411     nBytes = sz;
   101412   }
   101413   sqlite3_mutex_enter(db->mutex);
   101414   zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
   101415   if( zSql8 ){
   101416     rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
   101417   }
   101418 
   101419   if( zTail8 && pzTail ){
   101420     /* If sqlite3_prepare returns a tail pointer, we calculate the
   101421     ** equivalent pointer into the UTF-16 string by counting the unicode
   101422     ** characters between zSql8 and zTail8, and then returning a pointer
   101423     ** the same number of characters into the UTF-16 string.
   101424     */
   101425     int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
   101426     *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
   101427   }
   101428   sqlite3DbFree(db, zSql8);
   101429   rc = sqlite3ApiExit(db, rc);
   101430   sqlite3_mutex_leave(db->mutex);
   101431   return rc;
   101432 }
   101433 
   101434 /*
   101435 ** Two versions of the official API.  Legacy and new use.  In the legacy
   101436 ** version, the original SQL text is not saved in the prepared statement
   101437 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
   101438 ** sqlite3_step().  In the new version, the original SQL text is retained
   101439 ** and the statement is automatically recompiled if an schema change
   101440 ** occurs.
   101441 */
   101442 SQLITE_API int sqlite3_prepare16(
   101443   sqlite3 *db,              /* Database handle. */
   101444   const void *zSql,         /* UTF-16 encoded SQL statement. */
   101445   int nBytes,               /* Length of zSql in bytes. */
   101446   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   101447   const void **pzTail       /* OUT: End of parsed string */
   101448 ){
   101449   int rc;
   101450   rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
   101451   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
   101452   return rc;
   101453 }
   101454 SQLITE_API int sqlite3_prepare16_v2(
   101455   sqlite3 *db,              /* Database handle. */
   101456   const void *zSql,         /* UTF-16 encoded SQL statement. */
   101457   int nBytes,               /* Length of zSql in bytes. */
   101458   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   101459   const void **pzTail       /* OUT: End of parsed string */
   101460 ){
   101461   int rc;
   101462   rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
   101463   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
   101464   return rc;
   101465 }
   101466 
   101467 #endif /* SQLITE_OMIT_UTF16 */
   101468 
   101469 /************** End of prepare.c *********************************************/
   101470 /************** Begin file select.c ******************************************/
   101471 /*
   101472 ** 2001 September 15
   101473 **
   101474 ** The author disclaims copyright to this source code.  In place of
   101475 ** a legal notice, here is a blessing:
   101476 **
   101477 **    May you do good and not evil.
   101478 **    May you find forgiveness for yourself and forgive others.
   101479 **    May you share freely, never taking more than you give.
   101480 **
   101481 *************************************************************************
   101482 ** This file contains C code routines that are called by the parser
   101483 ** to handle SELECT statements in SQLite.
   101484 */
   101485 
   101486 /*
   101487 ** An instance of the following object is used to record information about
   101488 ** how to process the DISTINCT keyword, to simplify passing that information
   101489 ** into the selectInnerLoop() routine.
   101490 */
   101491 typedef struct DistinctCtx DistinctCtx;
   101492 struct DistinctCtx {
   101493   u8 isTnct;      /* True if the DISTINCT keyword is present */
   101494   u8 eTnctType;   /* One of the WHERE_DISTINCT_* operators */
   101495   int tabTnct;    /* Ephemeral table used for DISTINCT processing */
   101496   int addrTnct;   /* Address of OP_OpenEphemeral opcode for tabTnct */
   101497 };
   101498 
   101499 /*
   101500 ** An instance of the following object is used to record information about
   101501 ** the ORDER BY (or GROUP BY) clause of query is being coded.
   101502 */
   101503 typedef struct SortCtx SortCtx;
   101504 struct SortCtx {
   101505   ExprList *pOrderBy;   /* The ORDER BY (or GROUP BY clause) */
   101506   int nOBSat;           /* Number of ORDER BY terms satisfied by indices */
   101507   int iECursor;         /* Cursor number for the sorter */
   101508   int regReturn;        /* Register holding block-output return address */
   101509   int labelBkOut;       /* Start label for the block-output subroutine */
   101510   int addrSortIndex;    /* Address of the OP_SorterOpen or OP_OpenEphemeral */
   101511   u8 sortFlags;         /* Zero or more SORTFLAG_* bits */
   101512 };
   101513 #define SORTFLAG_UseSorter  0x01   /* Use SorterOpen instead of OpenEphemeral */
   101514 
   101515 /*
   101516 ** Delete all the content of a Select structure but do not deallocate
   101517 ** the select structure itself.
   101518 */
   101519 static void clearSelect(sqlite3 *db, Select *p){
   101520   sqlite3ExprListDelete(db, p->pEList);
   101521   sqlite3SrcListDelete(db, p->pSrc);
   101522   sqlite3ExprDelete(db, p->pWhere);
   101523   sqlite3ExprListDelete(db, p->pGroupBy);
   101524   sqlite3ExprDelete(db, p->pHaving);
   101525   sqlite3ExprListDelete(db, p->pOrderBy);
   101526   sqlite3SelectDelete(db, p->pPrior);
   101527   sqlite3ExprDelete(db, p->pLimit);
   101528   sqlite3ExprDelete(db, p->pOffset);
   101529   sqlite3WithDelete(db, p->pWith);
   101530 }
   101531 
   101532 /*
   101533 ** Initialize a SelectDest structure.
   101534 */
   101535 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
   101536   pDest->eDest = (u8)eDest;
   101537   pDest->iSDParm = iParm;
   101538   pDest->affSdst = 0;
   101539   pDest->iSdst = 0;
   101540   pDest->nSdst = 0;
   101541 }
   101542 
   101543 
   101544 /*
   101545 ** Allocate a new Select structure and return a pointer to that
   101546 ** structure.
   101547 */
   101548 SQLITE_PRIVATE Select *sqlite3SelectNew(
   101549   Parse *pParse,        /* Parsing context */
   101550   ExprList *pEList,     /* which columns to include in the result */
   101551   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
   101552   Expr *pWhere,         /* the WHERE clause */
   101553   ExprList *pGroupBy,   /* the GROUP BY clause */
   101554   Expr *pHaving,        /* the HAVING clause */
   101555   ExprList *pOrderBy,   /* the ORDER BY clause */
   101556   u16 selFlags,         /* Flag parameters, such as SF_Distinct */
   101557   Expr *pLimit,         /* LIMIT value.  NULL means not used */
   101558   Expr *pOffset         /* OFFSET value.  NULL means no offset */
   101559 ){
   101560   Select *pNew;
   101561   Select standin;
   101562   sqlite3 *db = pParse->db;
   101563   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
   101564   assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
   101565   if( pNew==0 ){
   101566     assert( db->mallocFailed );
   101567     pNew = &standin;
   101568     memset(pNew, 0, sizeof(*pNew));
   101569   }
   101570   if( pEList==0 ){
   101571     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
   101572   }
   101573   pNew->pEList = pEList;
   101574   if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
   101575   pNew->pSrc = pSrc;
   101576   pNew->pWhere = pWhere;
   101577   pNew->pGroupBy = pGroupBy;
   101578   pNew->pHaving = pHaving;
   101579   pNew->pOrderBy = pOrderBy;
   101580   pNew->selFlags = selFlags;
   101581   pNew->op = TK_SELECT;
   101582   pNew->pLimit = pLimit;
   101583   pNew->pOffset = pOffset;
   101584   assert( pOffset==0 || pLimit!=0 );
   101585   pNew->addrOpenEphm[0] = -1;
   101586   pNew->addrOpenEphm[1] = -1;
   101587   if( db->mallocFailed ) {
   101588     clearSelect(db, pNew);
   101589     if( pNew!=&standin ) sqlite3DbFree(db, pNew);
   101590     pNew = 0;
   101591   }else{
   101592     assert( pNew->pSrc!=0 || pParse->nErr>0 );
   101593   }
   101594   assert( pNew!=&standin );
   101595   return pNew;
   101596 }
   101597 
   101598 /*
   101599 ** Delete the given Select structure and all of its substructures.
   101600 */
   101601 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
   101602   if( p ){
   101603     clearSelect(db, p);
   101604     sqlite3DbFree(db, p);
   101605   }
   101606 }
   101607 
   101608 /*
   101609 ** Return a pointer to the right-most SELECT statement in a compound.
   101610 */
   101611 static Select *findRightmost(Select *p){
   101612   while( p->pNext ) p = p->pNext;
   101613   return p;
   101614 }
   101615 
   101616 /*
   101617 ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
   101618 ** type of join.  Return an integer constant that expresses that type
   101619 ** in terms of the following bit values:
   101620 **
   101621 **     JT_INNER
   101622 **     JT_CROSS
   101623 **     JT_OUTER
   101624 **     JT_NATURAL
   101625 **     JT_LEFT
   101626 **     JT_RIGHT
   101627 **
   101628 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
   101629 **
   101630 ** If an illegal or unsupported join type is seen, then still return
   101631 ** a join type, but put an error in the pParse structure.
   101632 */
   101633 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
   101634   int jointype = 0;
   101635   Token *apAll[3];
   101636   Token *p;
   101637                              /*   0123456789 123456789 123456789 123 */
   101638   static const char zKeyText[] = "naturaleftouterightfullinnercross";
   101639   static const struct {
   101640     u8 i;        /* Beginning of keyword text in zKeyText[] */
   101641     u8 nChar;    /* Length of the keyword in characters */
   101642     u8 code;     /* Join type mask */
   101643   } aKeyword[] = {
   101644     /* natural */ { 0,  7, JT_NATURAL                },
   101645     /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
   101646     /* outer   */ { 10, 5, JT_OUTER                  },
   101647     /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
   101648     /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
   101649     /* inner   */ { 23, 5, JT_INNER                  },
   101650     /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
   101651   };
   101652   int i, j;
   101653   apAll[0] = pA;
   101654   apAll[1] = pB;
   101655   apAll[2] = pC;
   101656   for(i=0; i<3 && apAll[i]; i++){
   101657     p = apAll[i];
   101658     for(j=0; j<ArraySize(aKeyword); j++){
   101659       if( p->n==aKeyword[j].nChar
   101660           && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
   101661         jointype |= aKeyword[j].code;
   101662         break;
   101663       }
   101664     }
   101665     testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
   101666     if( j>=ArraySize(aKeyword) ){
   101667       jointype |= JT_ERROR;
   101668       break;
   101669     }
   101670   }
   101671   if(
   101672      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
   101673      (jointype & JT_ERROR)!=0
   101674   ){
   101675     const char *zSp = " ";
   101676     assert( pB!=0 );
   101677     if( pC==0 ){ zSp++; }
   101678     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
   101679        "%T %T%s%T", pA, pB, zSp, pC);
   101680     jointype = JT_INNER;
   101681   }else if( (jointype & JT_OUTER)!=0
   101682          && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
   101683     sqlite3ErrorMsg(pParse,
   101684       "RIGHT and FULL OUTER JOINs are not currently supported");
   101685     jointype = JT_INNER;
   101686   }
   101687   return jointype;
   101688 }
   101689 
   101690 /*
   101691 ** Return the index of a column in a table.  Return -1 if the column
   101692 ** is not contained in the table.
   101693 */
   101694 static int columnIndex(Table *pTab, const char *zCol){
   101695   int i;
   101696   for(i=0; i<pTab->nCol; i++){
   101697     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
   101698   }
   101699   return -1;
   101700 }
   101701 
   101702 /*
   101703 ** Search the first N tables in pSrc, from left to right, looking for a
   101704 ** table that has a column named zCol.
   101705 **
   101706 ** When found, set *piTab and *piCol to the table index and column index
   101707 ** of the matching column and return TRUE.
   101708 **
   101709 ** If not found, return FALSE.
   101710 */
   101711 static int tableAndColumnIndex(
   101712   SrcList *pSrc,       /* Array of tables to search */
   101713   int N,               /* Number of tables in pSrc->a[] to search */
   101714   const char *zCol,    /* Name of the column we are looking for */
   101715   int *piTab,          /* Write index of pSrc->a[] here */
   101716   int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
   101717 ){
   101718   int i;               /* For looping over tables in pSrc */
   101719   int iCol;            /* Index of column matching zCol */
   101720 
   101721   assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
   101722   for(i=0; i<N; i++){
   101723     iCol = columnIndex(pSrc->a[i].pTab, zCol);
   101724     if( iCol>=0 ){
   101725       if( piTab ){
   101726         *piTab = i;
   101727         *piCol = iCol;
   101728       }
   101729       return 1;
   101730     }
   101731   }
   101732   return 0;
   101733 }
   101734 
   101735 /*
   101736 ** This function is used to add terms implied by JOIN syntax to the
   101737 ** WHERE clause expression of a SELECT statement. The new term, which
   101738 ** is ANDed with the existing WHERE clause, is of the form:
   101739 **
   101740 **    (tab1.col1 = tab2.col2)
   101741 **
   101742 ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
   101743 ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
   101744 ** column iColRight of tab2.
   101745 */
   101746 static void addWhereTerm(
   101747   Parse *pParse,                  /* Parsing context */
   101748   SrcList *pSrc,                  /* List of tables in FROM clause */
   101749   int iLeft,                      /* Index of first table to join in pSrc */
   101750   int iColLeft,                   /* Index of column in first table */
   101751   int iRight,                     /* Index of second table in pSrc */
   101752   int iColRight,                  /* Index of column in second table */
   101753   int isOuterJoin,                /* True if this is an OUTER join */
   101754   Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
   101755 ){
   101756   sqlite3 *db = pParse->db;
   101757   Expr *pE1;
   101758   Expr *pE2;
   101759   Expr *pEq;
   101760 
   101761   assert( iLeft<iRight );
   101762   assert( pSrc->nSrc>iRight );
   101763   assert( pSrc->a[iLeft].pTab );
   101764   assert( pSrc->a[iRight].pTab );
   101765 
   101766   pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
   101767   pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
   101768 
   101769   pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
   101770   if( pEq && isOuterJoin ){
   101771     ExprSetProperty(pEq, EP_FromJoin);
   101772     assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
   101773     ExprSetVVAProperty(pEq, EP_NoReduce);
   101774     pEq->iRightJoinTable = (i16)pE2->iTable;
   101775   }
   101776   *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
   101777 }
   101778 
   101779 /*
   101780 ** Set the EP_FromJoin property on all terms of the given expression.
   101781 ** And set the Expr.iRightJoinTable to iTable for every term in the
   101782 ** expression.
   101783 **
   101784 ** The EP_FromJoin property is used on terms of an expression to tell
   101785 ** the LEFT OUTER JOIN processing logic that this term is part of the
   101786 ** join restriction specified in the ON or USING clause and not a part
   101787 ** of the more general WHERE clause.  These terms are moved over to the
   101788 ** WHERE clause during join processing but we need to remember that they
   101789 ** originated in the ON or USING clause.
   101790 **
   101791 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
   101792 ** expression depends on table iRightJoinTable even if that table is not
   101793 ** explicitly mentioned in the expression.  That information is needed
   101794 ** for cases like this:
   101795 **
   101796 **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
   101797 **
   101798 ** The where clause needs to defer the handling of the t1.x=5
   101799 ** term until after the t2 loop of the join.  In that way, a
   101800 ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
   101801 ** defer the handling of t1.x=5, it will be processed immediately
   101802 ** after the t1 loop and rows with t1.x!=5 will never appear in
   101803 ** the output, which is incorrect.
   101804 */
   101805 static void setJoinExpr(Expr *p, int iTable){
   101806   while( p ){
   101807     ExprSetProperty(p, EP_FromJoin);
   101808     assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
   101809     ExprSetVVAProperty(p, EP_NoReduce);
   101810     p->iRightJoinTable = (i16)iTable;
   101811     setJoinExpr(p->pLeft, iTable);
   101812     p = p->pRight;
   101813   }
   101814 }
   101815 
   101816 /*
   101817 ** This routine processes the join information for a SELECT statement.
   101818 ** ON and USING clauses are converted into extra terms of the WHERE clause.
   101819 ** NATURAL joins also create extra WHERE clause terms.
   101820 **
   101821 ** The terms of a FROM clause are contained in the Select.pSrc structure.
   101822 ** The left most table is the first entry in Select.pSrc.  The right-most
   101823 ** table is the last entry.  The join operator is held in the entry to
   101824 ** the left.  Thus entry 0 contains the join operator for the join between
   101825 ** entries 0 and 1.  Any ON or USING clauses associated with the join are
   101826 ** also attached to the left entry.
   101827 **
   101828 ** This routine returns the number of errors encountered.
   101829 */
   101830 static int sqliteProcessJoin(Parse *pParse, Select *p){
   101831   SrcList *pSrc;                  /* All tables in the FROM clause */
   101832   int i, j;                       /* Loop counters */
   101833   struct SrcList_item *pLeft;     /* Left table being joined */
   101834   struct SrcList_item *pRight;    /* Right table being joined */
   101835 
   101836   pSrc = p->pSrc;
   101837   pLeft = &pSrc->a[0];
   101838   pRight = &pLeft[1];
   101839   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
   101840     Table *pLeftTab = pLeft->pTab;
   101841     Table *pRightTab = pRight->pTab;
   101842     int isOuter;
   101843 
   101844     if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
   101845     isOuter = (pRight->jointype & JT_OUTER)!=0;
   101846 
   101847     /* When the NATURAL keyword is present, add WHERE clause terms for
   101848     ** every column that the two tables have in common.
   101849     */
   101850     if( pRight->jointype & JT_NATURAL ){
   101851       if( pRight->pOn || pRight->pUsing ){
   101852         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
   101853            "an ON or USING clause", 0);
   101854         return 1;
   101855       }
   101856       for(j=0; j<pRightTab->nCol; j++){
   101857         char *zName;   /* Name of column in the right table */
   101858         int iLeft;     /* Matching left table */
   101859         int iLeftCol;  /* Matching column in the left table */
   101860 
   101861         zName = pRightTab->aCol[j].zName;
   101862         if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
   101863           addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
   101864                        isOuter, &p->pWhere);
   101865         }
   101866       }
   101867     }
   101868 
   101869     /* Disallow both ON and USING clauses in the same join
   101870     */
   101871     if( pRight->pOn && pRight->pUsing ){
   101872       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
   101873         "clauses in the same join");
   101874       return 1;
   101875     }
   101876 
   101877     /* Add the ON clause to the end of the WHERE clause, connected by
   101878     ** an AND operator.
   101879     */
   101880     if( pRight->pOn ){
   101881       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
   101882       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
   101883       pRight->pOn = 0;
   101884     }
   101885 
   101886     /* Create extra terms on the WHERE clause for each column named
   101887     ** in the USING clause.  Example: If the two tables to be joined are
   101888     ** A and B and the USING clause names X, Y, and Z, then add this
   101889     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
   101890     ** Report an error if any column mentioned in the USING clause is
   101891     ** not contained in both tables to be joined.
   101892     */
   101893     if( pRight->pUsing ){
   101894       IdList *pList = pRight->pUsing;
   101895       for(j=0; j<pList->nId; j++){
   101896         char *zName;     /* Name of the term in the USING clause */
   101897         int iLeft;       /* Table on the left with matching column name */
   101898         int iLeftCol;    /* Column number of matching column on the left */
   101899         int iRightCol;   /* Column number of matching column on the right */
   101900 
   101901         zName = pList->a[j].zName;
   101902         iRightCol = columnIndex(pRightTab, zName);
   101903         if( iRightCol<0
   101904          || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
   101905         ){
   101906           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
   101907             "not present in both tables", zName);
   101908           return 1;
   101909         }
   101910         addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
   101911                      isOuter, &p->pWhere);
   101912       }
   101913     }
   101914   }
   101915   return 0;
   101916 }
   101917 
   101918 /* Forward reference */
   101919 static KeyInfo *keyInfoFromExprList(
   101920   Parse *pParse,       /* Parsing context */
   101921   ExprList *pList,     /* Form the KeyInfo object from this ExprList */
   101922   int iStart,          /* Begin with this column of pList */
   101923   int nExtra           /* Add this many extra columns to the end */
   101924 );
   101925 
   101926 /*
   101927 ** Insert code into "v" that will push the record in register regData
   101928 ** into the sorter.
   101929 */
   101930 static void pushOntoSorter(
   101931   Parse *pParse,         /* Parser context */
   101932   SortCtx *pSort,        /* Information about the ORDER BY clause */
   101933   Select *pSelect,       /* The whole SELECT statement */
   101934   int regData            /* Register holding data to be sorted */
   101935 ){
   101936   Vdbe *v = pParse->pVdbe;
   101937   int nExpr = pSort->pOrderBy->nExpr;
   101938   int regRecord = ++pParse->nMem;
   101939   int regBase = pParse->nMem+1;
   101940   int nOBSat = pSort->nOBSat;
   101941   int op;
   101942 
   101943   pParse->nMem += nExpr+2;        /* nExpr+2 registers allocated at regBase */
   101944   sqlite3ExprCacheClear(pParse);
   101945   sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, 0);
   101946   sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
   101947   sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
   101948   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nExpr+2-nOBSat,regRecord);
   101949   if( nOBSat>0 ){
   101950     int regPrevKey;   /* The first nOBSat columns of the previous row */
   101951     int addrFirst;    /* Address of the OP_IfNot opcode */
   101952     int addrJmp;      /* Address of the OP_Jump opcode */
   101953     VdbeOp *pOp;      /* Opcode that opens the sorter */
   101954     int nKey;         /* Number of sorting key columns, including OP_Sequence */
   101955     KeyInfo *pKI;     /* Original KeyInfo on the sorter table */
   101956 
   101957     regPrevKey = pParse->nMem+1;
   101958     pParse->nMem += pSort->nOBSat;
   101959     nKey = nExpr - pSort->nOBSat + 1;
   101960     addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr); VdbeCoverage(v);
   101961     sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
   101962     pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
   101963     if( pParse->db->mallocFailed ) return;
   101964     pOp->p2 = nKey + 1;
   101965     pKI = pOp->p4.pKeyInfo;
   101966     memset(pKI->aSortOrder, 0, pKI->nField); /* Makes OP_Jump below testable */
   101967     sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
   101968     pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat, 1);
   101969     addrJmp = sqlite3VdbeCurrentAddr(v);
   101970     sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
   101971     pSort->labelBkOut = sqlite3VdbeMakeLabel(v);
   101972     pSort->regReturn = ++pParse->nMem;
   101973     sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
   101974     sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
   101975     sqlite3VdbeJumpHere(v, addrFirst);
   101976     sqlite3VdbeAddOp3(v, OP_Move, regBase, regPrevKey, pSort->nOBSat);
   101977     sqlite3VdbeJumpHere(v, addrJmp);
   101978   }
   101979   if( pSort->sortFlags & SORTFLAG_UseSorter ){
   101980     op = OP_SorterInsert;
   101981   }else{
   101982     op = OP_IdxInsert;
   101983   }
   101984   sqlite3VdbeAddOp2(v, op, pSort->iECursor, regRecord);
   101985   if( pSelect->iLimit ){
   101986     int addr1, addr2;
   101987     int iLimit;
   101988     if( pSelect->iOffset ){
   101989       iLimit = pSelect->iOffset+1;
   101990     }else{
   101991       iLimit = pSelect->iLimit;
   101992     }
   101993     addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit); VdbeCoverage(v);
   101994     sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
   101995     addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
   101996     sqlite3VdbeJumpHere(v, addr1);
   101997     sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor);
   101998     sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor);
   101999     sqlite3VdbeJumpHere(v, addr2);
   102000   }
   102001 }
   102002 
   102003 /*
   102004 ** Add code to implement the OFFSET
   102005 */
   102006 static void codeOffset(
   102007   Vdbe *v,          /* Generate code into this VM */
   102008   int iOffset,      /* Register holding the offset counter */
   102009   int iContinue     /* Jump here to skip the current record */
   102010 ){
   102011   if( iOffset>0 ){
   102012     int addr;
   102013     addr = sqlite3VdbeAddOp3(v, OP_IfNeg, iOffset, 0, -1); VdbeCoverage(v);
   102014     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
   102015     VdbeComment((v, "skip OFFSET records"));
   102016     sqlite3VdbeJumpHere(v, addr);
   102017   }
   102018 }
   102019 
   102020 /*
   102021 ** Add code that will check to make sure the N registers starting at iMem
   102022 ** form a distinct entry.  iTab is a sorting index that holds previously
   102023 ** seen combinations of the N values.  A new entry is made in iTab
   102024 ** if the current N values are new.
   102025 **
   102026 ** A jump to addrRepeat is made and the N+1 values are popped from the
   102027 ** stack if the top N elements are not distinct.
   102028 */
   102029 static void codeDistinct(
   102030   Parse *pParse,     /* Parsing and code generating context */
   102031   int iTab,          /* A sorting index used to test for distinctness */
   102032   int addrRepeat,    /* Jump to here if not distinct */
   102033   int N,             /* Number of elements */
   102034   int iMem           /* First element */
   102035 ){
   102036   Vdbe *v;
   102037   int r1;
   102038 
   102039   v = pParse->pVdbe;
   102040   r1 = sqlite3GetTempReg(pParse);
   102041   sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
   102042   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
   102043   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
   102044   sqlite3ReleaseTempReg(pParse, r1);
   102045 }
   102046 
   102047 #ifndef SQLITE_OMIT_SUBQUERY
   102048 /*
   102049 ** Generate an error message when a SELECT is used within a subexpression
   102050 ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
   102051 ** column.  We do this in a subroutine because the error used to occur
   102052 ** in multiple places.  (The error only occurs in one place now, but we
   102053 ** retain the subroutine to minimize code disruption.)
   102054 */
   102055 static int checkForMultiColumnSelectError(
   102056   Parse *pParse,       /* Parse context. */
   102057   SelectDest *pDest,   /* Destination of SELECT results */
   102058   int nExpr            /* Number of result columns returned by SELECT */
   102059 ){
   102060   int eDest = pDest->eDest;
   102061   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
   102062     sqlite3ErrorMsg(pParse, "only a single result allowed for "
   102063        "a SELECT that is part of an expression");
   102064     return 1;
   102065   }else{
   102066     return 0;
   102067   }
   102068 }
   102069 #endif
   102070 
   102071 /*
   102072 ** This routine generates the code for the inside of the inner loop
   102073 ** of a SELECT.
   102074 **
   102075 ** If srcTab is negative, then the pEList expressions
   102076 ** are evaluated in order to get the data for this row.  If srcTab is
   102077 ** zero or more, then data is pulled from srcTab and pEList is used only
   102078 ** to get number columns and the datatype for each column.
   102079 */
   102080 static void selectInnerLoop(
   102081   Parse *pParse,          /* The parser context */
   102082   Select *p,              /* The complete select statement being coded */
   102083   ExprList *pEList,       /* List of values being extracted */
   102084   int srcTab,             /* Pull data from this table */
   102085   SortCtx *pSort,         /* If not NULL, info on how to process ORDER BY */
   102086   DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
   102087   SelectDest *pDest,      /* How to dispose of the results */
   102088   int iContinue,          /* Jump here to continue with next row */
   102089   int iBreak              /* Jump here to break out of the inner loop */
   102090 ){
   102091   Vdbe *v = pParse->pVdbe;
   102092   int i;
   102093   int hasDistinct;        /* True if the DISTINCT keyword is present */
   102094   int regResult;              /* Start of memory holding result set */
   102095   int eDest = pDest->eDest;   /* How to dispose of results */
   102096   int iParm = pDest->iSDParm; /* First argument to disposal method */
   102097   int nResultCol;             /* Number of result columns */
   102098 
   102099   assert( v );
   102100   assert( pEList!=0 );
   102101   hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
   102102   if( pSort && pSort->pOrderBy==0 ) pSort = 0;
   102103   if( pSort==0 && !hasDistinct ){
   102104     assert( iContinue!=0 );
   102105     codeOffset(v, p->iOffset, iContinue);
   102106   }
   102107 
   102108   /* Pull the requested columns.
   102109   */
   102110   nResultCol = pEList->nExpr;
   102111 
   102112   if( pDest->iSdst==0 ){
   102113     pDest->iSdst = pParse->nMem+1;
   102114     pParse->nMem += nResultCol;
   102115   }else if( pDest->iSdst+nResultCol > pParse->nMem ){
   102116     /* This is an error condition that can result, for example, when a SELECT
   102117     ** on the right-hand side of an INSERT contains more result columns than
   102118     ** there are columns in the table on the left.  The error will be caught
   102119     ** and reported later.  But we need to make sure enough memory is allocated
   102120     ** to avoid other spurious errors in the meantime. */
   102121     pParse->nMem += nResultCol;
   102122   }
   102123   pDest->nSdst = nResultCol;
   102124   regResult = pDest->iSdst;
   102125   if( srcTab>=0 ){
   102126     for(i=0; i<nResultCol; i++){
   102127       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
   102128       VdbeComment((v, "%s", pEList->a[i].zName));
   102129     }
   102130   }else if( eDest!=SRT_Exists ){
   102131     /* If the destination is an EXISTS(...) expression, the actual
   102132     ** values returned by the SELECT are not required.
   102133     */
   102134     sqlite3ExprCodeExprList(pParse, pEList, regResult,
   102135                   (eDest==SRT_Output||eDest==SRT_Coroutine)?SQLITE_ECEL_DUP:0);
   102136   }
   102137 
   102138   /* If the DISTINCT keyword was present on the SELECT statement
   102139   ** and this row has been seen before, then do not make this row
   102140   ** part of the result.
   102141   */
   102142   if( hasDistinct ){
   102143     switch( pDistinct->eTnctType ){
   102144       case WHERE_DISTINCT_ORDERED: {
   102145         VdbeOp *pOp;            /* No longer required OpenEphemeral instr. */
   102146         int iJump;              /* Jump destination */
   102147         int regPrev;            /* Previous row content */
   102148 
   102149         /* Allocate space for the previous row */
   102150         regPrev = pParse->nMem+1;
   102151         pParse->nMem += nResultCol;
   102152 
   102153         /* Change the OP_OpenEphemeral coded earlier to an OP_Null
   102154         ** sets the MEM_Cleared bit on the first register of the
   102155         ** previous value.  This will cause the OP_Ne below to always
   102156         ** fail on the first iteration of the loop even if the first
   102157         ** row is all NULLs.
   102158         */
   102159         sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
   102160         pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
   102161         pOp->opcode = OP_Null;
   102162         pOp->p1 = 1;
   102163         pOp->p2 = regPrev;
   102164 
   102165         iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
   102166         for(i=0; i<nResultCol; i++){
   102167           CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
   102168           if( i<nResultCol-1 ){
   102169             sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
   102170             VdbeCoverage(v);
   102171           }else{
   102172             sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
   102173             VdbeCoverage(v);
   102174            }
   102175           sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
   102176           sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
   102177         }
   102178         assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
   102179         sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
   102180         break;
   102181       }
   102182 
   102183       case WHERE_DISTINCT_UNIQUE: {
   102184         sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
   102185         break;
   102186       }
   102187 
   102188       default: {
   102189         assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
   102190         codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol, regResult);
   102191         break;
   102192       }
   102193     }
   102194     if( pSort==0 ){
   102195       codeOffset(v, p->iOffset, iContinue);
   102196     }
   102197   }
   102198 
   102199   switch( eDest ){
   102200     /* In this mode, write each query result to the key of the temporary
   102201     ** table iParm.
   102202     */
   102203 #ifndef SQLITE_OMIT_COMPOUND_SELECT
   102204     case SRT_Union: {
   102205       int r1;
   102206       r1 = sqlite3GetTempReg(pParse);
   102207       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
   102208       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
   102209       sqlite3ReleaseTempReg(pParse, r1);
   102210       break;
   102211     }
   102212 
   102213     /* Construct a record from the query result, but instead of
   102214     ** saving that record, use it as a key to delete elements from
   102215     ** the temporary table iParm.
   102216     */
   102217     case SRT_Except: {
   102218       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
   102219       break;
   102220     }
   102221 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
   102222 
   102223     /* Store the result as data using a unique key.
   102224     */
   102225     case SRT_Fifo:
   102226     case SRT_DistFifo:
   102227     case SRT_Table:
   102228     case SRT_EphemTab: {
   102229       int r1 = sqlite3GetTempReg(pParse);
   102230       testcase( eDest==SRT_Table );
   102231       testcase( eDest==SRT_EphemTab );
   102232       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
   102233 #ifndef SQLITE_OMIT_CTE
   102234       if( eDest==SRT_DistFifo ){
   102235         /* If the destination is DistFifo, then cursor (iParm+1) is open
   102236         ** on an ephemeral index. If the current row is already present
   102237         ** in the index, do not write it to the output. If not, add the
   102238         ** current row to the index and proceed with writing it to the
   102239         ** output table as well.  */
   102240         int addr = sqlite3VdbeCurrentAddr(v) + 4;
   102241         sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0); VdbeCoverage(v);
   102242         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r1);
   102243         assert( pSort==0 );
   102244       }
   102245 #endif
   102246       if( pSort ){
   102247         pushOntoSorter(pParse, pSort, p, r1);
   102248       }else{
   102249         int r2 = sqlite3GetTempReg(pParse);
   102250         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
   102251         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
   102252         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   102253         sqlite3ReleaseTempReg(pParse, r2);
   102254       }
   102255       sqlite3ReleaseTempReg(pParse, r1);
   102256       break;
   102257     }
   102258 
   102259 #ifndef SQLITE_OMIT_SUBQUERY
   102260     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
   102261     ** then there should be a single item on the stack.  Write this
   102262     ** item into the set table with bogus data.
   102263     */
   102264     case SRT_Set: {
   102265       assert( nResultCol==1 );
   102266       pDest->affSdst =
   102267                   sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
   102268       if( pSort ){
   102269         /* At first glance you would think we could optimize out the
   102270         ** ORDER BY in this case since the order of entries in the set
   102271         ** does not matter.  But there might be a LIMIT clause, in which
   102272         ** case the order does matter */
   102273         pushOntoSorter(pParse, pSort, p, regResult);
   102274       }else{
   102275         int r1 = sqlite3GetTempReg(pParse);
   102276         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
   102277         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
   102278         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
   102279         sqlite3ReleaseTempReg(pParse, r1);
   102280       }
   102281       break;
   102282     }
   102283 
   102284     /* If any row exist in the result set, record that fact and abort.
   102285     */
   102286     case SRT_Exists: {
   102287       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
   102288       /* The LIMIT clause will terminate the loop for us */
   102289       break;
   102290     }
   102291 
   102292     /* If this is a scalar select that is part of an expression, then
   102293     ** store the results in the appropriate memory cell and break out
   102294     ** of the scan loop.
   102295     */
   102296     case SRT_Mem: {
   102297       assert( nResultCol==1 );
   102298       if( pSort ){
   102299         pushOntoSorter(pParse, pSort, p, regResult);
   102300       }else{
   102301         sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
   102302         /* The LIMIT clause will jump out of the loop for us */
   102303       }
   102304       break;
   102305     }
   102306 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
   102307 
   102308     case SRT_Coroutine:       /* Send data to a co-routine */
   102309     case SRT_Output: {        /* Return the results */
   102310       testcase( eDest==SRT_Coroutine );
   102311       testcase( eDest==SRT_Output );
   102312       if( pSort ){
   102313         int r1 = sqlite3GetTempReg(pParse);
   102314         sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
   102315         pushOntoSorter(pParse, pSort, p, r1);
   102316         sqlite3ReleaseTempReg(pParse, r1);
   102317       }else if( eDest==SRT_Coroutine ){
   102318         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
   102319       }else{
   102320         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
   102321         sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
   102322       }
   102323       break;
   102324     }
   102325 
   102326 #ifndef SQLITE_OMIT_CTE
   102327     /* Write the results into a priority queue that is order according to
   102328     ** pDest->pOrderBy (in pSO).  pDest->iSDParm (in iParm) is the cursor for an
   102329     ** index with pSO->nExpr+2 columns.  Build a key using pSO for the first
   102330     ** pSO->nExpr columns, then make sure all keys are unique by adding a
   102331     ** final OP_Sequence column.  The last column is the record as a blob.
   102332     */
   102333     case SRT_DistQueue:
   102334     case SRT_Queue: {
   102335       int nKey;
   102336       int r1, r2, r3;
   102337       int addrTest = 0;
   102338       ExprList *pSO;
   102339       pSO = pDest->pOrderBy;
   102340       assert( pSO );
   102341       nKey = pSO->nExpr;
   102342       r1 = sqlite3GetTempReg(pParse);
   102343       r2 = sqlite3GetTempRange(pParse, nKey+2);
   102344       r3 = r2+nKey+1;
   102345       if( eDest==SRT_DistQueue ){
   102346         /* If the destination is DistQueue, then cursor (iParm+1) is open
   102347         ** on a second ephemeral index that holds all values every previously
   102348         ** added to the queue. */
   102349         addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
   102350                                         regResult, nResultCol);
   102351         VdbeCoverage(v);
   102352       }
   102353       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
   102354       if( eDest==SRT_DistQueue ){
   102355         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
   102356         sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
   102357       }
   102358       for(i=0; i<nKey; i++){
   102359         sqlite3VdbeAddOp2(v, OP_SCopy,
   102360                           regResult + pSO->a[i].u.x.iOrderByCol - 1,
   102361                           r2+i);
   102362       }
   102363       sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
   102364       sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
   102365       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
   102366       if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
   102367       sqlite3ReleaseTempReg(pParse, r1);
   102368       sqlite3ReleaseTempRange(pParse, r2, nKey+2);
   102369       break;
   102370     }
   102371 #endif /* SQLITE_OMIT_CTE */
   102372 
   102373 
   102374 
   102375 #if !defined(SQLITE_OMIT_TRIGGER)
   102376     /* Discard the results.  This is used for SELECT statements inside
   102377     ** the body of a TRIGGER.  The purpose of such selects is to call
   102378     ** user-defined functions that have side effects.  We do not care
   102379     ** about the actual results of the select.
   102380     */
   102381     default: {
   102382       assert( eDest==SRT_Discard );
   102383       break;
   102384     }
   102385 #endif
   102386   }
   102387 
   102388   /* Jump to the end of the loop if the LIMIT is reached.  Except, if
   102389   ** there is a sorter, in which case the sorter has already limited
   102390   ** the output for us.
   102391   */
   102392   if( pSort==0 && p->iLimit ){
   102393     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1); VdbeCoverage(v);
   102394   }
   102395 }
   102396 
   102397 /*
   102398 ** Allocate a KeyInfo object sufficient for an index of N key columns and
   102399 ** X extra columns.
   102400 */
   102401 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
   102402   KeyInfo *p = sqlite3DbMallocZero(0,
   102403                    sizeof(KeyInfo) + (N+X)*(sizeof(CollSeq*)+1));
   102404   if( p ){
   102405     p->aSortOrder = (u8*)&p->aColl[N+X];
   102406     p->nField = (u16)N;
   102407     p->nXField = (u16)X;
   102408     p->enc = ENC(db);
   102409     p->db = db;
   102410     p->nRef = 1;
   102411   }else{
   102412     db->mallocFailed = 1;
   102413   }
   102414   return p;
   102415 }
   102416 
   102417 /*
   102418 ** Deallocate a KeyInfo object
   102419 */
   102420 SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){
   102421   if( p ){
   102422     assert( p->nRef>0 );
   102423     p->nRef--;
   102424     if( p->nRef==0 ) sqlite3DbFree(0, p);
   102425   }
   102426 }
   102427 
   102428 /*
   102429 ** Make a new pointer to a KeyInfo object
   102430 */
   102431 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
   102432   if( p ){
   102433     assert( p->nRef>0 );
   102434     p->nRef++;
   102435   }
   102436   return p;
   102437 }
   102438 
   102439 #ifdef SQLITE_DEBUG
   102440 /*
   102441 ** Return TRUE if a KeyInfo object can be change.  The KeyInfo object
   102442 ** can only be changed if this is just a single reference to the object.
   102443 **
   102444 ** This routine is used only inside of assert() statements.
   102445 */
   102446 SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
   102447 #endif /* SQLITE_DEBUG */
   102448 
   102449 /*
   102450 ** Given an expression list, generate a KeyInfo structure that records
   102451 ** the collating sequence for each expression in that expression list.
   102452 **
   102453 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
   102454 ** KeyInfo structure is appropriate for initializing a virtual index to
   102455 ** implement that clause.  If the ExprList is the result set of a SELECT
   102456 ** then the KeyInfo structure is appropriate for initializing a virtual
   102457 ** index to implement a DISTINCT test.
   102458 **
   102459 ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
   102460 ** function is responsible for seeing that this structure is eventually
   102461 ** freed.
   102462 */
   102463 static KeyInfo *keyInfoFromExprList(
   102464   Parse *pParse,       /* Parsing context */
   102465   ExprList *pList,     /* Form the KeyInfo object from this ExprList */
   102466   int iStart,          /* Begin with this column of pList */
   102467   int nExtra           /* Add this many extra columns to the end */
   102468 ){
   102469   int nExpr;
   102470   KeyInfo *pInfo;
   102471   struct ExprList_item *pItem;
   102472   sqlite3 *db = pParse->db;
   102473   int i;
   102474 
   102475   nExpr = pList->nExpr;
   102476   pInfo = sqlite3KeyInfoAlloc(db, nExpr+nExtra-iStart, 1);
   102477   if( pInfo ){
   102478     assert( sqlite3KeyInfoIsWriteable(pInfo) );
   102479     for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
   102480       CollSeq *pColl;
   102481       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
   102482       if( !pColl ) pColl = db->pDfltColl;
   102483       pInfo->aColl[i-iStart] = pColl;
   102484       pInfo->aSortOrder[i-iStart] = pItem->sortOrder;
   102485     }
   102486   }
   102487   return pInfo;
   102488 }
   102489 
   102490 #ifndef SQLITE_OMIT_COMPOUND_SELECT
   102491 /*
   102492 ** Name of the connection operator, used for error messages.
   102493 */
   102494 static const char *selectOpName(int id){
   102495   char *z;
   102496   switch( id ){
   102497     case TK_ALL:       z = "UNION ALL";   break;
   102498     case TK_INTERSECT: z = "INTERSECT";   break;
   102499     case TK_EXCEPT:    z = "EXCEPT";      break;
   102500     default:           z = "UNION";       break;
   102501   }
   102502   return z;
   102503 }
   102504 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
   102505 
   102506 #ifndef SQLITE_OMIT_EXPLAIN
   102507 /*
   102508 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
   102509 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
   102510 ** where the caption is of the form:
   102511 **
   102512 **   "USE TEMP B-TREE FOR xxx"
   102513 **
   102514 ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
   102515 ** is determined by the zUsage argument.
   102516 */
   102517 static void explainTempTable(Parse *pParse, const char *zUsage){
   102518   if( pParse->explain==2 ){
   102519     Vdbe *v = pParse->pVdbe;
   102520     char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
   102521     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
   102522   }
   102523 }
   102524 
   102525 /*
   102526 ** Assign expression b to lvalue a. A second, no-op, version of this macro
   102527 ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
   102528 ** in sqlite3Select() to assign values to structure member variables that
   102529 ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
   102530 ** code with #ifndef directives.
   102531 */
   102532 # define explainSetInteger(a, b) a = b
   102533 
   102534 #else
   102535 /* No-op versions of the explainXXX() functions and macros. */
   102536 # define explainTempTable(y,z)
   102537 # define explainSetInteger(y,z)
   102538 #endif
   102539 
   102540 #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
   102541 /*
   102542 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
   102543 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
   102544 ** where the caption is of one of the two forms:
   102545 **
   102546 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
   102547 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
   102548 **
   102549 ** where iSub1 and iSub2 are the integers passed as the corresponding
   102550 ** function parameters, and op is the text representation of the parameter
   102551 ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
   102552 ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
   102553 ** false, or the second form if it is true.
   102554 */
   102555 static void explainComposite(
   102556   Parse *pParse,                  /* Parse context */
   102557   int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
   102558   int iSub1,                      /* Subquery id 1 */
   102559   int iSub2,                      /* Subquery id 2 */
   102560   int bUseTmp                     /* True if a temp table was used */
   102561 ){
   102562   assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
   102563   if( pParse->explain==2 ){
   102564     Vdbe *v = pParse->pVdbe;
   102565     char *zMsg = sqlite3MPrintf(
   102566         pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
   102567         bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
   102568     );
   102569     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
   102570   }
   102571 }
   102572 #else
   102573 /* No-op versions of the explainXXX() functions and macros. */
   102574 # define explainComposite(v,w,x,y,z)
   102575 #endif
   102576 
   102577 /*
   102578 ** If the inner loop was generated using a non-null pOrderBy argument,
   102579 ** then the results were placed in a sorter.  After the loop is terminated
   102580 ** we need to run the sorter and output the results.  The following
   102581 ** routine generates the code needed to do that.
   102582 */
   102583 static void generateSortTail(
   102584   Parse *pParse,    /* Parsing context */
   102585   Select *p,        /* The SELECT statement */
   102586   SortCtx *pSort,   /* Information on the ORDER BY clause */
   102587   int nColumn,      /* Number of columns of data */
   102588   SelectDest *pDest /* Write the sorted results here */
   102589 ){
   102590   Vdbe *v = pParse->pVdbe;                     /* The prepared statement */
   102591   int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
   102592   int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
   102593   int addr;
   102594   int addrOnce = 0;
   102595   int iTab;
   102596   int pseudoTab = 0;
   102597   ExprList *pOrderBy = pSort->pOrderBy;
   102598   int eDest = pDest->eDest;
   102599   int iParm = pDest->iSDParm;
   102600   int regRow;
   102601   int regRowid;
   102602   int nKey;
   102603 
   102604   if( pSort->labelBkOut ){
   102605     sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
   102606     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrBreak);
   102607     sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
   102608     addrOnce = sqlite3CodeOnce(pParse); VdbeCoverage(v);
   102609   }
   102610   iTab = pSort->iECursor;
   102611   regRow = sqlite3GetTempReg(pParse);
   102612   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
   102613     pseudoTab = pParse->nTab++;
   102614     sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
   102615     regRowid = 0;
   102616   }else{
   102617     regRowid = sqlite3GetTempReg(pParse);
   102618   }
   102619   nKey = pOrderBy->nExpr - pSort->nOBSat;
   102620   if( pSort->sortFlags & SORTFLAG_UseSorter ){
   102621     int regSortOut = ++pParse->nMem;
   102622     int ptab2 = pParse->nTab++;
   102623     sqlite3VdbeAddOp3(v, OP_OpenPseudo, ptab2, regSortOut, nKey+2);
   102624     if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
   102625     addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
   102626     VdbeCoverage(v);
   102627     codeOffset(v, p->iOffset, addrContinue);
   102628     sqlite3VdbeAddOp2(v, OP_SorterData, iTab, regSortOut);
   102629     sqlite3VdbeAddOp3(v, OP_Column, ptab2, nKey+1, regRow);
   102630     sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
   102631   }else{
   102632     if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
   102633     addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
   102634     codeOffset(v, p->iOffset, addrContinue);
   102635     sqlite3VdbeAddOp3(v, OP_Column, iTab, nKey+1, regRow);
   102636   }
   102637   switch( eDest ){
   102638     case SRT_Table:
   102639     case SRT_EphemTab: {
   102640       testcase( eDest==SRT_Table );
   102641       testcase( eDest==SRT_EphemTab );
   102642       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
   102643       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
   102644       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   102645       break;
   102646     }
   102647 #ifndef SQLITE_OMIT_SUBQUERY
   102648     case SRT_Set: {
   102649       assert( nColumn==1 );
   102650       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
   102651                         &pDest->affSdst, 1);
   102652       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
   102653       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
   102654       break;
   102655     }
   102656     case SRT_Mem: {
   102657       assert( nColumn==1 );
   102658       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
   102659       /* The LIMIT clause will terminate the loop for us */
   102660       break;
   102661     }
   102662 #endif
   102663     default: {
   102664       int i;
   102665       assert( eDest==SRT_Output || eDest==SRT_Coroutine );
   102666       testcase( eDest==SRT_Output );
   102667       testcase( eDest==SRT_Coroutine );
   102668       for(i=0; i<nColumn; i++){
   102669         assert( regRow!=pDest->iSdst+i );
   102670         sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iSdst+i);
   102671         if( i==0 ){
   102672           sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
   102673         }
   102674       }
   102675       if( eDest==SRT_Output ){
   102676         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
   102677         sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
   102678       }else{
   102679         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
   102680       }
   102681       break;
   102682     }
   102683   }
   102684   sqlite3ReleaseTempReg(pParse, regRow);
   102685   sqlite3ReleaseTempReg(pParse, regRowid);
   102686 
   102687   /* The bottom of the loop
   102688   */
   102689   sqlite3VdbeResolveLabel(v, addrContinue);
   102690   if( pSort->sortFlags & SORTFLAG_UseSorter ){
   102691     sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
   102692   }else{
   102693     sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
   102694   }
   102695   if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
   102696   sqlite3VdbeResolveLabel(v, addrBreak);
   102697 }
   102698 
   102699 /*
   102700 ** Return a pointer to a string containing the 'declaration type' of the
   102701 ** expression pExpr. The string may be treated as static by the caller.
   102702 **
   102703 ** Also try to estimate the size of the returned value and return that
   102704 ** result in *pEstWidth.
   102705 **
   102706 ** The declaration type is the exact datatype definition extracted from the
   102707 ** original CREATE TABLE statement if the expression is a column. The
   102708 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
   102709 ** is considered a column can be complex in the presence of subqueries. The
   102710 ** result-set expression in all of the following SELECT statements is
   102711 ** considered a column by this function.
   102712 **
   102713 **   SELECT col FROM tbl;
   102714 **   SELECT (SELECT col FROM tbl;
   102715 **   SELECT (SELECT col FROM tbl);
   102716 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
   102717 **
   102718 ** The declaration type for any expression other than a column is NULL.
   102719 **
   102720 ** This routine has either 3 or 6 parameters depending on whether or not
   102721 ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
   102722 */
   102723 #ifdef SQLITE_ENABLE_COLUMN_METADATA
   102724 # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F)
   102725 static const char *columnTypeImpl(
   102726   NameContext *pNC,
   102727   Expr *pExpr,
   102728   const char **pzOrigDb,
   102729   const char **pzOrigTab,
   102730   const char **pzOrigCol,
   102731   u8 *pEstWidth
   102732 ){
   102733   char const *zOrigDb = 0;
   102734   char const *zOrigTab = 0;
   102735   char const *zOrigCol = 0;
   102736 #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
   102737 # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F)
   102738 static const char *columnTypeImpl(
   102739   NameContext *pNC,
   102740   Expr *pExpr,
   102741   u8 *pEstWidth
   102742 ){
   102743 #endif /* !defined(SQLITE_ENABLE_COLUMN_METADATA) */
   102744   char const *zType = 0;
   102745   int j;
   102746   u8 estWidth = 1;
   102747 
   102748   if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
   102749   switch( pExpr->op ){
   102750     case TK_AGG_COLUMN:
   102751     case TK_COLUMN: {
   102752       /* The expression is a column. Locate the table the column is being
   102753       ** extracted from in NameContext.pSrcList. This table may be real
   102754       ** database table or a subquery.
   102755       */
   102756       Table *pTab = 0;            /* Table structure column is extracted from */
   102757       Select *pS = 0;             /* Select the column is extracted from */
   102758       int iCol = pExpr->iColumn;  /* Index of column in pTab */
   102759       testcase( pExpr->op==TK_AGG_COLUMN );
   102760       testcase( pExpr->op==TK_COLUMN );
   102761       while( pNC && !pTab ){
   102762         SrcList *pTabList = pNC->pSrcList;
   102763         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
   102764         if( j<pTabList->nSrc ){
   102765           pTab = pTabList->a[j].pTab;
   102766           pS = pTabList->a[j].pSelect;
   102767         }else{
   102768           pNC = pNC->pNext;
   102769         }
   102770       }
   102771 
   102772       if( pTab==0 ){
   102773         /* At one time, code such as "SELECT new.x" within a trigger would
   102774         ** cause this condition to run.  Since then, we have restructured how
   102775         ** trigger code is generated and so this condition is no longer
   102776         ** possible. However, it can still be true for statements like
   102777         ** the following:
   102778         **
   102779         **   CREATE TABLE t1(col INTEGER);
   102780         **   SELECT (SELECT t1.col) FROM FROM t1;
   102781         **
   102782         ** when columnType() is called on the expression "t1.col" in the
   102783         ** sub-select. In this case, set the column type to NULL, even
   102784         ** though it should really be "INTEGER".
   102785         **
   102786         ** This is not a problem, as the column type of "t1.col" is never
   102787         ** used. When columnType() is called on the expression
   102788         ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
   102789         ** branch below.  */
   102790         break;
   102791       }
   102792 
   102793       assert( pTab && pExpr->pTab==pTab );
   102794       if( pS ){
   102795         /* The "table" is actually a sub-select or a view in the FROM clause
   102796         ** of the SELECT statement. Return the declaration type and origin
   102797         ** data for the result-set column of the sub-select.
   102798         */
   102799         if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
   102800           /* If iCol is less than zero, then the expression requests the
   102801           ** rowid of the sub-select or view. This expression is legal (see
   102802           ** test case misc2.2.2) - it always evaluates to NULL.
   102803           */
   102804           NameContext sNC;
   102805           Expr *p = pS->pEList->a[iCol].pExpr;
   102806           sNC.pSrcList = pS->pSrc;
   102807           sNC.pNext = pNC;
   102808           sNC.pParse = pNC->pParse;
   102809           zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth);
   102810         }
   102811       }else if( pTab->pSchema ){
   102812         /* A real table */
   102813         assert( !pS );
   102814         if( iCol<0 ) iCol = pTab->iPKey;
   102815         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
   102816 #ifdef SQLITE_ENABLE_COLUMN_METADATA
   102817         if( iCol<0 ){
   102818           zType = "INTEGER";
   102819           zOrigCol = "rowid";
   102820         }else{
   102821           zType = pTab->aCol[iCol].zType;
   102822           zOrigCol = pTab->aCol[iCol].zName;
   102823           estWidth = pTab->aCol[iCol].szEst;
   102824         }
   102825         zOrigTab = pTab->zName;
   102826         if( pNC->pParse ){
   102827           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
   102828           zOrigDb = pNC->pParse->db->aDb[iDb].zName;
   102829         }
   102830 #else
   102831         if( iCol<0 ){
   102832           zType = "INTEGER";
   102833         }else{
   102834           zType = pTab->aCol[iCol].zType;
   102835           estWidth = pTab->aCol[iCol].szEst;
   102836         }
   102837 #endif
   102838       }
   102839       break;
   102840     }
   102841 #ifndef SQLITE_OMIT_SUBQUERY
   102842     case TK_SELECT: {
   102843       /* The expression is a sub-select. Return the declaration type and
   102844       ** origin info for the single column in the result set of the SELECT
   102845       ** statement.
   102846       */
   102847       NameContext sNC;
   102848       Select *pS = pExpr->x.pSelect;
   102849       Expr *p = pS->pEList->a[0].pExpr;
   102850       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
   102851       sNC.pSrcList = pS->pSrc;
   102852       sNC.pNext = pNC;
   102853       sNC.pParse = pNC->pParse;
   102854       zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth);
   102855       break;
   102856     }
   102857 #endif
   102858   }
   102859 
   102860 #ifdef SQLITE_ENABLE_COLUMN_METADATA
   102861   if( pzOrigDb ){
   102862     assert( pzOrigTab && pzOrigCol );
   102863     *pzOrigDb = zOrigDb;
   102864     *pzOrigTab = zOrigTab;
   102865     *pzOrigCol = zOrigCol;
   102866   }
   102867 #endif
   102868   if( pEstWidth ) *pEstWidth = estWidth;
   102869   return zType;
   102870 }
   102871 
   102872 /*
   102873 ** Generate code that will tell the VDBE the declaration types of columns
   102874 ** in the result set.
   102875 */
   102876 static void generateColumnTypes(
   102877   Parse *pParse,      /* Parser context */
   102878   SrcList *pTabList,  /* List of tables */
   102879   ExprList *pEList    /* Expressions defining the result set */
   102880 ){
   102881 #ifndef SQLITE_OMIT_DECLTYPE
   102882   Vdbe *v = pParse->pVdbe;
   102883   int i;
   102884   NameContext sNC;
   102885   sNC.pSrcList = pTabList;
   102886   sNC.pParse = pParse;
   102887   for(i=0; i<pEList->nExpr; i++){
   102888     Expr *p = pEList->a[i].pExpr;
   102889     const char *zType;
   102890 #ifdef SQLITE_ENABLE_COLUMN_METADATA
   102891     const char *zOrigDb = 0;
   102892     const char *zOrigTab = 0;
   102893     const char *zOrigCol = 0;
   102894     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0);
   102895 
   102896     /* The vdbe must make its own copy of the column-type and other
   102897     ** column specific strings, in case the schema is reset before this
   102898     ** virtual machine is deleted.
   102899     */
   102900     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
   102901     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
   102902     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
   102903 #else
   102904     zType = columnType(&sNC, p, 0, 0, 0, 0);
   102905 #endif
   102906     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
   102907   }
   102908 #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
   102909 }
   102910 
   102911 /*
   102912 ** Generate code that will tell the VDBE the names of columns
   102913 ** in the result set.  This information is used to provide the
   102914 ** azCol[] values in the callback.
   102915 */
   102916 static void generateColumnNames(
   102917   Parse *pParse,      /* Parser context */
   102918   SrcList *pTabList,  /* List of tables */
   102919   ExprList *pEList    /* Expressions defining the result set */
   102920 ){
   102921   Vdbe *v = pParse->pVdbe;
   102922   int i, j;
   102923   sqlite3 *db = pParse->db;
   102924   int fullNames, shortNames;
   102925 
   102926 #ifndef SQLITE_OMIT_EXPLAIN
   102927   /* If this is an EXPLAIN, skip this step */
   102928   if( pParse->explain ){
   102929     return;
   102930   }
   102931 #endif
   102932 
   102933   if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
   102934   pParse->colNamesSet = 1;
   102935   fullNames = (db->flags & SQLITE_FullColNames)!=0;
   102936   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
   102937   sqlite3VdbeSetNumCols(v, pEList->nExpr);
   102938   for(i=0; i<pEList->nExpr; i++){
   102939     Expr *p;
   102940     p = pEList->a[i].pExpr;
   102941     if( NEVER(p==0) ) continue;
   102942     if( pEList->a[i].zName ){
   102943       char *zName = pEList->a[i].zName;
   102944       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
   102945     }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
   102946       Table *pTab;
   102947       char *zCol;
   102948       int iCol = p->iColumn;
   102949       for(j=0; ALWAYS(j<pTabList->nSrc); j++){
   102950         if( pTabList->a[j].iCursor==p->iTable ) break;
   102951       }
   102952       assert( j<pTabList->nSrc );
   102953       pTab = pTabList->a[j].pTab;
   102954       if( iCol<0 ) iCol = pTab->iPKey;
   102955       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
   102956       if( iCol<0 ){
   102957         zCol = "rowid";
   102958       }else{
   102959         zCol = pTab->aCol[iCol].zName;
   102960       }
   102961       if( !shortNames && !fullNames ){
   102962         sqlite3VdbeSetColName(v, i, COLNAME_NAME,
   102963             sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
   102964       }else if( fullNames ){
   102965         char *zName = 0;
   102966         zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
   102967         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
   102968       }else{
   102969         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
   102970       }
   102971     }else{
   102972       const char *z = pEList->a[i].zSpan;
   102973       z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
   102974       sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
   102975     }
   102976   }
   102977   generateColumnTypes(pParse, pTabList, pEList);
   102978 }
   102979 
   102980 /*
   102981 ** Given a an expression list (which is really the list of expressions
   102982 ** that form the result set of a SELECT statement) compute appropriate
   102983 ** column names for a table that would hold the expression list.
   102984 **
   102985 ** All column names will be unique.
   102986 **
   102987 ** Only the column names are computed.  Column.zType, Column.zColl,
   102988 ** and other fields of Column are zeroed.
   102989 **
   102990 ** Return SQLITE_OK on success.  If a memory allocation error occurs,
   102991 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
   102992 */
   102993 static int selectColumnsFromExprList(
   102994   Parse *pParse,          /* Parsing context */
   102995   ExprList *pEList,       /* Expr list from which to derive column names */
   102996   i16 *pnCol,             /* Write the number of columns here */
   102997   Column **paCol          /* Write the new column list here */
   102998 ){
   102999   sqlite3 *db = pParse->db;   /* Database connection */
   103000   int i, j;                   /* Loop counters */
   103001   int cnt;                    /* Index added to make the name unique */
   103002   Column *aCol, *pCol;        /* For looping over result columns */
   103003   int nCol;                   /* Number of columns in the result set */
   103004   Expr *p;                    /* Expression for a single result column */
   103005   char *zName;                /* Column name */
   103006   int nName;                  /* Size of name in zName[] */
   103007 
   103008   if( pEList ){
   103009     nCol = pEList->nExpr;
   103010     aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
   103011     testcase( aCol==0 );
   103012   }else{
   103013     nCol = 0;
   103014     aCol = 0;
   103015   }
   103016   *pnCol = nCol;
   103017   *paCol = aCol;
   103018 
   103019   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
   103020     /* Get an appropriate name for the column
   103021     */
   103022     p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
   103023     if( (zName = pEList->a[i].zName)!=0 ){
   103024       /* If the column contains an "AS <name>" phrase, use <name> as the name */
   103025       zName = sqlite3DbStrDup(db, zName);
   103026     }else{
   103027       Expr *pColExpr = p;  /* The expression that is the result column name */
   103028       Table *pTab;         /* Table associated with this expression */
   103029       while( pColExpr->op==TK_DOT ){
   103030         pColExpr = pColExpr->pRight;
   103031         assert( pColExpr!=0 );
   103032       }
   103033       if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
   103034         /* For columns use the column name name */
   103035         int iCol = pColExpr->iColumn;
   103036         pTab = pColExpr->pTab;
   103037         if( iCol<0 ) iCol = pTab->iPKey;
   103038         zName = sqlite3MPrintf(db, "%s",
   103039                  iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
   103040       }else if( pColExpr->op==TK_ID ){
   103041         assert( !ExprHasProperty(pColExpr, EP_IntValue) );
   103042         zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
   103043       }else{
   103044         /* Use the original text of the column expression as its name */
   103045         zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
   103046       }
   103047     }
   103048     if( db->mallocFailed ){
   103049       sqlite3DbFree(db, zName);
   103050       break;
   103051     }
   103052 
   103053     /* Make sure the column name is unique.  If the name is not unique,
   103054     ** append a integer to the name so that it becomes unique.
   103055     */
   103056     nName = sqlite3Strlen30(zName);
   103057     for(j=cnt=0; j<i; j++){
   103058       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
   103059         char *zNewName;
   103060         int k;
   103061         for(k=nName-1; k>1 && sqlite3Isdigit(zName[k]); k--){}
   103062         if( k>=0 && zName[k]==':' ) nName = k;
   103063         zName[nName] = 0;
   103064         zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
   103065         sqlite3DbFree(db, zName);
   103066         zName = zNewName;
   103067         j = -1;
   103068         if( zName==0 ) break;
   103069       }
   103070     }
   103071     pCol->zName = zName;
   103072   }
   103073   if( db->mallocFailed ){
   103074     for(j=0; j<i; j++){
   103075       sqlite3DbFree(db, aCol[j].zName);
   103076     }
   103077     sqlite3DbFree(db, aCol);
   103078     *paCol = 0;
   103079     *pnCol = 0;
   103080     return SQLITE_NOMEM;
   103081   }
   103082   return SQLITE_OK;
   103083 }
   103084 
   103085 /*
   103086 ** Add type and collation information to a column list based on
   103087 ** a SELECT statement.
   103088 **
   103089 ** The column list presumably came from selectColumnNamesFromExprList().
   103090 ** The column list has only names, not types or collations.  This
   103091 ** routine goes through and adds the types and collations.
   103092 **
   103093 ** This routine requires that all identifiers in the SELECT
   103094 ** statement be resolved.
   103095 */
   103096 static void selectAddColumnTypeAndCollation(
   103097   Parse *pParse,        /* Parsing contexts */
   103098   Table *pTab,          /* Add column type information to this table */
   103099   Select *pSelect       /* SELECT used to determine types and collations */
   103100 ){
   103101   sqlite3 *db = pParse->db;
   103102   NameContext sNC;
   103103   Column *pCol;
   103104   CollSeq *pColl;
   103105   int i;
   103106   Expr *p;
   103107   struct ExprList_item *a;
   103108   u64 szAll = 0;
   103109 
   103110   assert( pSelect!=0 );
   103111   assert( (pSelect->selFlags & SF_Resolved)!=0 );
   103112   assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
   103113   if( db->mallocFailed ) return;
   103114   memset(&sNC, 0, sizeof(sNC));
   103115   sNC.pSrcList = pSelect->pSrc;
   103116   a = pSelect->pEList->a;
   103117   for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
   103118     p = a[i].pExpr;
   103119     pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p,0,0,0, &pCol->szEst));
   103120     szAll += pCol->szEst;
   103121     pCol->affinity = sqlite3ExprAffinity(p);
   103122     if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
   103123     pColl = sqlite3ExprCollSeq(pParse, p);
   103124     if( pColl ){
   103125       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
   103126     }
   103127   }
   103128   pTab->szTabRow = sqlite3LogEst(szAll*4);
   103129 }
   103130 
   103131 /*
   103132 ** Given a SELECT statement, generate a Table structure that describes
   103133 ** the result set of that SELECT.
   103134 */
   103135 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
   103136   Table *pTab;
   103137   sqlite3 *db = pParse->db;
   103138   int savedFlags;
   103139 
   103140   savedFlags = db->flags;
   103141   db->flags &= ~SQLITE_FullColNames;
   103142   db->flags |= SQLITE_ShortColNames;
   103143   sqlite3SelectPrep(pParse, pSelect, 0);
   103144   if( pParse->nErr ) return 0;
   103145   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
   103146   db->flags = savedFlags;
   103147   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
   103148   if( pTab==0 ){
   103149     return 0;
   103150   }
   103151   /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
   103152   ** is disabled */
   103153   assert( db->lookaside.bEnabled==0 );
   103154   pTab->nRef = 1;
   103155   pTab->zName = 0;
   103156   pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
   103157   selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
   103158   selectAddColumnTypeAndCollation(pParse, pTab, pSelect);
   103159   pTab->iPKey = -1;
   103160   if( db->mallocFailed ){
   103161     sqlite3DeleteTable(db, pTab);
   103162     return 0;
   103163   }
   103164   return pTab;
   103165 }
   103166 
   103167 /*
   103168 ** Get a VDBE for the given parser context.  Create a new one if necessary.
   103169 ** If an error occurs, return NULL and leave a message in pParse.
   103170 */
   103171 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
   103172   Vdbe *v = pParse->pVdbe;
   103173   if( v==0 ){
   103174     v = pParse->pVdbe = sqlite3VdbeCreate(pParse);
   103175     if( v ) sqlite3VdbeAddOp0(v, OP_Init);
   103176     if( pParse->pToplevel==0
   103177      && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
   103178     ){
   103179       pParse->okConstFactor = 1;
   103180     }
   103181 
   103182   }
   103183   return v;
   103184 }
   103185 
   103186 
   103187 /*
   103188 ** Compute the iLimit and iOffset fields of the SELECT based on the
   103189 ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
   103190 ** that appear in the original SQL statement after the LIMIT and OFFSET
   103191 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
   103192 ** are the integer memory register numbers for counters used to compute
   103193 ** the limit and offset.  If there is no limit and/or offset, then
   103194 ** iLimit and iOffset are negative.
   103195 **
   103196 ** This routine changes the values of iLimit and iOffset only if
   103197 ** a limit or offset is defined by pLimit and pOffset.  iLimit and
   103198 ** iOffset should have been preset to appropriate default values (zero)
   103199 ** prior to calling this routine.
   103200 **
   103201 ** The iOffset register (if it exists) is initialized to the value
   103202 ** of the OFFSET.  The iLimit register is initialized to LIMIT.  Register
   103203 ** iOffset+1 is initialized to LIMIT+OFFSET.
   103204 **
   103205 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
   103206 ** redefined.  The UNION ALL operator uses this property to force
   103207 ** the reuse of the same limit and offset registers across multiple
   103208 ** SELECT statements.
   103209 */
   103210 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
   103211   Vdbe *v = 0;
   103212   int iLimit = 0;
   103213   int iOffset;
   103214   int addr1, n;
   103215   if( p->iLimit ) return;
   103216 
   103217   /*
   103218   ** "LIMIT -1" always shows all rows.  There is some
   103219   ** controversy about what the correct behavior should be.
   103220   ** The current implementation interprets "LIMIT 0" to mean
   103221   ** no rows.
   103222   */
   103223   sqlite3ExprCacheClear(pParse);
   103224   assert( p->pOffset==0 || p->pLimit!=0 );
   103225   if( p->pLimit ){
   103226     p->iLimit = iLimit = ++pParse->nMem;
   103227     v = sqlite3GetVdbe(pParse);
   103228     assert( v!=0 );
   103229     if( sqlite3ExprIsInteger(p->pLimit, &n) ){
   103230       sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
   103231       VdbeComment((v, "LIMIT counter"));
   103232       if( n==0 ){
   103233         sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
   103234       }else if( n>=0 && p->nSelectRow>(u64)n ){
   103235         p->nSelectRow = n;
   103236       }
   103237     }else{
   103238       sqlite3ExprCode(pParse, p->pLimit, iLimit);
   103239       sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
   103240       VdbeComment((v, "LIMIT counter"));
   103241       sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak); VdbeCoverage(v);
   103242     }
   103243     if( p->pOffset ){
   103244       p->iOffset = iOffset = ++pParse->nMem;
   103245       pParse->nMem++;   /* Allocate an extra register for limit+offset */
   103246       sqlite3ExprCode(pParse, p->pOffset, iOffset);
   103247       sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
   103248       VdbeComment((v, "OFFSET counter"));
   103249       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset); VdbeCoverage(v);
   103250       sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
   103251       sqlite3VdbeJumpHere(v, addr1);
   103252       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
   103253       VdbeComment((v, "LIMIT+OFFSET"));
   103254       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit); VdbeCoverage(v);
   103255       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
   103256       sqlite3VdbeJumpHere(v, addr1);
   103257     }
   103258   }
   103259 }
   103260 
   103261 #ifndef SQLITE_OMIT_COMPOUND_SELECT
   103262 /*
   103263 ** Return the appropriate collating sequence for the iCol-th column of
   103264 ** the result set for the compound-select statement "p".  Return NULL if
   103265 ** the column has no default collating sequence.
   103266 **
   103267 ** The collating sequence for the compound select is taken from the
   103268 ** left-most term of the select that has a collating sequence.
   103269 */
   103270 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
   103271   CollSeq *pRet;
   103272   if( p->pPrior ){
   103273     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
   103274   }else{
   103275     pRet = 0;
   103276   }
   103277   assert( iCol>=0 );
   103278   if( pRet==0 && iCol<p->pEList->nExpr ){
   103279     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
   103280   }
   103281   return pRet;
   103282 }
   103283 
   103284 /*
   103285 ** The select statement passed as the second parameter is a compound SELECT
   103286 ** with an ORDER BY clause. This function allocates and returns a KeyInfo
   103287 ** structure suitable for implementing the ORDER BY.
   103288 **
   103289 ** Space to hold the KeyInfo structure is obtained from malloc. The calling
   103290 ** function is responsible for ensuring that this structure is eventually
   103291 ** freed.
   103292 */
   103293 static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
   103294   ExprList *pOrderBy = p->pOrderBy;
   103295   int nOrderBy = p->pOrderBy->nExpr;
   103296   sqlite3 *db = pParse->db;
   103297   KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
   103298   if( pRet ){
   103299     int i;
   103300     for(i=0; i<nOrderBy; i++){
   103301       struct ExprList_item *pItem = &pOrderBy->a[i];
   103302       Expr *pTerm = pItem->pExpr;
   103303       CollSeq *pColl;
   103304 
   103305       if( pTerm->flags & EP_Collate ){
   103306         pColl = sqlite3ExprCollSeq(pParse, pTerm);
   103307       }else{
   103308         pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
   103309         if( pColl==0 ) pColl = db->pDfltColl;
   103310         pOrderBy->a[i].pExpr =
   103311           sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
   103312       }
   103313       assert( sqlite3KeyInfoIsWriteable(pRet) );
   103314       pRet->aColl[i] = pColl;
   103315       pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
   103316     }
   103317   }
   103318 
   103319   return pRet;
   103320 }
   103321 
   103322 #ifndef SQLITE_OMIT_CTE
   103323 /*
   103324 ** This routine generates VDBE code to compute the content of a WITH RECURSIVE
   103325 ** query of the form:
   103326 **
   103327 **   <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
   103328 **                         \___________/             \_______________/
   103329 **                           p->pPrior                      p
   103330 **
   103331 **
   103332 ** There is exactly one reference to the recursive-table in the FROM clause
   103333 ** of recursive-query, marked with the SrcList->a[].isRecursive flag.
   103334 **
   103335 ** The setup-query runs once to generate an initial set of rows that go
   103336 ** into a Queue table.  Rows are extracted from the Queue table one by
   103337 ** one.  Each row extracted from Queue is output to pDest.  Then the single
   103338 ** extracted row (now in the iCurrent table) becomes the content of the
   103339 ** recursive-table for a recursive-query run.  The output of the recursive-query
   103340 ** is added back into the Queue table.  Then another row is extracted from Queue
   103341 ** and the iteration continues until the Queue table is empty.
   103342 **
   103343 ** If the compound query operator is UNION then no duplicate rows are ever
   103344 ** inserted into the Queue table.  The iDistinct table keeps a copy of all rows
   103345 ** that have ever been inserted into Queue and causes duplicates to be
   103346 ** discarded.  If the operator is UNION ALL, then duplicates are allowed.
   103347 **
   103348 ** If the query has an ORDER BY, then entries in the Queue table are kept in
   103349 ** ORDER BY order and the first entry is extracted for each cycle.  Without
   103350 ** an ORDER BY, the Queue table is just a FIFO.
   103351 **
   103352 ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
   103353 ** have been output to pDest.  A LIMIT of zero means to output no rows and a
   103354 ** negative LIMIT means to output all rows.  If there is also an OFFSET clause
   103355 ** with a positive value, then the first OFFSET outputs are discarded rather
   103356 ** than being sent to pDest.  The LIMIT count does not begin until after OFFSET
   103357 ** rows have been skipped.
   103358 */
   103359 static void generateWithRecursiveQuery(
   103360   Parse *pParse,        /* Parsing context */
   103361   Select *p,            /* The recursive SELECT to be coded */
   103362   SelectDest *pDest     /* What to do with query results */
   103363 ){
   103364   SrcList *pSrc = p->pSrc;      /* The FROM clause of the recursive query */
   103365   int nCol = p->pEList->nExpr;  /* Number of columns in the recursive table */
   103366   Vdbe *v = pParse->pVdbe;      /* The prepared statement under construction */
   103367   Select *pSetup = p->pPrior;   /* The setup query */
   103368   int addrTop;                  /* Top of the loop */
   103369   int addrCont, addrBreak;      /* CONTINUE and BREAK addresses */
   103370   int iCurrent = 0;             /* The Current table */
   103371   int regCurrent;               /* Register holding Current table */
   103372   int iQueue;                   /* The Queue table */
   103373   int iDistinct = 0;            /* To ensure unique results if UNION */
   103374   int eDest = SRT_Fifo;         /* How to write to Queue */
   103375   SelectDest destQueue;         /* SelectDest targetting the Queue table */
   103376   int i;                        /* Loop counter */
   103377   int rc;                       /* Result code */
   103378   ExprList *pOrderBy;           /* The ORDER BY clause */
   103379   Expr *pLimit, *pOffset;       /* Saved LIMIT and OFFSET */
   103380   int regLimit, regOffset;      /* Registers used by LIMIT and OFFSET */
   103381 
   103382   /* Obtain authorization to do a recursive query */
   103383   if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
   103384 
   103385   /* Process the LIMIT and OFFSET clauses, if they exist */
   103386   addrBreak = sqlite3VdbeMakeLabel(v);
   103387   computeLimitRegisters(pParse, p, addrBreak);
   103388   pLimit = p->pLimit;
   103389   pOffset = p->pOffset;
   103390   regLimit = p->iLimit;
   103391   regOffset = p->iOffset;
   103392   p->pLimit = p->pOffset = 0;
   103393   p->iLimit = p->iOffset = 0;
   103394   pOrderBy = p->pOrderBy;
   103395 
   103396   /* Locate the cursor number of the Current table */
   103397   for(i=0; ALWAYS(i<pSrc->nSrc); i++){
   103398     if( pSrc->a[i].isRecursive ){
   103399       iCurrent = pSrc->a[i].iCursor;
   103400       break;
   103401     }
   103402   }
   103403 
   103404   /* Allocate cursors numbers for Queue and Distinct.  The cursor number for
   103405   ** the Distinct table must be exactly one greater than Queue in order
   103406   ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
   103407   iQueue = pParse->nTab++;
   103408   if( p->op==TK_UNION ){
   103409     eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
   103410     iDistinct = pParse->nTab++;
   103411   }else{
   103412     eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
   103413   }
   103414   sqlite3SelectDestInit(&destQueue, eDest, iQueue);
   103415 
   103416   /* Allocate cursors for Current, Queue, and Distinct. */
   103417   regCurrent = ++pParse->nMem;
   103418   sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
   103419   if( pOrderBy ){
   103420     KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
   103421     sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
   103422                       (char*)pKeyInfo, P4_KEYINFO);
   103423     destQueue.pOrderBy = pOrderBy;
   103424   }else{
   103425     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
   103426   }
   103427   VdbeComment((v, "Queue table"));
   103428   if( iDistinct ){
   103429     p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
   103430     p->selFlags |= SF_UsesEphemeral;
   103431   }
   103432 
   103433   /* Detach the ORDER BY clause from the compound SELECT */
   103434   p->pOrderBy = 0;
   103435 
   103436   /* Store the results of the setup-query in Queue. */
   103437   pSetup->pNext = 0;
   103438   rc = sqlite3Select(pParse, pSetup, &destQueue);
   103439   pSetup->pNext = p;
   103440   if( rc ) goto end_of_recursive_query;
   103441 
   103442   /* Find the next row in the Queue and output that row */
   103443   addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
   103444 
   103445   /* Transfer the next row in Queue over to Current */
   103446   sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
   103447   if( pOrderBy ){
   103448     sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
   103449   }else{
   103450     sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
   103451   }
   103452   sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
   103453 
   103454   /* Output the single row in Current */
   103455   addrCont = sqlite3VdbeMakeLabel(v);
   103456   codeOffset(v, regOffset, addrCont);
   103457   selectInnerLoop(pParse, p, p->pEList, iCurrent,
   103458       0, 0, pDest, addrCont, addrBreak);
   103459   if( regLimit ){
   103460     sqlite3VdbeAddOp3(v, OP_IfZero, regLimit, addrBreak, -1);
   103461     VdbeCoverage(v);
   103462   }
   103463   sqlite3VdbeResolveLabel(v, addrCont);
   103464 
   103465   /* Execute the recursive SELECT taking the single row in Current as
   103466   ** the value for the recursive-table. Store the results in the Queue.
   103467   */
   103468   p->pPrior = 0;
   103469   sqlite3Select(pParse, p, &destQueue);
   103470   assert( p->pPrior==0 );
   103471   p->pPrior = pSetup;
   103472 
   103473   /* Keep running the loop until the Queue is empty */
   103474   sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
   103475   sqlite3VdbeResolveLabel(v, addrBreak);
   103476 
   103477 end_of_recursive_query:
   103478   sqlite3ExprListDelete(pParse->db, p->pOrderBy);
   103479   p->pOrderBy = pOrderBy;
   103480   p->pLimit = pLimit;
   103481   p->pOffset = pOffset;
   103482   return;
   103483 }
   103484 #endif /* SQLITE_OMIT_CTE */
   103485 
   103486 /* Forward references */
   103487 static int multiSelectOrderBy(
   103488   Parse *pParse,        /* Parsing context */
   103489   Select *p,            /* The right-most of SELECTs to be coded */
   103490   SelectDest *pDest     /* What to do with query results */
   103491 );
   103492 
   103493 
   103494 /*
   103495 ** This routine is called to process a compound query form from
   103496 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
   103497 ** INTERSECT
   103498 **
   103499 ** "p" points to the right-most of the two queries.  the query on the
   103500 ** left is p->pPrior.  The left query could also be a compound query
   103501 ** in which case this routine will be called recursively.
   103502 **
   103503 ** The results of the total query are to be written into a destination
   103504 ** of type eDest with parameter iParm.
   103505 **
   103506 ** Example 1:  Consider a three-way compound SQL statement.
   103507 **
   103508 **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
   103509 **
   103510 ** This statement is parsed up as follows:
   103511 **
   103512 **     SELECT c FROM t3
   103513 **      |
   103514 **      `----->  SELECT b FROM t2
   103515 **                |
   103516 **                `------>  SELECT a FROM t1
   103517 **
   103518 ** The arrows in the diagram above represent the Select.pPrior pointer.
   103519 ** So if this routine is called with p equal to the t3 query, then
   103520 ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
   103521 **
   103522 ** Notice that because of the way SQLite parses compound SELECTs, the
   103523 ** individual selects always group from left to right.
   103524 */
   103525 static int multiSelect(
   103526   Parse *pParse,        /* Parsing context */
   103527   Select *p,            /* The right-most of SELECTs to be coded */
   103528   SelectDest *pDest     /* What to do with query results */
   103529 ){
   103530   int rc = SQLITE_OK;   /* Success code from a subroutine */
   103531   Select *pPrior;       /* Another SELECT immediately to our left */
   103532   Vdbe *v;              /* Generate code to this VDBE */
   103533   SelectDest dest;      /* Alternative data destination */
   103534   Select *pDelete = 0;  /* Chain of simple selects to delete */
   103535   sqlite3 *db;          /* Database connection */
   103536 #ifndef SQLITE_OMIT_EXPLAIN
   103537   int iSub1 = 0;        /* EQP id of left-hand query */
   103538   int iSub2 = 0;        /* EQP id of right-hand query */
   103539 #endif
   103540 
   103541   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
   103542   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
   103543   */
   103544   assert( p && p->pPrior );  /* Calling function guarantees this much */
   103545   assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
   103546   db = pParse->db;
   103547   pPrior = p->pPrior;
   103548   dest = *pDest;
   103549   if( pPrior->pOrderBy ){
   103550     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
   103551       selectOpName(p->op));
   103552     rc = 1;
   103553     goto multi_select_end;
   103554   }
   103555   if( pPrior->pLimit ){
   103556     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
   103557       selectOpName(p->op));
   103558     rc = 1;
   103559     goto multi_select_end;
   103560   }
   103561 
   103562   v = sqlite3GetVdbe(pParse);
   103563   assert( v!=0 );  /* The VDBE already created by calling function */
   103564 
   103565   /* Create the destination temporary table if necessary
   103566   */
   103567   if( dest.eDest==SRT_EphemTab ){
   103568     assert( p->pEList );
   103569     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
   103570     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
   103571     dest.eDest = SRT_Table;
   103572   }
   103573 
   103574   /* Make sure all SELECTs in the statement have the same number of elements
   103575   ** in their result sets.
   103576   */
   103577   assert( p->pEList && pPrior->pEList );
   103578   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
   103579     if( p->selFlags & SF_Values ){
   103580       sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
   103581     }else{
   103582       sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
   103583         " do not have the same number of result columns", selectOpName(p->op));
   103584     }
   103585     rc = 1;
   103586     goto multi_select_end;
   103587   }
   103588 
   103589 #ifndef SQLITE_OMIT_CTE
   103590   if( p->selFlags & SF_Recursive ){
   103591     generateWithRecursiveQuery(pParse, p, &dest);
   103592   }else
   103593 #endif
   103594 
   103595   /* Compound SELECTs that have an ORDER BY clause are handled separately.
   103596   */
   103597   if( p->pOrderBy ){
   103598     return multiSelectOrderBy(pParse, p, pDest);
   103599   }else
   103600 
   103601   /* Generate code for the left and right SELECT statements.
   103602   */
   103603   switch( p->op ){
   103604     case TK_ALL: {
   103605       int addr = 0;
   103606       int nLimit;
   103607       assert( !pPrior->pLimit );
   103608       pPrior->iLimit = p->iLimit;
   103609       pPrior->iOffset = p->iOffset;
   103610       pPrior->pLimit = p->pLimit;
   103611       pPrior->pOffset = p->pOffset;
   103612       explainSetInteger(iSub1, pParse->iNextSelectId);
   103613       rc = sqlite3Select(pParse, pPrior, &dest);
   103614       p->pLimit = 0;
   103615       p->pOffset = 0;
   103616       if( rc ){
   103617         goto multi_select_end;
   103618       }
   103619       p->pPrior = 0;
   103620       p->iLimit = pPrior->iLimit;
   103621       p->iOffset = pPrior->iOffset;
   103622       if( p->iLimit ){
   103623         addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit); VdbeCoverage(v);
   103624         VdbeComment((v, "Jump ahead if LIMIT reached"));
   103625       }
   103626       explainSetInteger(iSub2, pParse->iNextSelectId);
   103627       rc = sqlite3Select(pParse, p, &dest);
   103628       testcase( rc!=SQLITE_OK );
   103629       pDelete = p->pPrior;
   103630       p->pPrior = pPrior;
   103631       p->nSelectRow += pPrior->nSelectRow;
   103632       if( pPrior->pLimit
   103633        && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
   103634        && nLimit>0 && p->nSelectRow > (u64)nLimit
   103635       ){
   103636         p->nSelectRow = nLimit;
   103637       }
   103638       if( addr ){
   103639         sqlite3VdbeJumpHere(v, addr);
   103640       }
   103641       break;
   103642     }
   103643     case TK_EXCEPT:
   103644     case TK_UNION: {
   103645       int unionTab;    /* Cursor number of the temporary table holding result */
   103646       u8 op = 0;       /* One of the SRT_ operations to apply to self */
   103647       int priorOp;     /* The SRT_ operation to apply to prior selects */
   103648       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
   103649       int addr;
   103650       SelectDest uniondest;
   103651 
   103652       testcase( p->op==TK_EXCEPT );
   103653       testcase( p->op==TK_UNION );
   103654       priorOp = SRT_Union;
   103655       if( dest.eDest==priorOp ){
   103656         /* We can reuse a temporary table generated by a SELECT to our
   103657         ** right.
   103658         */
   103659         assert( p->pLimit==0 );      /* Not allowed on leftward elements */
   103660         assert( p->pOffset==0 );     /* Not allowed on leftward elements */
   103661         unionTab = dest.iSDParm;
   103662       }else{
   103663         /* We will need to create our own temporary table to hold the
   103664         ** intermediate results.
   103665         */
   103666         unionTab = pParse->nTab++;
   103667         assert( p->pOrderBy==0 );
   103668         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
   103669         assert( p->addrOpenEphm[0] == -1 );
   103670         p->addrOpenEphm[0] = addr;
   103671         findRightmost(p)->selFlags |= SF_UsesEphemeral;
   103672         assert( p->pEList );
   103673       }
   103674 
   103675       /* Code the SELECT statements to our left
   103676       */
   103677       assert( !pPrior->pOrderBy );
   103678       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
   103679       explainSetInteger(iSub1, pParse->iNextSelectId);
   103680       rc = sqlite3Select(pParse, pPrior, &uniondest);
   103681       if( rc ){
   103682         goto multi_select_end;
   103683       }
   103684 
   103685       /* Code the current SELECT statement
   103686       */
   103687       if( p->op==TK_EXCEPT ){
   103688         op = SRT_Except;
   103689       }else{
   103690         assert( p->op==TK_UNION );
   103691         op = SRT_Union;
   103692       }
   103693       p->pPrior = 0;
   103694       pLimit = p->pLimit;
   103695       p->pLimit = 0;
   103696       pOffset = p->pOffset;
   103697       p->pOffset = 0;
   103698       uniondest.eDest = op;
   103699       explainSetInteger(iSub2, pParse->iNextSelectId);
   103700       rc = sqlite3Select(pParse, p, &uniondest);
   103701       testcase( rc!=SQLITE_OK );
   103702       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
   103703       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
   103704       sqlite3ExprListDelete(db, p->pOrderBy);
   103705       pDelete = p->pPrior;
   103706       p->pPrior = pPrior;
   103707       p->pOrderBy = 0;
   103708       if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
   103709       sqlite3ExprDelete(db, p->pLimit);
   103710       p->pLimit = pLimit;
   103711       p->pOffset = pOffset;
   103712       p->iLimit = 0;
   103713       p->iOffset = 0;
   103714 
   103715       /* Convert the data in the temporary table into whatever form
   103716       ** it is that we currently need.
   103717       */
   103718       assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
   103719       if( dest.eDest!=priorOp ){
   103720         int iCont, iBreak, iStart;
   103721         assert( p->pEList );
   103722         if( dest.eDest==SRT_Output ){
   103723           Select *pFirst = p;
   103724           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
   103725           generateColumnNames(pParse, 0, pFirst->pEList);
   103726         }
   103727         iBreak = sqlite3VdbeMakeLabel(v);
   103728         iCont = sqlite3VdbeMakeLabel(v);
   103729         computeLimitRegisters(pParse, p, iBreak);
   103730         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
   103731         iStart = sqlite3VdbeCurrentAddr(v);
   103732         selectInnerLoop(pParse, p, p->pEList, unionTab,
   103733                         0, 0, &dest, iCont, iBreak);
   103734         sqlite3VdbeResolveLabel(v, iCont);
   103735         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
   103736         sqlite3VdbeResolveLabel(v, iBreak);
   103737         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
   103738       }
   103739       break;
   103740     }
   103741     default: assert( p->op==TK_INTERSECT ); {
   103742       int tab1, tab2;
   103743       int iCont, iBreak, iStart;
   103744       Expr *pLimit, *pOffset;
   103745       int addr;
   103746       SelectDest intersectdest;
   103747       int r1;
   103748 
   103749       /* INTERSECT is different from the others since it requires
   103750       ** two temporary tables.  Hence it has its own case.  Begin
   103751       ** by allocating the tables we will need.
   103752       */
   103753       tab1 = pParse->nTab++;
   103754       tab2 = pParse->nTab++;
   103755       assert( p->pOrderBy==0 );
   103756 
   103757       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
   103758       assert( p->addrOpenEphm[0] == -1 );
   103759       p->addrOpenEphm[0] = addr;
   103760       findRightmost(p)->selFlags |= SF_UsesEphemeral;
   103761       assert( p->pEList );
   103762 
   103763       /* Code the SELECTs to our left into temporary table "tab1".
   103764       */
   103765       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
   103766       explainSetInteger(iSub1, pParse->iNextSelectId);
   103767       rc = sqlite3Select(pParse, pPrior, &intersectdest);
   103768       if( rc ){
   103769         goto multi_select_end;
   103770       }
   103771 
   103772       /* Code the current SELECT into temporary table "tab2"
   103773       */
   103774       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
   103775       assert( p->addrOpenEphm[1] == -1 );
   103776       p->addrOpenEphm[1] = addr;
   103777       p->pPrior = 0;
   103778       pLimit = p->pLimit;
   103779       p->pLimit = 0;
   103780       pOffset = p->pOffset;
   103781       p->pOffset = 0;
   103782       intersectdest.iSDParm = tab2;
   103783       explainSetInteger(iSub2, pParse->iNextSelectId);
   103784       rc = sqlite3Select(pParse, p, &intersectdest);
   103785       testcase( rc!=SQLITE_OK );
   103786       pDelete = p->pPrior;
   103787       p->pPrior = pPrior;
   103788       if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
   103789       sqlite3ExprDelete(db, p->pLimit);
   103790       p->pLimit = pLimit;
   103791       p->pOffset = pOffset;
   103792 
   103793       /* Generate code to take the intersection of the two temporary
   103794       ** tables.
   103795       */
   103796       assert( p->pEList );
   103797       if( dest.eDest==SRT_Output ){
   103798         Select *pFirst = p;
   103799         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
   103800         generateColumnNames(pParse, 0, pFirst->pEList);
   103801       }
   103802       iBreak = sqlite3VdbeMakeLabel(v);
   103803       iCont = sqlite3VdbeMakeLabel(v);
   103804       computeLimitRegisters(pParse, p, iBreak);
   103805       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
   103806       r1 = sqlite3GetTempReg(pParse);
   103807       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
   103808       sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v);
   103809       sqlite3ReleaseTempReg(pParse, r1);
   103810       selectInnerLoop(pParse, p, p->pEList, tab1,
   103811                       0, 0, &dest, iCont, iBreak);
   103812       sqlite3VdbeResolveLabel(v, iCont);
   103813       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
   103814       sqlite3VdbeResolveLabel(v, iBreak);
   103815       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
   103816       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
   103817       break;
   103818     }
   103819   }
   103820 
   103821   explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
   103822 
   103823   /* Compute collating sequences used by
   103824   ** temporary tables needed to implement the compound select.
   103825   ** Attach the KeyInfo structure to all temporary tables.
   103826   **
   103827   ** This section is run by the right-most SELECT statement only.
   103828   ** SELECT statements to the left always skip this part.  The right-most
   103829   ** SELECT might also skip this part if it has no ORDER BY clause and
   103830   ** no temp tables are required.
   103831   */
   103832   if( p->selFlags & SF_UsesEphemeral ){
   103833     int i;                        /* Loop counter */
   103834     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
   103835     Select *pLoop;                /* For looping through SELECT statements */
   103836     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
   103837     int nCol;                     /* Number of columns in result set */
   103838 
   103839     assert( p->pNext==0 );
   103840     nCol = p->pEList->nExpr;
   103841     pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
   103842     if( !pKeyInfo ){
   103843       rc = SQLITE_NOMEM;
   103844       goto multi_select_end;
   103845     }
   103846     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
   103847       *apColl = multiSelectCollSeq(pParse, p, i);
   103848       if( 0==*apColl ){
   103849         *apColl = db->pDfltColl;
   103850       }
   103851     }
   103852 
   103853     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
   103854       for(i=0; i<2; i++){
   103855         int addr = pLoop->addrOpenEphm[i];
   103856         if( addr<0 ){
   103857           /* If [0] is unused then [1] is also unused.  So we can
   103858           ** always safely abort as soon as the first unused slot is found */
   103859           assert( pLoop->addrOpenEphm[1]<0 );
   103860           break;
   103861         }
   103862         sqlite3VdbeChangeP2(v, addr, nCol);
   103863         sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
   103864                             P4_KEYINFO);
   103865         pLoop->addrOpenEphm[i] = -1;
   103866       }
   103867     }
   103868     sqlite3KeyInfoUnref(pKeyInfo);
   103869   }
   103870 
   103871 multi_select_end:
   103872   pDest->iSdst = dest.iSdst;
   103873   pDest->nSdst = dest.nSdst;
   103874   sqlite3SelectDelete(db, pDelete);
   103875   return rc;
   103876 }
   103877 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
   103878 
   103879 /*
   103880 ** Code an output subroutine for a coroutine implementation of a
   103881 ** SELECT statment.
   103882 **
   103883 ** The data to be output is contained in pIn->iSdst.  There are
   103884 ** pIn->nSdst columns to be output.  pDest is where the output should
   103885 ** be sent.
   103886 **
   103887 ** regReturn is the number of the register holding the subroutine
   103888 ** return address.
   103889 **
   103890 ** If regPrev>0 then it is the first register in a vector that
   103891 ** records the previous output.  mem[regPrev] is a flag that is false
   103892 ** if there has been no previous output.  If regPrev>0 then code is
   103893 ** generated to suppress duplicates.  pKeyInfo is used for comparing
   103894 ** keys.
   103895 **
   103896 ** If the LIMIT found in p->iLimit is reached, jump immediately to
   103897 ** iBreak.
   103898 */
   103899 static int generateOutputSubroutine(
   103900   Parse *pParse,          /* Parsing context */
   103901   Select *p,              /* The SELECT statement */
   103902   SelectDest *pIn,        /* Coroutine supplying data */
   103903   SelectDest *pDest,      /* Where to send the data */
   103904   int regReturn,          /* The return address register */
   103905   int regPrev,            /* Previous result register.  No uniqueness if 0 */
   103906   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
   103907   int iBreak              /* Jump here if we hit the LIMIT */
   103908 ){
   103909   Vdbe *v = pParse->pVdbe;
   103910   int iContinue;
   103911   int addr;
   103912 
   103913   addr = sqlite3VdbeCurrentAddr(v);
   103914   iContinue = sqlite3VdbeMakeLabel(v);
   103915 
   103916   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
   103917   */
   103918   if( regPrev ){
   103919     int j1, j2;
   103920     j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
   103921     j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
   103922                               (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
   103923     sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2); VdbeCoverage(v);
   103924     sqlite3VdbeJumpHere(v, j1);
   103925     sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
   103926     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
   103927   }
   103928   if( pParse->db->mallocFailed ) return 0;
   103929 
   103930   /* Suppress the first OFFSET entries if there is an OFFSET clause
   103931   */
   103932   codeOffset(v, p->iOffset, iContinue);
   103933 
   103934   switch( pDest->eDest ){
   103935     /* Store the result as data using a unique key.
   103936     */
   103937     case SRT_Table:
   103938     case SRT_EphemTab: {
   103939       int r1 = sqlite3GetTempReg(pParse);
   103940       int r2 = sqlite3GetTempReg(pParse);
   103941       testcase( pDest->eDest==SRT_Table );
   103942       testcase( pDest->eDest==SRT_EphemTab );
   103943       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
   103944       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
   103945       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
   103946       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   103947       sqlite3ReleaseTempReg(pParse, r2);
   103948       sqlite3ReleaseTempReg(pParse, r1);
   103949       break;
   103950     }
   103951 
   103952 #ifndef SQLITE_OMIT_SUBQUERY
   103953     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
   103954     ** then there should be a single item on the stack.  Write this
   103955     ** item into the set table with bogus data.
   103956     */
   103957     case SRT_Set: {
   103958       int r1;
   103959       assert( pIn->nSdst==1 );
   103960       pDest->affSdst =
   103961          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
   103962       r1 = sqlite3GetTempReg(pParse);
   103963       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
   103964       sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
   103965       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
   103966       sqlite3ReleaseTempReg(pParse, r1);
   103967       break;
   103968     }
   103969 
   103970 #if 0  /* Never occurs on an ORDER BY query */
   103971     /* If any row exist in the result set, record that fact and abort.
   103972     */
   103973     case SRT_Exists: {
   103974       sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iSDParm);
   103975       /* The LIMIT clause will terminate the loop for us */
   103976       break;
   103977     }
   103978 #endif
   103979 
   103980     /* If this is a scalar select that is part of an expression, then
   103981     ** store the results in the appropriate memory cell and break out
   103982     ** of the scan loop.
   103983     */
   103984     case SRT_Mem: {
   103985       assert( pIn->nSdst==1 );
   103986       sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
   103987       /* The LIMIT clause will jump out of the loop for us */
   103988       break;
   103989     }
   103990 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
   103991 
   103992     /* The results are stored in a sequence of registers
   103993     ** starting at pDest->iSdst.  Then the co-routine yields.
   103994     */
   103995     case SRT_Coroutine: {
   103996       if( pDest->iSdst==0 ){
   103997         pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
   103998         pDest->nSdst = pIn->nSdst;
   103999       }
   104000       sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pDest->nSdst);
   104001       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
   104002       break;
   104003     }
   104004 
   104005     /* If none of the above, then the result destination must be
   104006     ** SRT_Output.  This routine is never called with any other
   104007     ** destination other than the ones handled above or SRT_Output.
   104008     **
   104009     ** For SRT_Output, results are stored in a sequence of registers.
   104010     ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
   104011     ** return the next row of result.
   104012     */
   104013     default: {
   104014       assert( pDest->eDest==SRT_Output );
   104015       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
   104016       sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
   104017       break;
   104018     }
   104019   }
   104020 
   104021   /* Jump to the end of the loop if the LIMIT is reached.
   104022   */
   104023   if( p->iLimit ){
   104024     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1); VdbeCoverage(v);
   104025   }
   104026 
   104027   /* Generate the subroutine return
   104028   */
   104029   sqlite3VdbeResolveLabel(v, iContinue);
   104030   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
   104031 
   104032   return addr;
   104033 }
   104034 
   104035 /*
   104036 ** Alternative compound select code generator for cases when there
   104037 ** is an ORDER BY clause.
   104038 **
   104039 ** We assume a query of the following form:
   104040 **
   104041 **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
   104042 **
   104043 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
   104044 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
   104045 ** co-routines.  Then run the co-routines in parallel and merge the results
   104046 ** into the output.  In addition to the two coroutines (called selectA and
   104047 ** selectB) there are 7 subroutines:
   104048 **
   104049 **    outA:    Move the output of the selectA coroutine into the output
   104050 **             of the compound query.
   104051 **
   104052 **    outB:    Move the output of the selectB coroutine into the output
   104053 **             of the compound query.  (Only generated for UNION and
   104054 **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
   104055 **             appears only in B.)
   104056 **
   104057 **    AltB:    Called when there is data from both coroutines and A<B.
   104058 **
   104059 **    AeqB:    Called when there is data from both coroutines and A==B.
   104060 **
   104061 **    AgtB:    Called when there is data from both coroutines and A>B.
   104062 **
   104063 **    EofA:    Called when data is exhausted from selectA.
   104064 **
   104065 **    EofB:    Called when data is exhausted from selectB.
   104066 **
   104067 ** The implementation of the latter five subroutines depend on which
   104068 ** <operator> is used:
   104069 **
   104070 **
   104071 **             UNION ALL         UNION            EXCEPT          INTERSECT
   104072 **          -------------  -----------------  --------------  -----------------
   104073 **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
   104074 **
   104075 **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
   104076 **
   104077 **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
   104078 **
   104079 **   EofA:   outB, nextB      outB, nextB          halt             halt
   104080 **
   104081 **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
   104082 **
   104083 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
   104084 ** causes an immediate jump to EofA and an EOF on B following nextB causes
   104085 ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
   104086 ** following nextX causes a jump to the end of the select processing.
   104087 **
   104088 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
   104089 ** within the output subroutine.  The regPrev register set holds the previously
   104090 ** output value.  A comparison is made against this value and the output
   104091 ** is skipped if the next results would be the same as the previous.
   104092 **
   104093 ** The implementation plan is to implement the two coroutines and seven
   104094 ** subroutines first, then put the control logic at the bottom.  Like this:
   104095 **
   104096 **          goto Init
   104097 **     coA: coroutine for left query (A)
   104098 **     coB: coroutine for right query (B)
   104099 **    outA: output one row of A
   104100 **    outB: output one row of B (UNION and UNION ALL only)
   104101 **    EofA: ...
   104102 **    EofB: ...
   104103 **    AltB: ...
   104104 **    AeqB: ...
   104105 **    AgtB: ...
   104106 **    Init: initialize coroutine registers
   104107 **          yield coA
   104108 **          if eof(A) goto EofA
   104109 **          yield coB
   104110 **          if eof(B) goto EofB
   104111 **    Cmpr: Compare A, B
   104112 **          Jump AltB, AeqB, AgtB
   104113 **     End: ...
   104114 **
   104115 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
   104116 ** actually called using Gosub and they do not Return.  EofA and EofB loop
   104117 ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
   104118 ** and AgtB jump to either L2 or to one of EofA or EofB.
   104119 */
   104120 #ifndef SQLITE_OMIT_COMPOUND_SELECT
   104121 static int multiSelectOrderBy(
   104122   Parse *pParse,        /* Parsing context */
   104123   Select *p,            /* The right-most of SELECTs to be coded */
   104124   SelectDest *pDest     /* What to do with query results */
   104125 ){
   104126   int i, j;             /* Loop counters */
   104127   Select *pPrior;       /* Another SELECT immediately to our left */
   104128   Vdbe *v;              /* Generate code to this VDBE */
   104129   SelectDest destA;     /* Destination for coroutine A */
   104130   SelectDest destB;     /* Destination for coroutine B */
   104131   int regAddrA;         /* Address register for select-A coroutine */
   104132   int regAddrB;         /* Address register for select-B coroutine */
   104133   int addrSelectA;      /* Address of the select-A coroutine */
   104134   int addrSelectB;      /* Address of the select-B coroutine */
   104135   int regOutA;          /* Address register for the output-A subroutine */
   104136   int regOutB;          /* Address register for the output-B subroutine */
   104137   int addrOutA;         /* Address of the output-A subroutine */
   104138   int addrOutB = 0;     /* Address of the output-B subroutine */
   104139   int addrEofA;         /* Address of the select-A-exhausted subroutine */
   104140   int addrEofA_noB;     /* Alternate addrEofA if B is uninitialized */
   104141   int addrEofB;         /* Address of the select-B-exhausted subroutine */
   104142   int addrAltB;         /* Address of the A<B subroutine */
   104143   int addrAeqB;         /* Address of the A==B subroutine */
   104144   int addrAgtB;         /* Address of the A>B subroutine */
   104145   int regLimitA;        /* Limit register for select-A */
   104146   int regLimitB;        /* Limit register for select-A */
   104147   int regPrev;          /* A range of registers to hold previous output */
   104148   int savedLimit;       /* Saved value of p->iLimit */
   104149   int savedOffset;      /* Saved value of p->iOffset */
   104150   int labelCmpr;        /* Label for the start of the merge algorithm */
   104151   int labelEnd;         /* Label for the end of the overall SELECT stmt */
   104152   int j1;               /* Jump instructions that get retargetted */
   104153   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
   104154   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
   104155   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
   104156   sqlite3 *db;          /* Database connection */
   104157   ExprList *pOrderBy;   /* The ORDER BY clause */
   104158   int nOrderBy;         /* Number of terms in the ORDER BY clause */
   104159   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
   104160 #ifndef SQLITE_OMIT_EXPLAIN
   104161   int iSub1;            /* EQP id of left-hand query */
   104162   int iSub2;            /* EQP id of right-hand query */
   104163 #endif
   104164 
   104165   assert( p->pOrderBy!=0 );
   104166   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
   104167   db = pParse->db;
   104168   v = pParse->pVdbe;
   104169   assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
   104170   labelEnd = sqlite3VdbeMakeLabel(v);
   104171   labelCmpr = sqlite3VdbeMakeLabel(v);
   104172 
   104173 
   104174   /* Patch up the ORDER BY clause
   104175   */
   104176   op = p->op;
   104177   pPrior = p->pPrior;
   104178   assert( pPrior->pOrderBy==0 );
   104179   pOrderBy = p->pOrderBy;
   104180   assert( pOrderBy );
   104181   nOrderBy = pOrderBy->nExpr;
   104182 
   104183   /* For operators other than UNION ALL we have to make sure that
   104184   ** the ORDER BY clause covers every term of the result set.  Add
   104185   ** terms to the ORDER BY clause as necessary.
   104186   */
   104187   if( op!=TK_ALL ){
   104188     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
   104189       struct ExprList_item *pItem;
   104190       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
   104191         assert( pItem->u.x.iOrderByCol>0 );
   104192         if( pItem->u.x.iOrderByCol==i ) break;
   104193       }
   104194       if( j==nOrderBy ){
   104195         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
   104196         if( pNew==0 ) return SQLITE_NOMEM;
   104197         pNew->flags |= EP_IntValue;
   104198         pNew->u.iValue = i;
   104199         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
   104200         if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
   104201       }
   104202     }
   104203   }
   104204 
   104205   /* Compute the comparison permutation and keyinfo that is used with
   104206   ** the permutation used to determine if the next
   104207   ** row of results comes from selectA or selectB.  Also add explicit
   104208   ** collations to the ORDER BY clause terms so that when the subqueries
   104209   ** to the right and the left are evaluated, they use the correct
   104210   ** collation.
   104211   */
   104212   aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
   104213   if( aPermute ){
   104214     struct ExprList_item *pItem;
   104215     for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
   104216       assert( pItem->u.x.iOrderByCol>0
   104217           && pItem->u.x.iOrderByCol<=p->pEList->nExpr );
   104218       aPermute[i] = pItem->u.x.iOrderByCol - 1;
   104219     }
   104220     pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
   104221   }else{
   104222     pKeyMerge = 0;
   104223   }
   104224 
   104225   /* Reattach the ORDER BY clause to the query.
   104226   */
   104227   p->pOrderBy = pOrderBy;
   104228   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
   104229 
   104230   /* Allocate a range of temporary registers and the KeyInfo needed
   104231   ** for the logic that removes duplicate result rows when the
   104232   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
   104233   */
   104234   if( op==TK_ALL ){
   104235     regPrev = 0;
   104236   }else{
   104237     int nExpr = p->pEList->nExpr;
   104238     assert( nOrderBy>=nExpr || db->mallocFailed );
   104239     regPrev = pParse->nMem+1;
   104240     pParse->nMem += nExpr+1;
   104241     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
   104242     pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
   104243     if( pKeyDup ){
   104244       assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
   104245       for(i=0; i<nExpr; i++){
   104246         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
   104247         pKeyDup->aSortOrder[i] = 0;
   104248       }
   104249     }
   104250   }
   104251 
   104252   /* Separate the left and the right query from one another
   104253   */
   104254   p->pPrior = 0;
   104255   pPrior->pNext = 0;
   104256   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
   104257   if( pPrior->pPrior==0 ){
   104258     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
   104259   }
   104260 
   104261   /* Compute the limit registers */
   104262   computeLimitRegisters(pParse, p, labelEnd);
   104263   if( p->iLimit && op==TK_ALL ){
   104264     regLimitA = ++pParse->nMem;
   104265     regLimitB = ++pParse->nMem;
   104266     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
   104267                                   regLimitA);
   104268     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
   104269   }else{
   104270     regLimitA = regLimitB = 0;
   104271   }
   104272   sqlite3ExprDelete(db, p->pLimit);
   104273   p->pLimit = 0;
   104274   sqlite3ExprDelete(db, p->pOffset);
   104275   p->pOffset = 0;
   104276 
   104277   regAddrA = ++pParse->nMem;
   104278   regAddrB = ++pParse->nMem;
   104279   regOutA = ++pParse->nMem;
   104280   regOutB = ++pParse->nMem;
   104281   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
   104282   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
   104283 
   104284   /* Generate a coroutine to evaluate the SELECT statement to the
   104285   ** left of the compound operator - the "A" select.
   104286   */
   104287   addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
   104288   j1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
   104289   VdbeComment((v, "left SELECT"));
   104290   pPrior->iLimit = regLimitA;
   104291   explainSetInteger(iSub1, pParse->iNextSelectId);
   104292   sqlite3Select(pParse, pPrior, &destA);
   104293   sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrA);
   104294   sqlite3VdbeJumpHere(v, j1);
   104295 
   104296   /* Generate a coroutine to evaluate the SELECT statement on
   104297   ** the right - the "B" select
   104298   */
   104299   addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
   104300   j1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
   104301   VdbeComment((v, "right SELECT"));
   104302   savedLimit = p->iLimit;
   104303   savedOffset = p->iOffset;
   104304   p->iLimit = regLimitB;
   104305   p->iOffset = 0;
   104306   explainSetInteger(iSub2, pParse->iNextSelectId);
   104307   sqlite3Select(pParse, p, &destB);
   104308   p->iLimit = savedLimit;
   104309   p->iOffset = savedOffset;
   104310   sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrB);
   104311 
   104312   /* Generate a subroutine that outputs the current row of the A
   104313   ** select as the next output row of the compound select.
   104314   */
   104315   VdbeNoopComment((v, "Output routine for A"));
   104316   addrOutA = generateOutputSubroutine(pParse,
   104317                  p, &destA, pDest, regOutA,
   104318                  regPrev, pKeyDup, labelEnd);
   104319 
   104320   /* Generate a subroutine that outputs the current row of the B
   104321   ** select as the next output row of the compound select.
   104322   */
   104323   if( op==TK_ALL || op==TK_UNION ){
   104324     VdbeNoopComment((v, "Output routine for B"));
   104325     addrOutB = generateOutputSubroutine(pParse,
   104326                  p, &destB, pDest, regOutB,
   104327                  regPrev, pKeyDup, labelEnd);
   104328   }
   104329   sqlite3KeyInfoUnref(pKeyDup);
   104330 
   104331   /* Generate a subroutine to run when the results from select A
   104332   ** are exhausted and only data in select B remains.
   104333   */
   104334   if( op==TK_EXCEPT || op==TK_INTERSECT ){
   104335     addrEofA_noB = addrEofA = labelEnd;
   104336   }else{
   104337     VdbeNoopComment((v, "eof-A subroutine"));
   104338     addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
   104339     addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
   104340                                      VdbeCoverage(v);
   104341     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
   104342     p->nSelectRow += pPrior->nSelectRow;
   104343   }
   104344 
   104345   /* Generate a subroutine to run when the results from select B
   104346   ** are exhausted and only data in select A remains.
   104347   */
   104348   if( op==TK_INTERSECT ){
   104349     addrEofB = addrEofA;
   104350     if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
   104351   }else{
   104352     VdbeNoopComment((v, "eof-B subroutine"));
   104353     addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
   104354     sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
   104355     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
   104356   }
   104357 
   104358   /* Generate code to handle the case of A<B
   104359   */
   104360   VdbeNoopComment((v, "A-lt-B subroutine"));
   104361   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
   104362   sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
   104363   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
   104364 
   104365   /* Generate code to handle the case of A==B
   104366   */
   104367   if( op==TK_ALL ){
   104368     addrAeqB = addrAltB;
   104369   }else if( op==TK_INTERSECT ){
   104370     addrAeqB = addrAltB;
   104371     addrAltB++;
   104372   }else{
   104373     VdbeNoopComment((v, "A-eq-B subroutine"));
   104374     addrAeqB =
   104375     sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
   104376     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
   104377   }
   104378 
   104379   /* Generate code to handle the case of A>B
   104380   */
   104381   VdbeNoopComment((v, "A-gt-B subroutine"));
   104382   addrAgtB = sqlite3VdbeCurrentAddr(v);
   104383   if( op==TK_ALL || op==TK_UNION ){
   104384     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
   104385   }
   104386   sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
   104387   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
   104388 
   104389   /* This code runs once to initialize everything.
   104390   */
   104391   sqlite3VdbeJumpHere(v, j1);
   104392   sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
   104393   sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
   104394 
   104395   /* Implement the main merge loop
   104396   */
   104397   sqlite3VdbeResolveLabel(v, labelCmpr);
   104398   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
   104399   sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
   104400                          (char*)pKeyMerge, P4_KEYINFO);
   104401   sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
   104402   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
   104403 
   104404   /* Jump to the this point in order to terminate the query.
   104405   */
   104406   sqlite3VdbeResolveLabel(v, labelEnd);
   104407 
   104408   /* Set the number of output columns
   104409   */
   104410   if( pDest->eDest==SRT_Output ){
   104411     Select *pFirst = pPrior;
   104412     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
   104413     generateColumnNames(pParse, 0, pFirst->pEList);
   104414   }
   104415 
   104416   /* Reassembly the compound query so that it will be freed correctly
   104417   ** by the calling function */
   104418   if( p->pPrior ){
   104419     sqlite3SelectDelete(db, p->pPrior);
   104420   }
   104421   p->pPrior = pPrior;
   104422   pPrior->pNext = p;
   104423 
   104424   /*** TBD:  Insert subroutine calls to close cursors on incomplete
   104425   **** subqueries ****/
   104426   explainComposite(pParse, p->op, iSub1, iSub2, 0);
   104427   return SQLITE_OK;
   104428 }
   104429 #endif
   104430 
   104431 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
   104432 /* Forward Declarations */
   104433 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
   104434 static void substSelect(sqlite3*, Select *, int, ExprList *);
   104435 
   104436 /*
   104437 ** Scan through the expression pExpr.  Replace every reference to
   104438 ** a column in table number iTable with a copy of the iColumn-th
   104439 ** entry in pEList.  (But leave references to the ROWID column
   104440 ** unchanged.)
   104441 **
   104442 ** This routine is part of the flattening procedure.  A subquery
   104443 ** whose result set is defined by pEList appears as entry in the
   104444 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
   104445 ** FORM clause entry is iTable.  This routine make the necessary
   104446 ** changes to pExpr so that it refers directly to the source table
   104447 ** of the subquery rather the result set of the subquery.
   104448 */
   104449 static Expr *substExpr(
   104450   sqlite3 *db,        /* Report malloc errors to this connection */
   104451   Expr *pExpr,        /* Expr in which substitution occurs */
   104452   int iTable,         /* Table to be substituted */
   104453   ExprList *pEList    /* Substitute expressions */
   104454 ){
   104455   if( pExpr==0 ) return 0;
   104456   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
   104457     if( pExpr->iColumn<0 ){
   104458       pExpr->op = TK_NULL;
   104459     }else{
   104460       Expr *pNew;
   104461       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
   104462       assert( pExpr->pLeft==0 && pExpr->pRight==0 );
   104463       pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
   104464       sqlite3ExprDelete(db, pExpr);
   104465       pExpr = pNew;
   104466     }
   104467   }else{
   104468     pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
   104469     pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
   104470     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   104471       substSelect(db, pExpr->x.pSelect, iTable, pEList);
   104472     }else{
   104473       substExprList(db, pExpr->x.pList, iTable, pEList);
   104474     }
   104475   }
   104476   return pExpr;
   104477 }
   104478 static void substExprList(
   104479   sqlite3 *db,         /* Report malloc errors here */
   104480   ExprList *pList,     /* List to scan and in which to make substitutes */
   104481   int iTable,          /* Table to be substituted */
   104482   ExprList *pEList     /* Substitute values */
   104483 ){
   104484   int i;
   104485   if( pList==0 ) return;
   104486   for(i=0; i<pList->nExpr; i++){
   104487     pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
   104488   }
   104489 }
   104490 static void substSelect(
   104491   sqlite3 *db,         /* Report malloc errors here */
   104492   Select *p,           /* SELECT statement in which to make substitutions */
   104493   int iTable,          /* Table to be replaced */
   104494   ExprList *pEList     /* Substitute values */
   104495 ){
   104496   SrcList *pSrc;
   104497   struct SrcList_item *pItem;
   104498   int i;
   104499   if( !p ) return;
   104500   substExprList(db, p->pEList, iTable, pEList);
   104501   substExprList(db, p->pGroupBy, iTable, pEList);
   104502   substExprList(db, p->pOrderBy, iTable, pEList);
   104503   p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
   104504   p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
   104505   substSelect(db, p->pPrior, iTable, pEList);
   104506   pSrc = p->pSrc;
   104507   assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
   104508   if( ALWAYS(pSrc) ){
   104509     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
   104510       substSelect(db, pItem->pSelect, iTable, pEList);
   104511     }
   104512   }
   104513 }
   104514 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
   104515 
   104516 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
   104517 /*
   104518 ** This routine attempts to flatten subqueries as a performance optimization.
   104519 ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
   104520 **
   104521 ** To understand the concept of flattening, consider the following
   104522 ** query:
   104523 **
   104524 **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
   104525 **
   104526 ** The default way of implementing this query is to execute the
   104527 ** subquery first and store the results in a temporary table, then
   104528 ** run the outer query on that temporary table.  This requires two
   104529 ** passes over the data.  Furthermore, because the temporary table
   104530 ** has no indices, the WHERE clause on the outer query cannot be
   104531 ** optimized.
   104532 **
   104533 ** This routine attempts to rewrite queries such as the above into
   104534 ** a single flat select, like this:
   104535 **
   104536 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
   104537 **
   104538 ** The code generated for this simpification gives the same result
   104539 ** but only has to scan the data once.  And because indices might
   104540 ** exist on the table t1, a complete scan of the data might be
   104541 ** avoided.
   104542 **
   104543 ** Flattening is only attempted if all of the following are true:
   104544 **
   104545 **   (1)  The subquery and the outer query do not both use aggregates.
   104546 **
   104547 **   (2)  The subquery is not an aggregate or the outer query is not a join.
   104548 **
   104549 **   (3)  The subquery is not the right operand of a left outer join
   104550 **        (Originally ticket #306.  Strengthened by ticket #3300)
   104551 **
   104552 **   (4)  The subquery is not DISTINCT.
   104553 **
   104554 **  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
   104555 **        sub-queries that were excluded from this optimization. Restriction
   104556 **        (4) has since been expanded to exclude all DISTINCT subqueries.
   104557 **
   104558 **   (6)  The subquery does not use aggregates or the outer query is not
   104559 **        DISTINCT.
   104560 **
   104561 **   (7)  The subquery has a FROM clause.  TODO:  For subqueries without
   104562 **        A FROM clause, consider adding a FROM close with the special
   104563 **        table sqlite_once that consists of a single row containing a
   104564 **        single NULL.
   104565 **
   104566 **   (8)  The subquery does not use LIMIT or the outer query is not a join.
   104567 **
   104568 **   (9)  The subquery does not use LIMIT or the outer query does not use
   104569 **        aggregates.
   104570 **
   104571 **  (10)  The subquery does not use aggregates or the outer query does not
   104572 **        use LIMIT.
   104573 **
   104574 **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
   104575 **
   104576 **  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
   104577 **        a separate restriction deriving from ticket #350.
   104578 **
   104579 **  (13)  The subquery and outer query do not both use LIMIT.
   104580 **
   104581 **  (14)  The subquery does not use OFFSET.
   104582 **
   104583 **  (15)  The outer query is not part of a compound select or the
   104584 **        subquery does not have a LIMIT clause.
   104585 **        (See ticket #2339 and ticket [02a8e81d44]).
   104586 **
   104587 **  (16)  The outer query is not an aggregate or the subquery does
   104588 **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
   104589 **        until we introduced the group_concat() function.
   104590 **
   104591 **  (17)  The sub-query is not a compound select, or it is a UNION ALL
   104592 **        compound clause made up entirely of non-aggregate queries, and
   104593 **        the parent query:
   104594 **
   104595 **          * is not itself part of a compound select,
   104596 **          * is not an aggregate or DISTINCT query, and
   104597 **          * is not a join
   104598 **
   104599 **        The parent and sub-query may contain WHERE clauses. Subject to
   104600 **        rules (11), (13) and (14), they may also contain ORDER BY,
   104601 **        LIMIT and OFFSET clauses.  The subquery cannot use any compound
   104602 **        operator other than UNION ALL because all the other compound
   104603 **        operators have an implied DISTINCT which is disallowed by
   104604 **        restriction (4).
   104605 **
   104606 **        Also, each component of the sub-query must return the same number
   104607 **        of result columns. This is actually a requirement for any compound
   104608 **        SELECT statement, but all the code here does is make sure that no
   104609 **        such (illegal) sub-query is flattened. The caller will detect the
   104610 **        syntax error and return a detailed message.
   104611 **
   104612 **  (18)  If the sub-query is a compound select, then all terms of the
   104613 **        ORDER by clause of the parent must be simple references to
   104614 **        columns of the sub-query.
   104615 **
   104616 **  (19)  The subquery does not use LIMIT or the outer query does not
   104617 **        have a WHERE clause.
   104618 **
   104619 **  (20)  If the sub-query is a compound select, then it must not use
   104620 **        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
   104621 **        somewhat by saying that the terms of the ORDER BY clause must
   104622 **        appear as unmodified result columns in the outer query.  But we
   104623 **        have other optimizations in mind to deal with that case.
   104624 **
   104625 **  (21)  The subquery does not use LIMIT or the outer query is not
   104626 **        DISTINCT.  (See ticket [752e1646fc]).
   104627 **
   104628 **  (22)  The subquery is not a recursive CTE.
   104629 **
   104630 **  (23)  The parent is not a recursive CTE, or the sub-query is not a
   104631 **        compound query. This restriction is because transforming the
   104632 **        parent to a compound query confuses the code that handles
   104633 **        recursive queries in multiSelect().
   104634 **
   104635 **
   104636 ** In this routine, the "p" parameter is a pointer to the outer query.
   104637 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
   104638 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
   104639 **
   104640 ** If flattening is not attempted, this routine is a no-op and returns 0.
   104641 ** If flattening is attempted this routine returns 1.
   104642 **
   104643 ** All of the expression analysis must occur on both the outer query and
   104644 ** the subquery before this routine runs.
   104645 */
   104646 static int flattenSubquery(
   104647   Parse *pParse,       /* Parsing context */
   104648   Select *p,           /* The parent or outer SELECT statement */
   104649   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
   104650   int isAgg,           /* True if outer SELECT uses aggregate functions */
   104651   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
   104652 ){
   104653   const char *zSavedAuthContext = pParse->zAuthContext;
   104654   Select *pParent;
   104655   Select *pSub;       /* The inner query or "subquery" */
   104656   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
   104657   SrcList *pSrc;      /* The FROM clause of the outer query */
   104658   SrcList *pSubSrc;   /* The FROM clause of the subquery */
   104659   ExprList *pList;    /* The result set of the outer query */
   104660   int iParent;        /* VDBE cursor number of the pSub result set temp table */
   104661   int i;              /* Loop counter */
   104662   Expr *pWhere;                    /* The WHERE clause */
   104663   struct SrcList_item *pSubitem;   /* The subquery */
   104664   sqlite3 *db = pParse->db;
   104665 
   104666   /* Check to see if flattening is permitted.  Return 0 if not.
   104667   */
   104668   assert( p!=0 );
   104669   assert( p->pPrior==0 );  /* Unable to flatten compound queries */
   104670   if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
   104671   pSrc = p->pSrc;
   104672   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
   104673   pSubitem = &pSrc->a[iFrom];
   104674   iParent = pSubitem->iCursor;
   104675   pSub = pSubitem->pSelect;
   104676   assert( pSub!=0 );
   104677   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
   104678   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
   104679   pSubSrc = pSub->pSrc;
   104680   assert( pSubSrc );
   104681   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
   104682   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
   104683   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
   104684   ** became arbitrary expressions, we were forced to add restrictions (13)
   104685   ** and (14). */
   104686   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
   104687   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
   104688   if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
   104689     return 0;                                            /* Restriction (15) */
   104690   }
   104691   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
   104692   if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
   104693   if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
   104694      return 0;         /* Restrictions (8)(9) */
   104695   }
   104696   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
   104697      return 0;         /* Restriction (6)  */
   104698   }
   104699   if( p->pOrderBy && pSub->pOrderBy ){
   104700      return 0;                                           /* Restriction (11) */
   104701   }
   104702   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
   104703   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
   104704   if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
   104705      return 0;         /* Restriction (21) */
   104706   }
   104707   if( pSub->selFlags & SF_Recursive ) return 0;          /* Restriction (22)  */
   104708   if( (p->selFlags & SF_Recursive) && pSub->pPrior ) return 0;       /* (23)  */
   104709 
   104710   /* OBSOLETE COMMENT 1:
   104711   ** Restriction 3:  If the subquery is a join, make sure the subquery is
   104712   ** not used as the right operand of an outer join.  Examples of why this
   104713   ** is not allowed:
   104714   **
   104715   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
   104716   **
   104717   ** If we flatten the above, we would get
   104718   **
   104719   **         (t1 LEFT OUTER JOIN t2) JOIN t3
   104720   **
   104721   ** which is not at all the same thing.
   104722   **
   104723   ** OBSOLETE COMMENT 2:
   104724   ** Restriction 12:  If the subquery is the right operand of a left outer
   104725   ** join, make sure the subquery has no WHERE clause.
   104726   ** An examples of why this is not allowed:
   104727   **
   104728   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
   104729   **
   104730   ** If we flatten the above, we would get
   104731   **
   104732   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
   104733   **
   104734   ** But the t2.x>0 test will always fail on a NULL row of t2, which
   104735   ** effectively converts the OUTER JOIN into an INNER JOIN.
   104736   **
   104737   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
   104738   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
   104739   ** is fraught with danger.  Best to avoid the whole thing.  If the
   104740   ** subquery is the right term of a LEFT JOIN, then do not flatten.
   104741   */
   104742   if( (pSubitem->jointype & JT_OUTER)!=0 ){
   104743     return 0;
   104744   }
   104745 
   104746   /* Restriction 17: If the sub-query is a compound SELECT, then it must
   104747   ** use only the UNION ALL operator. And none of the simple select queries
   104748   ** that make up the compound SELECT are allowed to be aggregate or distinct
   104749   ** queries.
   104750   */
   104751   if( pSub->pPrior ){
   104752     if( pSub->pOrderBy ){
   104753       return 0;  /* Restriction 20 */
   104754     }
   104755     if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
   104756       return 0;
   104757     }
   104758     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
   104759       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
   104760       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
   104761       assert( pSub->pSrc!=0 );
   104762       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
   104763        || (pSub1->pPrior && pSub1->op!=TK_ALL)
   104764        || pSub1->pSrc->nSrc<1
   104765        || pSub->pEList->nExpr!=pSub1->pEList->nExpr
   104766       ){
   104767         return 0;
   104768       }
   104769       testcase( pSub1->pSrc->nSrc>1 );
   104770     }
   104771 
   104772     /* Restriction 18. */
   104773     if( p->pOrderBy ){
   104774       int ii;
   104775       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
   104776         if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
   104777       }
   104778     }
   104779   }
   104780 
   104781   /***** If we reach this point, flattening is permitted. *****/
   104782 
   104783   /* Authorize the subquery */
   104784   pParse->zAuthContext = pSubitem->zName;
   104785   TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
   104786   testcase( i==SQLITE_DENY );
   104787   pParse->zAuthContext = zSavedAuthContext;
   104788 
   104789   /* If the sub-query is a compound SELECT statement, then (by restrictions
   104790   ** 17 and 18 above) it must be a UNION ALL and the parent query must
   104791   ** be of the form:
   104792   **
   104793   **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
   104794   **
   104795   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
   104796   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
   104797   ** OFFSET clauses and joins them to the left-hand-side of the original
   104798   ** using UNION ALL operators. In this case N is the number of simple
   104799   ** select statements in the compound sub-query.
   104800   **
   104801   ** Example:
   104802   **
   104803   **     SELECT a+1 FROM (
   104804   **        SELECT x FROM tab
   104805   **        UNION ALL
   104806   **        SELECT y FROM tab
   104807   **        UNION ALL
   104808   **        SELECT abs(z*2) FROM tab2
   104809   **     ) WHERE a!=5 ORDER BY 1
   104810   **
   104811   ** Transformed into:
   104812   **
   104813   **     SELECT x+1 FROM tab WHERE x+1!=5
   104814   **     UNION ALL
   104815   **     SELECT y+1 FROM tab WHERE y+1!=5
   104816   **     UNION ALL
   104817   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
   104818   **     ORDER BY 1
   104819   **
   104820   ** We call this the "compound-subquery flattening".
   104821   */
   104822   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
   104823     Select *pNew;
   104824     ExprList *pOrderBy = p->pOrderBy;
   104825     Expr *pLimit = p->pLimit;
   104826     Expr *pOffset = p->pOffset;
   104827     Select *pPrior = p->pPrior;
   104828     p->pOrderBy = 0;
   104829     p->pSrc = 0;
   104830     p->pPrior = 0;
   104831     p->pLimit = 0;
   104832     p->pOffset = 0;
   104833     pNew = sqlite3SelectDup(db, p, 0);
   104834     p->pOffset = pOffset;
   104835     p->pLimit = pLimit;
   104836     p->pOrderBy = pOrderBy;
   104837     p->pSrc = pSrc;
   104838     p->op = TK_ALL;
   104839     if( pNew==0 ){
   104840       p->pPrior = pPrior;
   104841     }else{
   104842       pNew->pPrior = pPrior;
   104843       if( pPrior ) pPrior->pNext = pNew;
   104844       pNew->pNext = p;
   104845       p->pPrior = pNew;
   104846     }
   104847     if( db->mallocFailed ) return 1;
   104848   }
   104849 
   104850   /* Begin flattening the iFrom-th entry of the FROM clause
   104851   ** in the outer query.
   104852   */
   104853   pSub = pSub1 = pSubitem->pSelect;
   104854 
   104855   /* Delete the transient table structure associated with the
   104856   ** subquery
   104857   */
   104858   sqlite3DbFree(db, pSubitem->zDatabase);
   104859   sqlite3DbFree(db, pSubitem->zName);
   104860   sqlite3DbFree(db, pSubitem->zAlias);
   104861   pSubitem->zDatabase = 0;
   104862   pSubitem->zName = 0;
   104863   pSubitem->zAlias = 0;
   104864   pSubitem->pSelect = 0;
   104865 
   104866   /* Defer deleting the Table object associated with the
   104867   ** subquery until code generation is
   104868   ** complete, since there may still exist Expr.pTab entries that
   104869   ** refer to the subquery even after flattening.  Ticket #3346.
   104870   **
   104871   ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
   104872   */
   104873   if( ALWAYS(pSubitem->pTab!=0) ){
   104874     Table *pTabToDel = pSubitem->pTab;
   104875     if( pTabToDel->nRef==1 ){
   104876       Parse *pToplevel = sqlite3ParseToplevel(pParse);
   104877       pTabToDel->pNextZombie = pToplevel->pZombieTab;
   104878       pToplevel->pZombieTab = pTabToDel;
   104879     }else{
   104880       pTabToDel->nRef--;
   104881     }
   104882     pSubitem->pTab = 0;
   104883   }
   104884 
   104885   /* The following loop runs once for each term in a compound-subquery
   104886   ** flattening (as described above).  If we are doing a different kind
   104887   ** of flattening - a flattening other than a compound-subquery flattening -
   104888   ** then this loop only runs once.
   104889   **
   104890   ** This loop moves all of the FROM elements of the subquery into the
   104891   ** the FROM clause of the outer query.  Before doing this, remember
   104892   ** the cursor number for the original outer query FROM element in
   104893   ** iParent.  The iParent cursor will never be used.  Subsequent code
   104894   ** will scan expressions looking for iParent references and replace
   104895   ** those references with expressions that resolve to the subquery FROM
   104896   ** elements we are now copying in.
   104897   */
   104898   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
   104899     int nSubSrc;
   104900     u8 jointype = 0;
   104901     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
   104902     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
   104903     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
   104904 
   104905     if( pSrc ){
   104906       assert( pParent==p );  /* First time through the loop */
   104907       jointype = pSubitem->jointype;
   104908     }else{
   104909       assert( pParent!=p );  /* 2nd and subsequent times through the loop */
   104910       pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
   104911       if( pSrc==0 ){
   104912         assert( db->mallocFailed );
   104913         break;
   104914       }
   104915     }
   104916 
   104917     /* The subquery uses a single slot of the FROM clause of the outer
   104918     ** query.  If the subquery has more than one element in its FROM clause,
   104919     ** then expand the outer query to make space for it to hold all elements
   104920     ** of the subquery.
   104921     **
   104922     ** Example:
   104923     **
   104924     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
   104925     **
   104926     ** The outer query has 3 slots in its FROM clause.  One slot of the
   104927     ** outer query (the middle slot) is used by the subquery.  The next
   104928     ** block of code will expand the out query to 4 slots.  The middle
   104929     ** slot is expanded to two slots in order to make space for the
   104930     ** two elements in the FROM clause of the subquery.
   104931     */
   104932     if( nSubSrc>1 ){
   104933       pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
   104934       if( db->mallocFailed ){
   104935         break;
   104936       }
   104937     }
   104938 
   104939     /* Transfer the FROM clause terms from the subquery into the
   104940     ** outer query.
   104941     */
   104942     for(i=0; i<nSubSrc; i++){
   104943       sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
   104944       pSrc->a[i+iFrom] = pSubSrc->a[i];
   104945       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
   104946     }
   104947     pSrc->a[iFrom].jointype = jointype;
   104948 
   104949     /* Now begin substituting subquery result set expressions for
   104950     ** references to the iParent in the outer query.
   104951     **
   104952     ** Example:
   104953     **
   104954     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
   104955     **   \                     \_____________ subquery __________/          /
   104956     **    \_____________________ outer query ______________________________/
   104957     **
   104958     ** We look at every expression in the outer query and every place we see
   104959     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
   104960     */
   104961     pList = pParent->pEList;
   104962     for(i=0; i<pList->nExpr; i++){
   104963       if( pList->a[i].zName==0 ){
   104964         char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
   104965         sqlite3Dequote(zName);
   104966         pList->a[i].zName = zName;
   104967       }
   104968     }
   104969     substExprList(db, pParent->pEList, iParent, pSub->pEList);
   104970     if( isAgg ){
   104971       substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
   104972       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
   104973     }
   104974     if( pSub->pOrderBy ){
   104975       assert( pParent->pOrderBy==0 );
   104976       pParent->pOrderBy = pSub->pOrderBy;
   104977       pSub->pOrderBy = 0;
   104978     }else if( pParent->pOrderBy ){
   104979       substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
   104980     }
   104981     if( pSub->pWhere ){
   104982       pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
   104983     }else{
   104984       pWhere = 0;
   104985     }
   104986     if( subqueryIsAgg ){
   104987       assert( pParent->pHaving==0 );
   104988       pParent->pHaving = pParent->pWhere;
   104989       pParent->pWhere = pWhere;
   104990       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
   104991       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
   104992                                   sqlite3ExprDup(db, pSub->pHaving, 0));
   104993       assert( pParent->pGroupBy==0 );
   104994       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
   104995     }else{
   104996       pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
   104997       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
   104998     }
   104999 
   105000     /* The flattened query is distinct if either the inner or the
   105001     ** outer query is distinct.
   105002     */
   105003     pParent->selFlags |= pSub->selFlags & SF_Distinct;
   105004 
   105005     /*
   105006     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
   105007     **
   105008     ** One is tempted to try to add a and b to combine the limits.  But this
   105009     ** does not work if either limit is negative.
   105010     */
   105011     if( pSub->pLimit ){
   105012       pParent->pLimit = pSub->pLimit;
   105013       pSub->pLimit = 0;
   105014     }
   105015   }
   105016 
   105017   /* Finially, delete what is left of the subquery and return
   105018   ** success.
   105019   */
   105020   sqlite3SelectDelete(db, pSub1);
   105021 
   105022   return 1;
   105023 }
   105024 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
   105025 
   105026 /*
   105027 ** Based on the contents of the AggInfo structure indicated by the first
   105028 ** argument, this function checks if the following are true:
   105029 **
   105030 **    * the query contains just a single aggregate function,
   105031 **    * the aggregate function is either min() or max(), and
   105032 **    * the argument to the aggregate function is a column value.
   105033 **
   105034 ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
   105035 ** is returned as appropriate. Also, *ppMinMax is set to point to the
   105036 ** list of arguments passed to the aggregate before returning.
   105037 **
   105038 ** Or, if the conditions above are not met, *ppMinMax is set to 0 and
   105039 ** WHERE_ORDERBY_NORMAL is returned.
   105040 */
   105041 static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
   105042   int eRet = WHERE_ORDERBY_NORMAL;          /* Return value */
   105043 
   105044   *ppMinMax = 0;
   105045   if( pAggInfo->nFunc==1 ){
   105046     Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
   105047     ExprList *pEList = pExpr->x.pList;      /* Arguments to agg function */
   105048 
   105049     assert( pExpr->op==TK_AGG_FUNCTION );
   105050     if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
   105051       const char *zFunc = pExpr->u.zToken;
   105052       if( sqlite3StrICmp(zFunc, "min")==0 ){
   105053         eRet = WHERE_ORDERBY_MIN;
   105054         *ppMinMax = pEList;
   105055       }else if( sqlite3StrICmp(zFunc, "max")==0 ){
   105056         eRet = WHERE_ORDERBY_MAX;
   105057         *ppMinMax = pEList;
   105058       }
   105059     }
   105060   }
   105061 
   105062   assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
   105063   return eRet;
   105064 }
   105065 
   105066 /*
   105067 ** The select statement passed as the first argument is an aggregate query.
   105068 ** The second argment is the associated aggregate-info object. This
   105069 ** function tests if the SELECT is of the form:
   105070 **
   105071 **   SELECT count(*) FROM <tbl>
   105072 **
   105073 ** where table is a database table, not a sub-select or view. If the query
   105074 ** does match this pattern, then a pointer to the Table object representing
   105075 ** <tbl> is returned. Otherwise, 0 is returned.
   105076 */
   105077 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
   105078   Table *pTab;
   105079   Expr *pExpr;
   105080 
   105081   assert( !p->pGroupBy );
   105082 
   105083   if( p->pWhere || p->pEList->nExpr!=1
   105084    || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
   105085   ){
   105086     return 0;
   105087   }
   105088   pTab = p->pSrc->a[0].pTab;
   105089   pExpr = p->pEList->a[0].pExpr;
   105090   assert( pTab && !pTab->pSelect && pExpr );
   105091 
   105092   if( IsVirtual(pTab) ) return 0;
   105093   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
   105094   if( NEVER(pAggInfo->nFunc==0) ) return 0;
   105095   if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
   105096   if( pExpr->flags&EP_Distinct ) return 0;
   105097 
   105098   return pTab;
   105099 }
   105100 
   105101 /*
   105102 ** If the source-list item passed as an argument was augmented with an
   105103 ** INDEXED BY clause, then try to locate the specified index. If there
   105104 ** was such a clause and the named index cannot be found, return
   105105 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
   105106 ** pFrom->pIndex and return SQLITE_OK.
   105107 */
   105108 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
   105109   if( pFrom->pTab && pFrom->zIndex ){
   105110     Table *pTab = pFrom->pTab;
   105111     char *zIndex = pFrom->zIndex;
   105112     Index *pIdx;
   105113     for(pIdx=pTab->pIndex;
   105114         pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
   105115         pIdx=pIdx->pNext
   105116     );
   105117     if( !pIdx ){
   105118       sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
   105119       pParse->checkSchema = 1;
   105120       return SQLITE_ERROR;
   105121     }
   105122     pFrom->pIndex = pIdx;
   105123   }
   105124   return SQLITE_OK;
   105125 }
   105126 /*
   105127 ** Detect compound SELECT statements that use an ORDER BY clause with
   105128 ** an alternative collating sequence.
   105129 **
   105130 **    SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
   105131 **
   105132 ** These are rewritten as a subquery:
   105133 **
   105134 **    SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
   105135 **     ORDER BY ... COLLATE ...
   105136 **
   105137 ** This transformation is necessary because the multiSelectOrderBy() routine
   105138 ** above that generates the code for a compound SELECT with an ORDER BY clause
   105139 ** uses a merge algorithm that requires the same collating sequence on the
   105140 ** result columns as on the ORDER BY clause.  See ticket
   105141 ** http://www.sqlite.org/src/info/6709574d2a
   105142 **
   105143 ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
   105144 ** The UNION ALL operator works fine with multiSelectOrderBy() even when
   105145 ** there are COLLATE terms in the ORDER BY.
   105146 */
   105147 static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
   105148   int i;
   105149   Select *pNew;
   105150   Select *pX;
   105151   sqlite3 *db;
   105152   struct ExprList_item *a;
   105153   SrcList *pNewSrc;
   105154   Parse *pParse;
   105155   Token dummy;
   105156 
   105157   if( p->pPrior==0 ) return WRC_Continue;
   105158   if( p->pOrderBy==0 ) return WRC_Continue;
   105159   for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
   105160   if( pX==0 ) return WRC_Continue;
   105161   a = p->pOrderBy->a;
   105162   for(i=p->pOrderBy->nExpr-1; i>=0; i--){
   105163     if( a[i].pExpr->flags & EP_Collate ) break;
   105164   }
   105165   if( i<0 ) return WRC_Continue;
   105166 
   105167   /* If we reach this point, that means the transformation is required. */
   105168 
   105169   pParse = pWalker->pParse;
   105170   db = pParse->db;
   105171   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
   105172   if( pNew==0 ) return WRC_Abort;
   105173   memset(&dummy, 0, sizeof(dummy));
   105174   pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
   105175   if( pNewSrc==0 ) return WRC_Abort;
   105176   *pNew = *p;
   105177   p->pSrc = pNewSrc;
   105178   p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ALL, 0));
   105179   p->op = TK_SELECT;
   105180   p->pWhere = 0;
   105181   pNew->pGroupBy = 0;
   105182   pNew->pHaving = 0;
   105183   pNew->pOrderBy = 0;
   105184   p->pPrior = 0;
   105185   p->pNext = 0;
   105186   p->selFlags &= ~SF_Compound;
   105187   assert( pNew->pPrior!=0 );
   105188   pNew->pPrior->pNext = pNew;
   105189   pNew->pLimit = 0;
   105190   pNew->pOffset = 0;
   105191   return WRC_Continue;
   105192 }
   105193 
   105194 #ifndef SQLITE_OMIT_CTE
   105195 /*
   105196 ** Argument pWith (which may be NULL) points to a linked list of nested
   105197 ** WITH contexts, from inner to outermost. If the table identified by
   105198 ** FROM clause element pItem is really a common-table-expression (CTE)
   105199 ** then return a pointer to the CTE definition for that table. Otherwise
   105200 ** return NULL.
   105201 **
   105202 ** If a non-NULL value is returned, set *ppContext to point to the With
   105203 ** object that the returned CTE belongs to.
   105204 */
   105205 static struct Cte *searchWith(
   105206   With *pWith,                    /* Current outermost WITH clause */
   105207   struct SrcList_item *pItem,     /* FROM clause element to resolve */
   105208   With **ppContext                /* OUT: WITH clause return value belongs to */
   105209 ){
   105210   const char *zName;
   105211   if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
   105212     With *p;
   105213     for(p=pWith; p; p=p->pOuter){
   105214       int i;
   105215       for(i=0; i<p->nCte; i++){
   105216         if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
   105217           *ppContext = p;
   105218           return &p->a[i];
   105219         }
   105220       }
   105221     }
   105222   }
   105223   return 0;
   105224 }
   105225 
   105226 /* The code generator maintains a stack of active WITH clauses
   105227 ** with the inner-most WITH clause being at the top of the stack.
   105228 **
   105229 ** This routine pushes the WITH clause passed as the second argument
   105230 ** onto the top of the stack. If argument bFree is true, then this
   105231 ** WITH clause will never be popped from the stack. In this case it
   105232 ** should be freed along with the Parse object. In other cases, when
   105233 ** bFree==0, the With object will be freed along with the SELECT
   105234 ** statement with which it is associated.
   105235 */
   105236 SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
   105237   assert( bFree==0 || pParse->pWith==0 );
   105238   if( pWith ){
   105239     pWith->pOuter = pParse->pWith;
   105240     pParse->pWith = pWith;
   105241     pParse->bFreeWith = bFree;
   105242   }
   105243 }
   105244 
   105245 /*
   105246 ** This function checks if argument pFrom refers to a CTE declared by
   105247 ** a WITH clause on the stack currently maintained by the parser. And,
   105248 ** if currently processing a CTE expression, if it is a recursive
   105249 ** reference to the current CTE.
   105250 **
   105251 ** If pFrom falls into either of the two categories above, pFrom->pTab
   105252 ** and other fields are populated accordingly. The caller should check
   105253 ** (pFrom->pTab!=0) to determine whether or not a successful match
   105254 ** was found.
   105255 **
   105256 ** Whether or not a match is found, SQLITE_OK is returned if no error
   105257 ** occurs. If an error does occur, an error message is stored in the
   105258 ** parser and some error code other than SQLITE_OK returned.
   105259 */
   105260 static int withExpand(
   105261   Walker *pWalker,
   105262   struct SrcList_item *pFrom
   105263 ){
   105264   Parse *pParse = pWalker->pParse;
   105265   sqlite3 *db = pParse->db;
   105266   struct Cte *pCte;               /* Matched CTE (or NULL if no match) */
   105267   With *pWith;                    /* WITH clause that pCte belongs to */
   105268 
   105269   assert( pFrom->pTab==0 );
   105270 
   105271   pCte = searchWith(pParse->pWith, pFrom, &pWith);
   105272   if( pCte ){
   105273     Table *pTab;
   105274     ExprList *pEList;
   105275     Select *pSel;
   105276     Select *pLeft;                /* Left-most SELECT statement */
   105277     int bMayRecursive;            /* True if compound joined by UNION [ALL] */
   105278     With *pSavedWith;             /* Initial value of pParse->pWith */
   105279 
   105280     /* If pCte->zErr is non-NULL at this point, then this is an illegal
   105281     ** recursive reference to CTE pCte. Leave an error in pParse and return
   105282     ** early. If pCte->zErr is NULL, then this is not a recursive reference.
   105283     ** In this case, proceed.  */
   105284     if( pCte->zErr ){
   105285       sqlite3ErrorMsg(pParse, pCte->zErr, pCte->zName);
   105286       return SQLITE_ERROR;
   105287     }
   105288 
   105289     assert( pFrom->pTab==0 );
   105290     pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
   105291     if( pTab==0 ) return WRC_Abort;
   105292     pTab->nRef = 1;
   105293     pTab->zName = sqlite3DbStrDup(db, pCte->zName);
   105294     pTab->iPKey = -1;
   105295     pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
   105296     pTab->tabFlags |= TF_Ephemeral;
   105297     pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
   105298     if( db->mallocFailed ) return SQLITE_NOMEM;
   105299     assert( pFrom->pSelect );
   105300 
   105301     /* Check if this is a recursive CTE. */
   105302     pSel = pFrom->pSelect;
   105303     bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
   105304     if( bMayRecursive ){
   105305       int i;
   105306       SrcList *pSrc = pFrom->pSelect->pSrc;
   105307       for(i=0; i<pSrc->nSrc; i++){
   105308         struct SrcList_item *pItem = &pSrc->a[i];
   105309         if( pItem->zDatabase==0
   105310          && pItem->zName!=0
   105311          && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
   105312           ){
   105313           pItem->pTab = pTab;
   105314           pItem->isRecursive = 1;
   105315           pTab->nRef++;
   105316           pSel->selFlags |= SF_Recursive;
   105317         }
   105318       }
   105319     }
   105320 
   105321     /* Only one recursive reference is permitted. */
   105322     if( pTab->nRef>2 ){
   105323       sqlite3ErrorMsg(
   105324           pParse, "multiple references to recursive table: %s", pCte->zName
   105325       );
   105326       return SQLITE_ERROR;
   105327     }
   105328     assert( pTab->nRef==1 || ((pSel->selFlags&SF_Recursive) && pTab->nRef==2 ));
   105329 
   105330     pCte->zErr = "circular reference: %s";
   105331     pSavedWith = pParse->pWith;
   105332     pParse->pWith = pWith;
   105333     sqlite3WalkSelect(pWalker, bMayRecursive ? pSel->pPrior : pSel);
   105334 
   105335     for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
   105336     pEList = pLeft->pEList;
   105337     if( pCte->pCols ){
   105338       if( pEList->nExpr!=pCte->pCols->nExpr ){
   105339         sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
   105340             pCte->zName, pEList->nExpr, pCte->pCols->nExpr
   105341         );
   105342         pParse->pWith = pSavedWith;
   105343         return SQLITE_ERROR;
   105344       }
   105345       pEList = pCte->pCols;
   105346     }
   105347 
   105348     selectColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
   105349     if( bMayRecursive ){
   105350       if( pSel->selFlags & SF_Recursive ){
   105351         pCte->zErr = "multiple recursive references: %s";
   105352       }else{
   105353         pCte->zErr = "recursive reference in a subquery: %s";
   105354       }
   105355       sqlite3WalkSelect(pWalker, pSel);
   105356     }
   105357     pCte->zErr = 0;
   105358     pParse->pWith = pSavedWith;
   105359   }
   105360 
   105361   return SQLITE_OK;
   105362 }
   105363 #endif
   105364 
   105365 #ifndef SQLITE_OMIT_CTE
   105366 /*
   105367 ** If the SELECT passed as the second argument has an associated WITH
   105368 ** clause, pop it from the stack stored as part of the Parse object.
   105369 **
   105370 ** This function is used as the xSelectCallback2() callback by
   105371 ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
   105372 ** names and other FROM clause elements.
   105373 */
   105374 static void selectPopWith(Walker *pWalker, Select *p){
   105375   Parse *pParse = pWalker->pParse;
   105376   With *pWith = findRightmost(p)->pWith;
   105377   if( pWith!=0 ){
   105378     assert( pParse->pWith==pWith );
   105379     pParse->pWith = pWith->pOuter;
   105380   }
   105381 }
   105382 #else
   105383 #define selectPopWith 0
   105384 #endif
   105385 
   105386 /*
   105387 ** This routine is a Walker callback for "expanding" a SELECT statement.
   105388 ** "Expanding" means to do the following:
   105389 **
   105390 **    (1)  Make sure VDBE cursor numbers have been assigned to every
   105391 **         element of the FROM clause.
   105392 **
   105393 **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
   105394 **         defines FROM clause.  When views appear in the FROM clause,
   105395 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
   105396 **         that implements the view.  A copy is made of the view's SELECT
   105397 **         statement so that we can freely modify or delete that statement
   105398 **         without worrying about messing up the presistent representation
   105399 **         of the view.
   105400 **
   105401 **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
   105402 **         on joins and the ON and USING clause of joins.
   105403 **
   105404 **    (4)  Scan the list of columns in the result set (pEList) looking
   105405 **         for instances of the "*" operator or the TABLE.* operator.
   105406 **         If found, expand each "*" to be every column in every table
   105407 **         and TABLE.* to be every column in TABLE.
   105408 **
   105409 */
   105410 static int selectExpander(Walker *pWalker, Select *p){
   105411   Parse *pParse = pWalker->pParse;
   105412   int i, j, k;
   105413   SrcList *pTabList;
   105414   ExprList *pEList;
   105415   struct SrcList_item *pFrom;
   105416   sqlite3 *db = pParse->db;
   105417   Expr *pE, *pRight, *pExpr;
   105418   u16 selFlags = p->selFlags;
   105419 
   105420   p->selFlags |= SF_Expanded;
   105421   if( db->mallocFailed  ){
   105422     return WRC_Abort;
   105423   }
   105424   if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
   105425     return WRC_Prune;
   105426   }
   105427   pTabList = p->pSrc;
   105428   pEList = p->pEList;
   105429   sqlite3WithPush(pParse, findRightmost(p)->pWith, 0);
   105430 
   105431   /* Make sure cursor numbers have been assigned to all entries in
   105432   ** the FROM clause of the SELECT statement.
   105433   */
   105434   sqlite3SrcListAssignCursors(pParse, pTabList);
   105435 
   105436   /* Look up every table named in the FROM clause of the select.  If
   105437   ** an entry of the FROM clause is a subquery instead of a table or view,
   105438   ** then create a transient table structure to describe the subquery.
   105439   */
   105440   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
   105441     Table *pTab;
   105442     assert( pFrom->isRecursive==0 || pFrom->pTab );
   105443     if( pFrom->isRecursive ) continue;
   105444     if( pFrom->pTab!=0 ){
   105445       /* This statement has already been prepared.  There is no need
   105446       ** to go further. */
   105447       assert( i==0 );
   105448 #ifndef SQLITE_OMIT_CTE
   105449       selectPopWith(pWalker, p);
   105450 #endif
   105451       return WRC_Prune;
   105452     }
   105453 #ifndef SQLITE_OMIT_CTE
   105454     if( withExpand(pWalker, pFrom) ) return WRC_Abort;
   105455     if( pFrom->pTab ) {} else
   105456 #endif
   105457     if( pFrom->zName==0 ){
   105458 #ifndef SQLITE_OMIT_SUBQUERY
   105459       Select *pSel = pFrom->pSelect;
   105460       /* A sub-query in the FROM clause of a SELECT */
   105461       assert( pSel!=0 );
   105462       assert( pFrom->pTab==0 );
   105463       sqlite3WalkSelect(pWalker, pSel);
   105464       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
   105465       if( pTab==0 ) return WRC_Abort;
   105466       pTab->nRef = 1;
   105467       pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab);
   105468       while( pSel->pPrior ){ pSel = pSel->pPrior; }
   105469       selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
   105470       pTab->iPKey = -1;
   105471       pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
   105472       pTab->tabFlags |= TF_Ephemeral;
   105473 #endif
   105474     }else{
   105475       /* An ordinary table or view name in the FROM clause */
   105476       assert( pFrom->pTab==0 );
   105477       pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
   105478       if( pTab==0 ) return WRC_Abort;
   105479       if( pTab->nRef==0xffff ){
   105480         sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
   105481            pTab->zName);
   105482         pFrom->pTab = 0;
   105483         return WRC_Abort;
   105484       }
   105485       pTab->nRef++;
   105486 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
   105487       if( pTab->pSelect || IsVirtual(pTab) ){
   105488         /* We reach here if the named table is a really a view */
   105489         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
   105490         assert( pFrom->pSelect==0 );
   105491         pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
   105492         sqlite3WalkSelect(pWalker, pFrom->pSelect);
   105493       }
   105494 #endif
   105495     }
   105496 
   105497     /* Locate the index named by the INDEXED BY clause, if any. */
   105498     if( sqlite3IndexedByLookup(pParse, pFrom) ){
   105499       return WRC_Abort;
   105500     }
   105501   }
   105502 
   105503   /* Process NATURAL keywords, and ON and USING clauses of joins.
   105504   */
   105505   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
   105506     return WRC_Abort;
   105507   }
   105508 
   105509   /* For every "*" that occurs in the column list, insert the names of
   105510   ** all columns in all tables.  And for every TABLE.* insert the names
   105511   ** of all columns in TABLE.  The parser inserted a special expression
   105512   ** with the TK_ALL operator for each "*" that it found in the column list.
   105513   ** The following code just has to locate the TK_ALL expressions and expand
   105514   ** each one to the list of all columns in all tables.
   105515   **
   105516   ** The first loop just checks to see if there are any "*" operators
   105517   ** that need expanding.
   105518   */
   105519   for(k=0; k<pEList->nExpr; k++){
   105520     pE = pEList->a[k].pExpr;
   105521     if( pE->op==TK_ALL ) break;
   105522     assert( pE->op!=TK_DOT || pE->pRight!=0 );
   105523     assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
   105524     if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
   105525   }
   105526   if( k<pEList->nExpr ){
   105527     /*
   105528     ** If we get here it means the result set contains one or more "*"
   105529     ** operators that need to be expanded.  Loop through each expression
   105530     ** in the result set and expand them one by one.
   105531     */
   105532     struct ExprList_item *a = pEList->a;
   105533     ExprList *pNew = 0;
   105534     int flags = pParse->db->flags;
   105535     int longNames = (flags & SQLITE_FullColNames)!=0
   105536                       && (flags & SQLITE_ShortColNames)==0;
   105537 
   105538     /* When processing FROM-clause subqueries, it is always the case
   105539     ** that full_column_names=OFF and short_column_names=ON.  The
   105540     ** sqlite3ResultSetOfSelect() routine makes it so. */
   105541     assert( (p->selFlags & SF_NestedFrom)==0
   105542           || ((flags & SQLITE_FullColNames)==0 &&
   105543               (flags & SQLITE_ShortColNames)!=0) );
   105544 
   105545     for(k=0; k<pEList->nExpr; k++){
   105546       pE = a[k].pExpr;
   105547       pRight = pE->pRight;
   105548       assert( pE->op!=TK_DOT || pRight!=0 );
   105549       if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pRight->op!=TK_ALL) ){
   105550         /* This particular expression does not need to be expanded.
   105551         */
   105552         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
   105553         if( pNew ){
   105554           pNew->a[pNew->nExpr-1].zName = a[k].zName;
   105555           pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
   105556           a[k].zName = 0;
   105557           a[k].zSpan = 0;
   105558         }
   105559         a[k].pExpr = 0;
   105560       }else{
   105561         /* This expression is a "*" or a "TABLE.*" and needs to be
   105562         ** expanded. */
   105563         int tableSeen = 0;      /* Set to 1 when TABLE matches */
   105564         char *zTName = 0;       /* text of name of TABLE */
   105565         if( pE->op==TK_DOT ){
   105566           assert( pE->pLeft!=0 );
   105567           assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
   105568           zTName = pE->pLeft->u.zToken;
   105569         }
   105570         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
   105571           Table *pTab = pFrom->pTab;
   105572           Select *pSub = pFrom->pSelect;
   105573           char *zTabName = pFrom->zAlias;
   105574           const char *zSchemaName = 0;
   105575           int iDb;
   105576           if( zTabName==0 ){
   105577             zTabName = pTab->zName;
   105578           }
   105579           if( db->mallocFailed ) break;
   105580           if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
   105581             pSub = 0;
   105582             if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
   105583               continue;
   105584             }
   105585             iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   105586             zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*";
   105587           }
   105588           for(j=0; j<pTab->nCol; j++){
   105589             char *zName = pTab->aCol[j].zName;
   105590             char *zColname;  /* The computed column name */
   105591             char *zToFree;   /* Malloced string that needs to be freed */
   105592             Token sColname;  /* Computed column name as a token */
   105593 
   105594             assert( zName );
   105595             if( zTName && pSub
   105596              && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
   105597             ){
   105598               continue;
   105599             }
   105600 
   105601             /* If a column is marked as 'hidden' (currently only possible
   105602             ** for virtual tables), do not include it in the expanded
   105603             ** result-set list.
   105604             */
   105605             if( IsHiddenColumn(&pTab->aCol[j]) ){
   105606               assert(IsVirtual(pTab));
   105607               continue;
   105608             }
   105609             tableSeen = 1;
   105610 
   105611             if( i>0 && zTName==0 ){
   105612               if( (pFrom->jointype & JT_NATURAL)!=0
   105613                 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
   105614               ){
   105615                 /* In a NATURAL join, omit the join columns from the
   105616                 ** table to the right of the join */
   105617                 continue;
   105618               }
   105619               if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
   105620                 /* In a join with a USING clause, omit columns in the
   105621                 ** using clause from the table on the right. */
   105622                 continue;
   105623               }
   105624             }
   105625             pRight = sqlite3Expr(db, TK_ID, zName);
   105626             zColname = zName;
   105627             zToFree = 0;
   105628             if( longNames || pTabList->nSrc>1 ){
   105629               Expr *pLeft;
   105630               pLeft = sqlite3Expr(db, TK_ID, zTabName);
   105631               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
   105632               if( zSchemaName ){
   105633                 pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
   105634                 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0);
   105635               }
   105636               if( longNames ){
   105637                 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
   105638                 zToFree = zColname;
   105639               }
   105640             }else{
   105641               pExpr = pRight;
   105642             }
   105643             pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
   105644             sColname.z = zColname;
   105645             sColname.n = sqlite3Strlen30(zColname);
   105646             sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
   105647             if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
   105648               struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
   105649               if( pSub ){
   105650                 pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
   105651                 testcase( pX->zSpan==0 );
   105652               }else{
   105653                 pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
   105654                                            zSchemaName, zTabName, zColname);
   105655                 testcase( pX->zSpan==0 );
   105656               }
   105657               pX->bSpanIsTab = 1;
   105658             }
   105659             sqlite3DbFree(db, zToFree);
   105660           }
   105661         }
   105662         if( !tableSeen ){
   105663           if( zTName ){
   105664             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
   105665           }else{
   105666             sqlite3ErrorMsg(pParse, "no tables specified");
   105667           }
   105668         }
   105669       }
   105670     }
   105671     sqlite3ExprListDelete(db, pEList);
   105672     p->pEList = pNew;
   105673   }
   105674 #if SQLITE_MAX_COLUMN
   105675   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
   105676     sqlite3ErrorMsg(pParse, "too many columns in result set");
   105677   }
   105678 #endif
   105679   return WRC_Continue;
   105680 }
   105681 
   105682 /*
   105683 ** No-op routine for the parse-tree walker.
   105684 **
   105685 ** When this routine is the Walker.xExprCallback then expression trees
   105686 ** are walked without any actions being taken at each node.  Presumably,
   105687 ** when this routine is used for Walker.xExprCallback then
   105688 ** Walker.xSelectCallback is set to do something useful for every
   105689 ** subquery in the parser tree.
   105690 */
   105691 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
   105692   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   105693   return WRC_Continue;
   105694 }
   105695 
   105696 /*
   105697 ** This routine "expands" a SELECT statement and all of its subqueries.
   105698 ** For additional information on what it means to "expand" a SELECT
   105699 ** statement, see the comment on the selectExpand worker callback above.
   105700 **
   105701 ** Expanding a SELECT statement is the first step in processing a
   105702 ** SELECT statement.  The SELECT statement must be expanded before
   105703 ** name resolution is performed.
   105704 **
   105705 ** If anything goes wrong, an error message is written into pParse.
   105706 ** The calling function can detect the problem by looking at pParse->nErr
   105707 ** and/or pParse->db->mallocFailed.
   105708 */
   105709 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
   105710   Walker w;
   105711   memset(&w, 0, sizeof(w));
   105712   w.xExprCallback = exprWalkNoop;
   105713   w.pParse = pParse;
   105714   if( pParse->hasCompound ){
   105715     w.xSelectCallback = convertCompoundSelectToSubquery;
   105716     sqlite3WalkSelect(&w, pSelect);
   105717   }
   105718   w.xSelectCallback = selectExpander;
   105719   w.xSelectCallback2 = selectPopWith;
   105720   sqlite3WalkSelect(&w, pSelect);
   105721 }
   105722 
   105723 
   105724 #ifndef SQLITE_OMIT_SUBQUERY
   105725 /*
   105726 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
   105727 ** interface.
   105728 **
   105729 ** For each FROM-clause subquery, add Column.zType and Column.zColl
   105730 ** information to the Table structure that represents the result set
   105731 ** of that subquery.
   105732 **
   105733 ** The Table structure that represents the result set was constructed
   105734 ** by selectExpander() but the type and collation information was omitted
   105735 ** at that point because identifiers had not yet been resolved.  This
   105736 ** routine is called after identifier resolution.
   105737 */
   105738 static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
   105739   Parse *pParse;
   105740   int i;
   105741   SrcList *pTabList;
   105742   struct SrcList_item *pFrom;
   105743 
   105744   assert( p->selFlags & SF_Resolved );
   105745   if( (p->selFlags & SF_HasTypeInfo)==0 ){
   105746     p->selFlags |= SF_HasTypeInfo;
   105747     pParse = pWalker->pParse;
   105748     pTabList = p->pSrc;
   105749     for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
   105750       Table *pTab = pFrom->pTab;
   105751       if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
   105752         /* A sub-query in the FROM clause of a SELECT */
   105753         Select *pSel = pFrom->pSelect;
   105754         if( pSel ){
   105755           while( pSel->pPrior ) pSel = pSel->pPrior;
   105756           selectAddColumnTypeAndCollation(pParse, pTab, pSel);
   105757         }
   105758       }
   105759     }
   105760   }
   105761 }
   105762 #endif
   105763 
   105764 
   105765 /*
   105766 ** This routine adds datatype and collating sequence information to
   105767 ** the Table structures of all FROM-clause subqueries in a
   105768 ** SELECT statement.
   105769 **
   105770 ** Use this routine after name resolution.
   105771 */
   105772 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
   105773 #ifndef SQLITE_OMIT_SUBQUERY
   105774   Walker w;
   105775   memset(&w, 0, sizeof(w));
   105776   w.xSelectCallback2 = selectAddSubqueryTypeInfo;
   105777   w.xExprCallback = exprWalkNoop;
   105778   w.pParse = pParse;
   105779   sqlite3WalkSelect(&w, pSelect);
   105780 #endif
   105781 }
   105782 
   105783 
   105784 /*
   105785 ** This routine sets up a SELECT statement for processing.  The
   105786 ** following is accomplished:
   105787 **
   105788 **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
   105789 **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
   105790 **     *  ON and USING clauses are shifted into WHERE statements
   105791 **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
   105792 **     *  Identifiers in expression are matched to tables.
   105793 **
   105794 ** This routine acts recursively on all subqueries within the SELECT.
   105795 */
   105796 SQLITE_PRIVATE void sqlite3SelectPrep(
   105797   Parse *pParse,         /* The parser context */
   105798   Select *p,             /* The SELECT statement being coded. */
   105799   NameContext *pOuterNC  /* Name context for container */
   105800 ){
   105801   sqlite3 *db;
   105802   if( NEVER(p==0) ) return;
   105803   db = pParse->db;
   105804   if( db->mallocFailed ) return;
   105805   if( p->selFlags & SF_HasTypeInfo ) return;
   105806   sqlite3SelectExpand(pParse, p);
   105807   if( pParse->nErr || db->mallocFailed ) return;
   105808   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
   105809   if( pParse->nErr || db->mallocFailed ) return;
   105810   sqlite3SelectAddTypeInfo(pParse, p);
   105811 }
   105812 
   105813 /*
   105814 ** Reset the aggregate accumulator.
   105815 **
   105816 ** The aggregate accumulator is a set of memory cells that hold
   105817 ** intermediate results while calculating an aggregate.  This
   105818 ** routine generates code that stores NULLs in all of those memory
   105819 ** cells.
   105820 */
   105821 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
   105822   Vdbe *v = pParse->pVdbe;
   105823   int i;
   105824   struct AggInfo_func *pFunc;
   105825   int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
   105826   if( nReg==0 ) return;
   105827 #ifdef SQLITE_DEBUG
   105828   /* Verify that all AggInfo registers are within the range specified by
   105829   ** AggInfo.mnReg..AggInfo.mxReg */
   105830   assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
   105831   for(i=0; i<pAggInfo->nColumn; i++){
   105832     assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
   105833          && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
   105834   }
   105835   for(i=0; i<pAggInfo->nFunc; i++){
   105836     assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
   105837          && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
   105838   }
   105839 #endif
   105840   sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
   105841   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
   105842     if( pFunc->iDistinct>=0 ){
   105843       Expr *pE = pFunc->pExpr;
   105844       assert( !ExprHasProperty(pE, EP_xIsSelect) );
   105845       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
   105846         sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
   105847            "argument");
   105848         pFunc->iDistinct = -1;
   105849       }else{
   105850         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0);
   105851         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
   105852                           (char*)pKeyInfo, P4_KEYINFO);
   105853       }
   105854     }
   105855   }
   105856 }
   105857 
   105858 /*
   105859 ** Invoke the OP_AggFinalize opcode for every aggregate function
   105860 ** in the AggInfo structure.
   105861 */
   105862 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
   105863   Vdbe *v = pParse->pVdbe;
   105864   int i;
   105865   struct AggInfo_func *pF;
   105866   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
   105867     ExprList *pList = pF->pExpr->x.pList;
   105868     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
   105869     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
   105870                       (void*)pF->pFunc, P4_FUNCDEF);
   105871   }
   105872 }
   105873 
   105874 /*
   105875 ** Update the accumulator memory cells for an aggregate based on
   105876 ** the current cursor position.
   105877 */
   105878 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
   105879   Vdbe *v = pParse->pVdbe;
   105880   int i;
   105881   int regHit = 0;
   105882   int addrHitTest = 0;
   105883   struct AggInfo_func *pF;
   105884   struct AggInfo_col *pC;
   105885 
   105886   pAggInfo->directMode = 1;
   105887   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
   105888     int nArg;
   105889     int addrNext = 0;
   105890     int regAgg;
   105891     ExprList *pList = pF->pExpr->x.pList;
   105892     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
   105893     if( pList ){
   105894       nArg = pList->nExpr;
   105895       regAgg = sqlite3GetTempRange(pParse, nArg);
   105896       sqlite3ExprCodeExprList(pParse, pList, regAgg, SQLITE_ECEL_DUP);
   105897     }else{
   105898       nArg = 0;
   105899       regAgg = 0;
   105900     }
   105901     if( pF->iDistinct>=0 ){
   105902       addrNext = sqlite3VdbeMakeLabel(v);
   105903       assert( nArg==1 );
   105904       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
   105905     }
   105906     if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
   105907       CollSeq *pColl = 0;
   105908       struct ExprList_item *pItem;
   105909       int j;
   105910       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
   105911       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
   105912         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
   105913       }
   105914       if( !pColl ){
   105915         pColl = pParse->db->pDfltColl;
   105916       }
   105917       if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
   105918       sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
   105919     }
   105920     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
   105921                       (void*)pF->pFunc, P4_FUNCDEF);
   105922     sqlite3VdbeChangeP5(v, (u8)nArg);
   105923     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
   105924     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
   105925     if( addrNext ){
   105926       sqlite3VdbeResolveLabel(v, addrNext);
   105927       sqlite3ExprCacheClear(pParse);
   105928     }
   105929   }
   105930 
   105931   /* Before populating the accumulator registers, clear the column cache.
   105932   ** Otherwise, if any of the required column values are already present
   105933   ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
   105934   ** to pC->iMem. But by the time the value is used, the original register
   105935   ** may have been used, invalidating the underlying buffer holding the
   105936   ** text or blob value. See ticket [883034dcb5].
   105937   **
   105938   ** Another solution would be to change the OP_SCopy used to copy cached
   105939   ** values to an OP_Copy.
   105940   */
   105941   if( regHit ){
   105942     addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
   105943   }
   105944   sqlite3ExprCacheClear(pParse);
   105945   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
   105946     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
   105947   }
   105948   pAggInfo->directMode = 0;
   105949   sqlite3ExprCacheClear(pParse);
   105950   if( addrHitTest ){
   105951     sqlite3VdbeJumpHere(v, addrHitTest);
   105952   }
   105953 }
   105954 
   105955 /*
   105956 ** Add a single OP_Explain instruction to the VDBE to explain a simple
   105957 ** count(*) query ("SELECT count(*) FROM pTab").
   105958 */
   105959 #ifndef SQLITE_OMIT_EXPLAIN
   105960 static void explainSimpleCount(
   105961   Parse *pParse,                  /* Parse context */
   105962   Table *pTab,                    /* Table being queried */
   105963   Index *pIdx                     /* Index used to optimize scan, or NULL */
   105964 ){
   105965   if( pParse->explain==2 ){
   105966     int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
   105967     char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
   105968         pTab->zName,
   105969         bCover ? " USING COVERING INDEX " : "",
   105970         bCover ? pIdx->zName : ""
   105971     );
   105972     sqlite3VdbeAddOp4(
   105973         pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
   105974     );
   105975   }
   105976 }
   105977 #else
   105978 # define explainSimpleCount(a,b,c)
   105979 #endif
   105980 
   105981 /*
   105982 ** Generate code for the SELECT statement given in the p argument.
   105983 **
   105984 ** The results are returned according to the SelectDest structure.
   105985 ** See comments in sqliteInt.h for further information.
   105986 **
   105987 ** This routine returns the number of errors.  If any errors are
   105988 ** encountered, then an appropriate error message is left in
   105989 ** pParse->zErrMsg.
   105990 **
   105991 ** This routine does NOT free the Select structure passed in.  The
   105992 ** calling function needs to do that.
   105993 */
   105994 SQLITE_PRIVATE int sqlite3Select(
   105995   Parse *pParse,         /* The parser context */
   105996   Select *p,             /* The SELECT statement being coded. */
   105997   SelectDest *pDest      /* What to do with the query results */
   105998 ){
   105999   int i, j;              /* Loop counters */
   106000   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
   106001   Vdbe *v;               /* The virtual machine under construction */
   106002   int isAgg;             /* True for select lists like "count(*)" */
   106003   ExprList *pEList;      /* List of columns to extract. */
   106004   SrcList *pTabList;     /* List of tables to select from */
   106005   Expr *pWhere;          /* The WHERE clause.  May be NULL */
   106006   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
   106007   Expr *pHaving;         /* The HAVING clause.  May be NULL */
   106008   int rc = 1;            /* Value to return from this function */
   106009   DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
   106010   SortCtx sSort;         /* Info on how to code the ORDER BY clause */
   106011   AggInfo sAggInfo;      /* Information used by aggregate queries */
   106012   int iEnd;              /* Address of the end of the query */
   106013   sqlite3 *db;           /* The database connection */
   106014 
   106015 #ifndef SQLITE_OMIT_EXPLAIN
   106016   int iRestoreSelectId = pParse->iSelectId;
   106017   pParse->iSelectId = pParse->iNextSelectId++;
   106018 #endif
   106019 
   106020   db = pParse->db;
   106021   if( p==0 || db->mallocFailed || pParse->nErr ){
   106022     return 1;
   106023   }
   106024   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
   106025   memset(&sAggInfo, 0, sizeof(sAggInfo));
   106026 
   106027   assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
   106028   assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
   106029   assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
   106030   assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
   106031   if( IgnorableOrderby(pDest) ){
   106032     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
   106033            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
   106034            pDest->eDest==SRT_Queue  || pDest->eDest==SRT_DistFifo ||
   106035            pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
   106036     /* If ORDER BY makes no difference in the output then neither does
   106037     ** DISTINCT so it can be removed too. */
   106038     sqlite3ExprListDelete(db, p->pOrderBy);
   106039     p->pOrderBy = 0;
   106040     p->selFlags &= ~SF_Distinct;
   106041   }
   106042   sqlite3SelectPrep(pParse, p, 0);
   106043   memset(&sSort, 0, sizeof(sSort));
   106044   sSort.pOrderBy = p->pOrderBy;
   106045   pTabList = p->pSrc;
   106046   pEList = p->pEList;
   106047   if( pParse->nErr || db->mallocFailed ){
   106048     goto select_end;
   106049   }
   106050   isAgg = (p->selFlags & SF_Aggregate)!=0;
   106051   assert( pEList!=0 );
   106052 
   106053   /* Begin generating code.
   106054   */
   106055   v = sqlite3GetVdbe(pParse);
   106056   if( v==0 ) goto select_end;
   106057 
   106058   /* If writing to memory or generating a set
   106059   ** only a single column may be output.
   106060   */
   106061 #ifndef SQLITE_OMIT_SUBQUERY
   106062   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
   106063     goto select_end;
   106064   }
   106065 #endif
   106066 
   106067   /* Generate code for all sub-queries in the FROM clause
   106068   */
   106069 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
   106070   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
   106071     struct SrcList_item *pItem = &pTabList->a[i];
   106072     SelectDest dest;
   106073     Select *pSub = pItem->pSelect;
   106074     int isAggSub;
   106075 
   106076     if( pSub==0 ) continue;
   106077 
   106078     /* Sometimes the code for a subquery will be generated more than
   106079     ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
   106080     ** for example.  In that case, do not regenerate the code to manifest
   106081     ** a view or the co-routine to implement a view.  The first instance
   106082     ** is sufficient, though the subroutine to manifest the view does need
   106083     ** to be invoked again. */
   106084     if( pItem->addrFillSub ){
   106085       if( pItem->viaCoroutine==0 ){
   106086         sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
   106087       }
   106088       continue;
   106089     }
   106090 
   106091     /* Increment Parse.nHeight by the height of the largest expression
   106092     ** tree referred to by this, the parent select. The child select
   106093     ** may contain expression trees of at most
   106094     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
   106095     ** more conservative than necessary, but much easier than enforcing
   106096     ** an exact limit.
   106097     */
   106098     pParse->nHeight += sqlite3SelectExprHeight(p);
   106099 
   106100     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
   106101     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
   106102       /* This subquery can be absorbed into its parent. */
   106103       if( isAggSub ){
   106104         isAgg = 1;
   106105         p->selFlags |= SF_Aggregate;
   106106       }
   106107       i = -1;
   106108     }else if( pTabList->nSrc==1
   106109            && OptimizationEnabled(db, SQLITE_SubqCoroutine)
   106110     ){
   106111       /* Implement a co-routine that will return a single row of the result
   106112       ** set on each invocation.
   106113       */
   106114       int addrTop = sqlite3VdbeCurrentAddr(v)+1;
   106115       pItem->regReturn = ++pParse->nMem;
   106116       sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
   106117       VdbeComment((v, "%s", pItem->pTab->zName));
   106118       pItem->addrFillSub = addrTop;
   106119       sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
   106120       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
   106121       sqlite3Select(pParse, pSub, &dest);
   106122       pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow);
   106123       pItem->viaCoroutine = 1;
   106124       pItem->regResult = dest.iSdst;
   106125       sqlite3VdbeAddOp1(v, OP_EndCoroutine, pItem->regReturn);
   106126       sqlite3VdbeJumpHere(v, addrTop-1);
   106127       sqlite3ClearTempRegCache(pParse);
   106128     }else{
   106129       /* Generate a subroutine that will fill an ephemeral table with
   106130       ** the content of this subquery.  pItem->addrFillSub will point
   106131       ** to the address of the generated subroutine.  pItem->regReturn
   106132       ** is a register allocated to hold the subroutine return address
   106133       */
   106134       int topAddr;
   106135       int onceAddr = 0;
   106136       int retAddr;
   106137       assert( pItem->addrFillSub==0 );
   106138       pItem->regReturn = ++pParse->nMem;
   106139       topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
   106140       pItem->addrFillSub = topAddr+1;
   106141       if( pItem->isCorrelated==0 ){
   106142         /* If the subquery is not correlated and if we are not inside of
   106143         ** a trigger, then we only need to compute the value of the subquery
   106144         ** once. */
   106145         onceAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
   106146         VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
   106147       }else{
   106148         VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
   106149       }
   106150       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
   106151       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
   106152       sqlite3Select(pParse, pSub, &dest);
   106153       pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow);
   106154       if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
   106155       retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
   106156       VdbeComment((v, "end %s", pItem->pTab->zName));
   106157       sqlite3VdbeChangeP1(v, topAddr, retAddr);
   106158       sqlite3ClearTempRegCache(pParse);
   106159     }
   106160     if( /*pParse->nErr ||*/ db->mallocFailed ){
   106161       goto select_end;
   106162     }
   106163     pParse->nHeight -= sqlite3SelectExprHeight(p);
   106164     pTabList = p->pSrc;
   106165     if( !IgnorableOrderby(pDest) ){
   106166       sSort.pOrderBy = p->pOrderBy;
   106167     }
   106168   }
   106169   pEList = p->pEList;
   106170 #endif
   106171   pWhere = p->pWhere;
   106172   pGroupBy = p->pGroupBy;
   106173   pHaving = p->pHaving;
   106174   sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
   106175 
   106176 #ifndef SQLITE_OMIT_COMPOUND_SELECT
   106177   /* If there is are a sequence of queries, do the earlier ones first.
   106178   */
   106179   if( p->pPrior ){
   106180     rc = multiSelect(pParse, p, pDest);
   106181     explainSetInteger(pParse->iSelectId, iRestoreSelectId);
   106182     return rc;
   106183   }
   106184 #endif
   106185 
   106186   /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
   106187   ** if the select-list is the same as the ORDER BY list, then this query
   106188   ** can be rewritten as a GROUP BY. In other words, this:
   106189   **
   106190   **     SELECT DISTINCT xyz FROM ... ORDER BY xyz
   106191   **
   106192   ** is transformed to:
   106193   **
   106194   **     SELECT xyz FROM ... GROUP BY xyz
   106195   **
   106196   ** The second form is preferred as a single index (or temp-table) may be
   106197   ** used for both the ORDER BY and DISTINCT processing. As originally
   106198   ** written the query must use a temp-table for at least one of the ORDER
   106199   ** BY and DISTINCT, and an index or separate temp-table for the other.
   106200   */
   106201   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
   106202    && sqlite3ExprListCompare(sSort.pOrderBy, p->pEList, -1)==0
   106203   ){
   106204     p->selFlags &= ~SF_Distinct;
   106205     p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
   106206     pGroupBy = p->pGroupBy;
   106207     sSort.pOrderBy = 0;
   106208     /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
   106209     ** the sDistinct.isTnct is still set.  Hence, isTnct represents the
   106210     ** original setting of the SF_Distinct flag, not the current setting */
   106211     assert( sDistinct.isTnct );
   106212   }
   106213 
   106214   /* If there is an ORDER BY clause, then this sorting
   106215   ** index might end up being unused if the data can be
   106216   ** extracted in pre-sorted order.  If that is the case, then the
   106217   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
   106218   ** we figure out that the sorting index is not needed.  The addrSortIndex
   106219   ** variable is used to facilitate that change.
   106220   */
   106221   if( sSort.pOrderBy ){
   106222     KeyInfo *pKeyInfo;
   106223     pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, 0);
   106224     sSort.iECursor = pParse->nTab++;
   106225     sSort.addrSortIndex =
   106226       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
   106227                            sSort.iECursor, sSort.pOrderBy->nExpr+2, 0,
   106228                            (char*)pKeyInfo, P4_KEYINFO);
   106229   }else{
   106230     sSort.addrSortIndex = -1;
   106231   }
   106232 
   106233   /* If the output is destined for a temporary table, open that table.
   106234   */
   106235   if( pDest->eDest==SRT_EphemTab ){
   106236     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
   106237   }
   106238 
   106239   /* Set the limiter.
   106240   */
   106241   iEnd = sqlite3VdbeMakeLabel(v);
   106242   p->nSelectRow = LARGEST_INT64;
   106243   computeLimitRegisters(pParse, p, iEnd);
   106244   if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
   106245     sqlite3VdbeGetOp(v, sSort.addrSortIndex)->opcode = OP_SorterOpen;
   106246     sSort.sortFlags |= SORTFLAG_UseSorter;
   106247   }
   106248 
   106249   /* Open a virtual index to use for the distinct set.
   106250   */
   106251   if( p->selFlags & SF_Distinct ){
   106252     sDistinct.tabTnct = pParse->nTab++;
   106253     sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
   106254                                 sDistinct.tabTnct, 0, 0,
   106255                                 (char*)keyInfoFromExprList(pParse, p->pEList,0,0),
   106256                                 P4_KEYINFO);
   106257     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
   106258     sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
   106259   }else{
   106260     sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
   106261   }
   106262 
   106263   if( !isAgg && pGroupBy==0 ){
   106264     /* No aggregate functions and no GROUP BY clause */
   106265     u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
   106266 
   106267     /* Begin the database scan. */
   106268     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
   106269                                p->pEList, wctrlFlags, 0);
   106270     if( pWInfo==0 ) goto select_end;
   106271     if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
   106272       p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
   106273     }
   106274     if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
   106275       sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
   106276     }
   106277     if( sSort.pOrderBy ){
   106278       sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
   106279       if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
   106280         sSort.pOrderBy = 0;
   106281       }
   106282     }
   106283 
   106284     /* If sorting index that was created by a prior OP_OpenEphemeral
   106285     ** instruction ended up not being needed, then change the OP_OpenEphemeral
   106286     ** into an OP_Noop.
   106287     */
   106288     if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
   106289       sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
   106290     }
   106291 
   106292     /* Use the standard inner loop. */
   106293     selectInnerLoop(pParse, p, pEList, -1, &sSort, &sDistinct, pDest,
   106294                     sqlite3WhereContinueLabel(pWInfo),
   106295                     sqlite3WhereBreakLabel(pWInfo));
   106296 
   106297     /* End the database scan loop.
   106298     */
   106299     sqlite3WhereEnd(pWInfo);
   106300   }else{
   106301     /* This case when there exist aggregate functions or a GROUP BY clause
   106302     ** or both */
   106303     NameContext sNC;    /* Name context for processing aggregate information */
   106304     int iAMem;          /* First Mem address for storing current GROUP BY */
   106305     int iBMem;          /* First Mem address for previous GROUP BY */
   106306     int iUseFlag;       /* Mem address holding flag indicating that at least
   106307                         ** one row of the input to the aggregator has been
   106308                         ** processed */
   106309     int iAbortFlag;     /* Mem address which causes query abort if positive */
   106310     int groupBySort;    /* Rows come from source in GROUP BY order */
   106311     int addrEnd;        /* End of processing for this SELECT */
   106312     int sortPTab = 0;   /* Pseudotable used to decode sorting results */
   106313     int sortOut = 0;    /* Output register from the sorter */
   106314     int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
   106315 
   106316     /* Remove any and all aliases between the result set and the
   106317     ** GROUP BY clause.
   106318     */
   106319     if( pGroupBy ){
   106320       int k;                        /* Loop counter */
   106321       struct ExprList_item *pItem;  /* For looping over expression in a list */
   106322 
   106323       for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
   106324         pItem->u.x.iAlias = 0;
   106325       }
   106326       for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
   106327         pItem->u.x.iAlias = 0;
   106328       }
   106329       if( p->nSelectRow>100 ) p->nSelectRow = 100;
   106330     }else{
   106331       p->nSelectRow = 1;
   106332     }
   106333 
   106334 
   106335     /* If there is both a GROUP BY and an ORDER BY clause and they are
   106336     ** identical, then it may be possible to disable the ORDER BY clause
   106337     ** on the grounds that the GROUP BY will cause elements to come out
   106338     ** in the correct order. It also may not - the GROUP BY may use a
   106339     ** database index that causes rows to be grouped together as required
   106340     ** but not actually sorted. Either way, record the fact that the
   106341     ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
   106342     ** variable.  */
   106343     if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
   106344       orderByGrp = 1;
   106345     }
   106346 
   106347     /* Create a label to jump to when we want to abort the query */
   106348     addrEnd = sqlite3VdbeMakeLabel(v);
   106349 
   106350     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
   106351     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
   106352     ** SELECT statement.
   106353     */
   106354     memset(&sNC, 0, sizeof(sNC));
   106355     sNC.pParse = pParse;
   106356     sNC.pSrcList = pTabList;
   106357     sNC.pAggInfo = &sAggInfo;
   106358     sAggInfo.mnReg = pParse->nMem+1;
   106359     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
   106360     sAggInfo.pGroupBy = pGroupBy;
   106361     sqlite3ExprAnalyzeAggList(&sNC, pEList);
   106362     sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
   106363     if( pHaving ){
   106364       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
   106365     }
   106366     sAggInfo.nAccumulator = sAggInfo.nColumn;
   106367     for(i=0; i<sAggInfo.nFunc; i++){
   106368       assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
   106369       sNC.ncFlags |= NC_InAggFunc;
   106370       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
   106371       sNC.ncFlags &= ~NC_InAggFunc;
   106372     }
   106373     sAggInfo.mxReg = pParse->nMem;
   106374     if( db->mallocFailed ) goto select_end;
   106375 
   106376     /* Processing for aggregates with GROUP BY is very different and
   106377     ** much more complex than aggregates without a GROUP BY.
   106378     */
   106379     if( pGroupBy ){
   106380       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
   106381       int j1;             /* A-vs-B comparision jump */
   106382       int addrOutputRow;  /* Start of subroutine that outputs a result row */
   106383       int regOutputRow;   /* Return address register for output subroutine */
   106384       int addrSetAbort;   /* Set the abort flag and return */
   106385       int addrTopOfLoop;  /* Top of the input loop */
   106386       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
   106387       int addrReset;      /* Subroutine for resetting the accumulator */
   106388       int regReset;       /* Return address register for reset subroutine */
   106389 
   106390       /* If there is a GROUP BY clause we might need a sorting index to
   106391       ** implement it.  Allocate that sorting index now.  If it turns out
   106392       ** that we do not need it after all, the OP_SorterOpen instruction
   106393       ** will be converted into a Noop.
   106394       */
   106395       sAggInfo.sortingIdx = pParse->nTab++;
   106396       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, 0);
   106397       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
   106398           sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
   106399           0, (char*)pKeyInfo, P4_KEYINFO);
   106400 
   106401       /* Initialize memory locations used by GROUP BY aggregate processing
   106402       */
   106403       iUseFlag = ++pParse->nMem;
   106404       iAbortFlag = ++pParse->nMem;
   106405       regOutputRow = ++pParse->nMem;
   106406       addrOutputRow = sqlite3VdbeMakeLabel(v);
   106407       regReset = ++pParse->nMem;
   106408       addrReset = sqlite3VdbeMakeLabel(v);
   106409       iAMem = pParse->nMem + 1;
   106410       pParse->nMem += pGroupBy->nExpr;
   106411       iBMem = pParse->nMem + 1;
   106412       pParse->nMem += pGroupBy->nExpr;
   106413       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
   106414       VdbeComment((v, "clear abort flag"));
   106415       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
   106416       VdbeComment((v, "indicate accumulator empty"));
   106417       sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
   106418 
   106419       /* Begin a loop that will extract all source rows in GROUP BY order.
   106420       ** This might involve two separate loops with an OP_Sort in between, or
   106421       ** it might be a single loop that uses an index to extract information
   106422       ** in the right order to begin with.
   106423       */
   106424       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
   106425       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
   106426           WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
   106427       );
   106428       if( pWInfo==0 ) goto select_end;
   106429       if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
   106430         /* The optimizer is able to deliver rows in group by order so
   106431         ** we do not have to sort.  The OP_OpenEphemeral table will be
   106432         ** cancelled later because we still need to use the pKeyInfo
   106433         */
   106434         groupBySort = 0;
   106435       }else{
   106436         /* Rows are coming out in undetermined order.  We have to push
   106437         ** each row into a sorting index, terminate the first loop,
   106438         ** then loop over the sorting index in order to get the output
   106439         ** in sorted order
   106440         */
   106441         int regBase;
   106442         int regRecord;
   106443         int nCol;
   106444         int nGroupBy;
   106445 
   106446         explainTempTable(pParse,
   106447             (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
   106448                     "DISTINCT" : "GROUP BY");
   106449 
   106450         groupBySort = 1;
   106451         nGroupBy = pGroupBy->nExpr;
   106452         nCol = nGroupBy + 1;
   106453         j = nGroupBy+1;
   106454         for(i=0; i<sAggInfo.nColumn; i++){
   106455           if( sAggInfo.aCol[i].iSorterColumn>=j ){
   106456             nCol++;
   106457             j++;
   106458           }
   106459         }
   106460         regBase = sqlite3GetTempRange(pParse, nCol);
   106461         sqlite3ExprCacheClear(pParse);
   106462         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
   106463         sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
   106464         j = nGroupBy+1;
   106465         for(i=0; i<sAggInfo.nColumn; i++){
   106466           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
   106467           if( pCol->iSorterColumn>=j ){
   106468             int r1 = j + regBase;
   106469             int r2;
   106470 
   106471             r2 = sqlite3ExprCodeGetColumn(pParse,
   106472                                pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
   106473             if( r1!=r2 ){
   106474               sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
   106475             }
   106476             j++;
   106477           }
   106478         }
   106479         regRecord = sqlite3GetTempReg(pParse);
   106480         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
   106481         sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
   106482         sqlite3ReleaseTempReg(pParse, regRecord);
   106483         sqlite3ReleaseTempRange(pParse, regBase, nCol);
   106484         sqlite3WhereEnd(pWInfo);
   106485         sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
   106486         sortOut = sqlite3GetTempReg(pParse);
   106487         sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
   106488         sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
   106489         VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
   106490         sAggInfo.useSortingIdx = 1;
   106491         sqlite3ExprCacheClear(pParse);
   106492 
   106493       }
   106494 
   106495       /* If the index or temporary table used by the GROUP BY sort
   106496       ** will naturally deliver rows in the order required by the ORDER BY
   106497       ** clause, cancel the ephemeral table open coded earlier.
   106498       **
   106499       ** This is an optimization - the correct answer should result regardless.
   106500       ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
   106501       ** disable this optimization for testing purposes.  */
   106502       if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
   106503        && (groupBySort || sqlite3WhereIsSorted(pWInfo))
   106504       ){
   106505         sSort.pOrderBy = 0;
   106506         sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
   106507       }
   106508 
   106509       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
   106510       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
   106511       ** Then compare the current GROUP BY terms against the GROUP BY terms
   106512       ** from the previous row currently stored in a0, a1, a2...
   106513       */
   106514       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
   106515       sqlite3ExprCacheClear(pParse);
   106516       if( groupBySort ){
   106517         sqlite3VdbeAddOp2(v, OP_SorterData, sAggInfo.sortingIdx, sortOut);
   106518       }
   106519       for(j=0; j<pGroupBy->nExpr; j++){
   106520         if( groupBySort ){
   106521           sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
   106522           if( j==0 ) sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
   106523         }else{
   106524           sAggInfo.directMode = 1;
   106525           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
   106526         }
   106527       }
   106528       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
   106529                           (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
   106530       j1 = sqlite3VdbeCurrentAddr(v);
   106531       sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1); VdbeCoverage(v);
   106532 
   106533       /* Generate code that runs whenever the GROUP BY changes.
   106534       ** Changes in the GROUP BY are detected by the previous code
   106535       ** block.  If there were no changes, this block is skipped.
   106536       **
   106537       ** This code copies current group by terms in b0,b1,b2,...
   106538       ** over to a0,a1,a2.  It then calls the output subroutine
   106539       ** and resets the aggregate accumulator registers in preparation
   106540       ** for the next GROUP BY batch.
   106541       */
   106542       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
   106543       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
   106544       VdbeComment((v, "output one row"));
   106545       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
   106546       VdbeComment((v, "check abort flag"));
   106547       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
   106548       VdbeComment((v, "reset accumulator"));
   106549 
   106550       /* Update the aggregate accumulators based on the content of
   106551       ** the current row
   106552       */
   106553       sqlite3VdbeJumpHere(v, j1);
   106554       updateAccumulator(pParse, &sAggInfo);
   106555       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
   106556       VdbeComment((v, "indicate data in accumulator"));
   106557 
   106558       /* End of the loop
   106559       */
   106560       if( groupBySort ){
   106561         sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
   106562         VdbeCoverage(v);
   106563       }else{
   106564         sqlite3WhereEnd(pWInfo);
   106565         sqlite3VdbeChangeToNoop(v, addrSortingIdx);
   106566       }
   106567 
   106568       /* Output the final row of result
   106569       */
   106570       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
   106571       VdbeComment((v, "output final row"));
   106572 
   106573       /* Jump over the subroutines
   106574       */
   106575       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
   106576 
   106577       /* Generate a subroutine that outputs a single row of the result
   106578       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
   106579       ** is less than or equal to zero, the subroutine is a no-op.  If
   106580       ** the processing calls for the query to abort, this subroutine
   106581       ** increments the iAbortFlag memory location before returning in
   106582       ** order to signal the caller to abort.
   106583       */
   106584       addrSetAbort = sqlite3VdbeCurrentAddr(v);
   106585       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
   106586       VdbeComment((v, "set abort flag"));
   106587       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
   106588       sqlite3VdbeResolveLabel(v, addrOutputRow);
   106589       addrOutputRow = sqlite3VdbeCurrentAddr(v);
   106590       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2); VdbeCoverage(v);
   106591       VdbeComment((v, "Groupby result generator entry point"));
   106592       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
   106593       finalizeAggFunctions(pParse, &sAggInfo);
   106594       sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
   106595       selectInnerLoop(pParse, p, p->pEList, -1, &sSort,
   106596                       &sDistinct, pDest,
   106597                       addrOutputRow+1, addrSetAbort);
   106598       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
   106599       VdbeComment((v, "end groupby result generator"));
   106600 
   106601       /* Generate a subroutine that will reset the group-by accumulator
   106602       */
   106603       sqlite3VdbeResolveLabel(v, addrReset);
   106604       resetAccumulator(pParse, &sAggInfo);
   106605       sqlite3VdbeAddOp1(v, OP_Return, regReset);
   106606 
   106607     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
   106608     else {
   106609       ExprList *pDel = 0;
   106610 #ifndef SQLITE_OMIT_BTREECOUNT
   106611       Table *pTab;
   106612       if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
   106613         /* If isSimpleCount() returns a pointer to a Table structure, then
   106614         ** the SQL statement is of the form:
   106615         **
   106616         **   SELECT count(*) FROM <tbl>
   106617         **
   106618         ** where the Table structure returned represents table <tbl>.
   106619         **
   106620         ** This statement is so common that it is optimized specially. The
   106621         ** OP_Count instruction is executed either on the intkey table that
   106622         ** contains the data for table <tbl> or on one of its indexes. It
   106623         ** is better to execute the op on an index, as indexes are almost
   106624         ** always spread across less pages than their corresponding tables.
   106625         */
   106626         const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   106627         const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
   106628         Index *pIdx;                         /* Iterator variable */
   106629         KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
   106630         Index *pBest = 0;                    /* Best index found so far */
   106631         int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
   106632 
   106633         sqlite3CodeVerifySchema(pParse, iDb);
   106634         sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
   106635 
   106636         /* Search for the index that has the lowest scan cost.
   106637         **
   106638         ** (2011-04-15) Do not do a full scan of an unordered index.
   106639         **
   106640         ** (2013-10-03) Do not count the entries in a partial index.
   106641         **
   106642         ** In practice the KeyInfo structure will not be used. It is only
   106643         ** passed to keep OP_OpenRead happy.
   106644         */
   106645         if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
   106646         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   106647           if( pIdx->bUnordered==0
   106648            && pIdx->szIdxRow<pTab->szTabRow
   106649            && pIdx->pPartIdxWhere==0
   106650            && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
   106651           ){
   106652             pBest = pIdx;
   106653           }
   106654         }
   106655         if( pBest ){
   106656           iRoot = pBest->tnum;
   106657           pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
   106658         }
   106659 
   106660         /* Open a read-only cursor, execute the OP_Count, close the cursor. */
   106661         sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
   106662         if( pKeyInfo ){
   106663           sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
   106664         }
   106665         sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
   106666         sqlite3VdbeAddOp1(v, OP_Close, iCsr);
   106667         explainSimpleCount(pParse, pTab, pBest);
   106668       }else
   106669 #endif /* SQLITE_OMIT_BTREECOUNT */
   106670       {
   106671         /* Check if the query is of one of the following forms:
   106672         **
   106673         **   SELECT min(x) FROM ...
   106674         **   SELECT max(x) FROM ...
   106675         **
   106676         ** If it is, then ask the code in where.c to attempt to sort results
   106677         ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
   106678         ** If where.c is able to produce results sorted in this order, then
   106679         ** add vdbe code to break out of the processing loop after the
   106680         ** first iteration (since the first iteration of the loop is
   106681         ** guaranteed to operate on the row with the minimum or maximum
   106682         ** value of x, the only row required).
   106683         **
   106684         ** A special flag must be passed to sqlite3WhereBegin() to slightly
   106685         ** modify behavior as follows:
   106686         **
   106687         **   + If the query is a "SELECT min(x)", then the loop coded by
   106688         **     where.c should not iterate over any values with a NULL value
   106689         **     for x.
   106690         **
   106691         **   + The optimizer code in where.c (the thing that decides which
   106692         **     index or indices to use) should place a different priority on
   106693         **     satisfying the 'ORDER BY' clause than it does in other cases.
   106694         **     Refer to code and comments in where.c for details.
   106695         */
   106696         ExprList *pMinMax = 0;
   106697         u8 flag = WHERE_ORDERBY_NORMAL;
   106698 
   106699         assert( p->pGroupBy==0 );
   106700         assert( flag==0 );
   106701         if( p->pHaving==0 ){
   106702           flag = minMaxQuery(&sAggInfo, &pMinMax);
   106703         }
   106704         assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
   106705 
   106706         if( flag ){
   106707           pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
   106708           pDel = pMinMax;
   106709           if( pMinMax && !db->mallocFailed ){
   106710             pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
   106711             pMinMax->a[0].pExpr->op = TK_COLUMN;
   106712           }
   106713         }
   106714 
   106715         /* This case runs if the aggregate has no GROUP BY clause.  The
   106716         ** processing is much simpler since there is only a single row
   106717         ** of output.
   106718         */
   106719         resetAccumulator(pParse, &sAggInfo);
   106720         pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
   106721         if( pWInfo==0 ){
   106722           sqlite3ExprListDelete(db, pDel);
   106723           goto select_end;
   106724         }
   106725         updateAccumulator(pParse, &sAggInfo);
   106726         assert( pMinMax==0 || pMinMax->nExpr==1 );
   106727         if( sqlite3WhereIsOrdered(pWInfo)>0 ){
   106728           sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3WhereBreakLabel(pWInfo));
   106729           VdbeComment((v, "%s() by index",
   106730                 (flag==WHERE_ORDERBY_MIN?"min":"max")));
   106731         }
   106732         sqlite3WhereEnd(pWInfo);
   106733         finalizeAggFunctions(pParse, &sAggInfo);
   106734       }
   106735 
   106736       sSort.pOrderBy = 0;
   106737       sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
   106738       selectInnerLoop(pParse, p, p->pEList, -1, 0, 0,
   106739                       pDest, addrEnd, addrEnd);
   106740       sqlite3ExprListDelete(db, pDel);
   106741     }
   106742     sqlite3VdbeResolveLabel(v, addrEnd);
   106743 
   106744   } /* endif aggregate query */
   106745 
   106746   if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
   106747     explainTempTable(pParse, "DISTINCT");
   106748   }
   106749 
   106750   /* If there is an ORDER BY clause, then we need to sort the results
   106751   ** and send them to the callback one by one.
   106752   */
   106753   if( sSort.pOrderBy ){
   106754     explainTempTable(pParse, sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
   106755     generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
   106756   }
   106757 
   106758   /* Jump here to skip this query
   106759   */
   106760   sqlite3VdbeResolveLabel(v, iEnd);
   106761 
   106762   /* The SELECT was successfully coded.   Set the return code to 0
   106763   ** to indicate no errors.
   106764   */
   106765   rc = 0;
   106766 
   106767   /* Control jumps to here if an error is encountered above, or upon
   106768   ** successful coding of the SELECT.
   106769   */
   106770 select_end:
   106771   explainSetInteger(pParse->iSelectId, iRestoreSelectId);
   106772 
   106773   /* Identify column names if results of the SELECT are to be output.
   106774   */
   106775   if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
   106776     generateColumnNames(pParse, pTabList, pEList);
   106777   }
   106778 
   106779   sqlite3DbFree(db, sAggInfo.aCol);
   106780   sqlite3DbFree(db, sAggInfo.aFunc);
   106781   return rc;
   106782 }
   106783 
   106784 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
   106785 /*
   106786 ** Generate a human-readable description of a the Select object.
   106787 */
   106788 static void explainOneSelect(Vdbe *pVdbe, Select *p){
   106789   sqlite3ExplainPrintf(pVdbe, "SELECT ");
   106790   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
   106791     if( p->selFlags & SF_Distinct ){
   106792       sqlite3ExplainPrintf(pVdbe, "DISTINCT ");
   106793     }
   106794     if( p->selFlags & SF_Aggregate ){
   106795       sqlite3ExplainPrintf(pVdbe, "agg_flag ");
   106796     }
   106797     sqlite3ExplainNL(pVdbe);
   106798     sqlite3ExplainPrintf(pVdbe, "   ");
   106799   }
   106800   sqlite3ExplainExprList(pVdbe, p->pEList);
   106801   sqlite3ExplainNL(pVdbe);
   106802   if( p->pSrc && p->pSrc->nSrc ){
   106803     int i;
   106804     sqlite3ExplainPrintf(pVdbe, "FROM ");
   106805     sqlite3ExplainPush(pVdbe);
   106806     for(i=0; i<p->pSrc->nSrc; i++){
   106807       struct SrcList_item *pItem = &p->pSrc->a[i];
   106808       sqlite3ExplainPrintf(pVdbe, "{%d,*} = ", pItem->iCursor);
   106809       if( pItem->pSelect ){
   106810         sqlite3ExplainSelect(pVdbe, pItem->pSelect);
   106811         if( pItem->pTab ){
   106812           sqlite3ExplainPrintf(pVdbe, " (tabname=%s)", pItem->pTab->zName);
   106813         }
   106814       }else if( pItem->zName ){
   106815         sqlite3ExplainPrintf(pVdbe, "%s", pItem->zName);
   106816       }
   106817       if( pItem->zAlias ){
   106818         sqlite3ExplainPrintf(pVdbe, " (AS %s)", pItem->zAlias);
   106819       }
   106820       if( pItem->jointype & JT_LEFT ){
   106821         sqlite3ExplainPrintf(pVdbe, " LEFT-JOIN");
   106822       }
   106823       sqlite3ExplainNL(pVdbe);
   106824     }
   106825     sqlite3ExplainPop(pVdbe);
   106826   }
   106827   if( p->pWhere ){
   106828     sqlite3ExplainPrintf(pVdbe, "WHERE ");
   106829     sqlite3ExplainExpr(pVdbe, p->pWhere);
   106830     sqlite3ExplainNL(pVdbe);
   106831   }
   106832   if( p->pGroupBy ){
   106833     sqlite3ExplainPrintf(pVdbe, "GROUPBY ");
   106834     sqlite3ExplainExprList(pVdbe, p->pGroupBy);
   106835     sqlite3ExplainNL(pVdbe);
   106836   }
   106837   if( p->pHaving ){
   106838     sqlite3ExplainPrintf(pVdbe, "HAVING ");
   106839     sqlite3ExplainExpr(pVdbe, p->pHaving);
   106840     sqlite3ExplainNL(pVdbe);
   106841   }
   106842   if( p->pOrderBy ){
   106843     sqlite3ExplainPrintf(pVdbe, "ORDERBY ");
   106844     sqlite3ExplainExprList(pVdbe, p->pOrderBy);
   106845     sqlite3ExplainNL(pVdbe);
   106846   }
   106847   if( p->pLimit ){
   106848     sqlite3ExplainPrintf(pVdbe, "LIMIT ");
   106849     sqlite3ExplainExpr(pVdbe, p->pLimit);
   106850     sqlite3ExplainNL(pVdbe);
   106851   }
   106852   if( p->pOffset ){
   106853     sqlite3ExplainPrintf(pVdbe, "OFFSET ");
   106854     sqlite3ExplainExpr(pVdbe, p->pOffset);
   106855     sqlite3ExplainNL(pVdbe);
   106856   }
   106857 }
   106858 SQLITE_PRIVATE void sqlite3ExplainSelect(Vdbe *pVdbe, Select *p){
   106859   if( p==0 ){
   106860     sqlite3ExplainPrintf(pVdbe, "(null-select)");
   106861     return;
   106862   }
   106863   sqlite3ExplainPush(pVdbe);
   106864   while( p ){
   106865     explainOneSelect(pVdbe, p);
   106866     p = p->pNext;
   106867     if( p==0 ) break;
   106868     sqlite3ExplainNL(pVdbe);
   106869     sqlite3ExplainPrintf(pVdbe, "%s\n", selectOpName(p->op));
   106870   }
   106871   sqlite3ExplainPrintf(pVdbe, "END");
   106872   sqlite3ExplainPop(pVdbe);
   106873 }
   106874 
   106875 /* End of the structure debug printing code
   106876 *****************************************************************************/
   106877 #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
   106878 
   106879 /************** End of select.c **********************************************/
   106880 /************** Begin file table.c *******************************************/
   106881 /*
   106882 ** 2001 September 15
   106883 **
   106884 ** The author disclaims copyright to this source code.  In place of
   106885 ** a legal notice, here is a blessing:
   106886 **
   106887 **    May you do good and not evil.
   106888 **    May you find forgiveness for yourself and forgive others.
   106889 **    May you share freely, never taking more than you give.
   106890 **
   106891 *************************************************************************
   106892 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
   106893 ** interface routines.  These are just wrappers around the main
   106894 ** interface routine of sqlite3_exec().
   106895 **
   106896 ** These routines are in a separate files so that they will not be linked
   106897 ** if they are not used.
   106898 */
   106899 /* #include <stdlib.h> */
   106900 /* #include <string.h> */
   106901 
   106902 #ifndef SQLITE_OMIT_GET_TABLE
   106903 
   106904 /*
   106905 ** This structure is used to pass data from sqlite3_get_table() through
   106906 ** to the callback function is uses to build the result.
   106907 */
   106908 typedef struct TabResult {
   106909   char **azResult;   /* Accumulated output */
   106910   char *zErrMsg;     /* Error message text, if an error occurs */
   106911   int nAlloc;        /* Slots allocated for azResult[] */
   106912   int nRow;          /* Number of rows in the result */
   106913   int nColumn;       /* Number of columns in the result */
   106914   int nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
   106915   int rc;            /* Return code from sqlite3_exec() */
   106916 } TabResult;
   106917 
   106918 /*
   106919 ** This routine is called once for each row in the result table.  Its job
   106920 ** is to fill in the TabResult structure appropriately, allocating new
   106921 ** memory as necessary.
   106922 */
   106923 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
   106924   TabResult *p = (TabResult*)pArg;  /* Result accumulator */
   106925   int need;                         /* Slots needed in p->azResult[] */
   106926   int i;                            /* Loop counter */
   106927   char *z;                          /* A single column of result */
   106928 
   106929   /* Make sure there is enough space in p->azResult to hold everything
   106930   ** we need to remember from this invocation of the callback.
   106931   */
   106932   if( p->nRow==0 && argv!=0 ){
   106933     need = nCol*2;
   106934   }else{
   106935     need = nCol;
   106936   }
   106937   if( p->nData + need > p->nAlloc ){
   106938     char **azNew;
   106939     p->nAlloc = p->nAlloc*2 + need;
   106940     azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
   106941     if( azNew==0 ) goto malloc_failed;
   106942     p->azResult = azNew;
   106943   }
   106944 
   106945   /* If this is the first row, then generate an extra row containing
   106946   ** the names of all columns.
   106947   */
   106948   if( p->nRow==0 ){
   106949     p->nColumn = nCol;
   106950     for(i=0; i<nCol; i++){
   106951       z = sqlite3_mprintf("%s", colv[i]);
   106952       if( z==0 ) goto malloc_failed;
   106953       p->azResult[p->nData++] = z;
   106954     }
   106955   }else if( p->nColumn!=nCol ){
   106956     sqlite3_free(p->zErrMsg);
   106957     p->zErrMsg = sqlite3_mprintf(
   106958        "sqlite3_get_table() called with two or more incompatible queries"
   106959     );
   106960     p->rc = SQLITE_ERROR;
   106961     return 1;
   106962   }
   106963 
   106964   /* Copy over the row data
   106965   */
   106966   if( argv!=0 ){
   106967     for(i=0; i<nCol; i++){
   106968       if( argv[i]==0 ){
   106969         z = 0;
   106970       }else{
   106971         int n = sqlite3Strlen30(argv[i])+1;
   106972         z = sqlite3_malloc( n );
   106973         if( z==0 ) goto malloc_failed;
   106974         memcpy(z, argv[i], n);
   106975       }
   106976       p->azResult[p->nData++] = z;
   106977     }
   106978     p->nRow++;
   106979   }
   106980   return 0;
   106981 
   106982 malloc_failed:
   106983   p->rc = SQLITE_NOMEM;
   106984   return 1;
   106985 }
   106986 
   106987 /*
   106988 ** Query the database.  But instead of invoking a callback for each row,
   106989 ** malloc() for space to hold the result and return the entire results
   106990 ** at the conclusion of the call.
   106991 **
   106992 ** The result that is written to ***pazResult is held in memory obtained
   106993 ** from malloc().  But the caller cannot free this memory directly.
   106994 ** Instead, the entire table should be passed to sqlite3_free_table() when
   106995 ** the calling procedure is finished using it.
   106996 */
   106997 SQLITE_API int sqlite3_get_table(
   106998   sqlite3 *db,                /* The database on which the SQL executes */
   106999   const char *zSql,           /* The SQL to be executed */
   107000   char ***pazResult,          /* Write the result table here */
   107001   int *pnRow,                 /* Write the number of rows in the result here */
   107002   int *pnColumn,              /* Write the number of columns of result here */
   107003   char **pzErrMsg             /* Write error messages here */
   107004 ){
   107005   int rc;
   107006   TabResult res;
   107007 
   107008   *pazResult = 0;
   107009   if( pnColumn ) *pnColumn = 0;
   107010   if( pnRow ) *pnRow = 0;
   107011   if( pzErrMsg ) *pzErrMsg = 0;
   107012   res.zErrMsg = 0;
   107013   res.nRow = 0;
   107014   res.nColumn = 0;
   107015   res.nData = 1;
   107016   res.nAlloc = 20;
   107017   res.rc = SQLITE_OK;
   107018   res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
   107019   if( res.azResult==0 ){
   107020      db->errCode = SQLITE_NOMEM;
   107021      return SQLITE_NOMEM;
   107022   }
   107023   res.azResult[0] = 0;
   107024   rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
   107025   assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
   107026   res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
   107027   if( (rc&0xff)==SQLITE_ABORT ){
   107028     sqlite3_free_table(&res.azResult[1]);
   107029     if( res.zErrMsg ){
   107030       if( pzErrMsg ){
   107031         sqlite3_free(*pzErrMsg);
   107032         *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
   107033       }
   107034       sqlite3_free(res.zErrMsg);
   107035     }
   107036     db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
   107037     return res.rc;
   107038   }
   107039   sqlite3_free(res.zErrMsg);
   107040   if( rc!=SQLITE_OK ){
   107041     sqlite3_free_table(&res.azResult[1]);
   107042     return rc;
   107043   }
   107044   if( res.nAlloc>res.nData ){
   107045     char **azNew;
   107046     azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
   107047     if( azNew==0 ){
   107048       sqlite3_free_table(&res.azResult[1]);
   107049       db->errCode = SQLITE_NOMEM;
   107050       return SQLITE_NOMEM;
   107051     }
   107052     res.azResult = azNew;
   107053   }
   107054   *pazResult = &res.azResult[1];
   107055   if( pnColumn ) *pnColumn = res.nColumn;
   107056   if( pnRow ) *pnRow = res.nRow;
   107057   return rc;
   107058 }
   107059 
   107060 /*
   107061 ** This routine frees the space the sqlite3_get_table() malloced.
   107062 */
   107063 SQLITE_API void sqlite3_free_table(
   107064   char **azResult            /* Result returned from from sqlite3_get_table() */
   107065 ){
   107066   if( azResult ){
   107067     int i, n;
   107068     azResult--;
   107069     assert( azResult!=0 );
   107070     n = SQLITE_PTR_TO_INT(azResult[0]);
   107071     for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
   107072     sqlite3_free(azResult);
   107073   }
   107074 }
   107075 
   107076 #endif /* SQLITE_OMIT_GET_TABLE */
   107077 
   107078 /************** End of table.c ***********************************************/
   107079 /************** Begin file trigger.c *****************************************/
   107080 /*
   107081 **
   107082 ** The author disclaims copyright to this source code.  In place of
   107083 ** a legal notice, here is a blessing:
   107084 **
   107085 **    May you do good and not evil.
   107086 **    May you find forgiveness for yourself and forgive others.
   107087 **    May you share freely, never taking more than you give.
   107088 **
   107089 *************************************************************************
   107090 ** This file contains the implementation for TRIGGERs
   107091 */
   107092 
   107093 #ifndef SQLITE_OMIT_TRIGGER
   107094 /*
   107095 ** Delete a linked list of TriggerStep structures.
   107096 */
   107097 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
   107098   while( pTriggerStep ){
   107099     TriggerStep * pTmp = pTriggerStep;
   107100     pTriggerStep = pTriggerStep->pNext;
   107101 
   107102     sqlite3ExprDelete(db, pTmp->pWhere);
   107103     sqlite3ExprListDelete(db, pTmp->pExprList);
   107104     sqlite3SelectDelete(db, pTmp->pSelect);
   107105     sqlite3IdListDelete(db, pTmp->pIdList);
   107106 
   107107     sqlite3DbFree(db, pTmp);
   107108   }
   107109 }
   107110 
   107111 /*
   107112 ** Given table pTab, return a list of all the triggers attached to
   107113 ** the table. The list is connected by Trigger.pNext pointers.
   107114 **
   107115 ** All of the triggers on pTab that are in the same database as pTab
   107116 ** are already attached to pTab->pTrigger.  But there might be additional
   107117 ** triggers on pTab in the TEMP schema.  This routine prepends all
   107118 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
   107119 ** and returns the combined list.
   107120 **
   107121 ** To state it another way:  This routine returns a list of all triggers
   107122 ** that fire off of pTab.  The list will include any TEMP triggers on
   107123 ** pTab as well as the triggers lised in pTab->pTrigger.
   107124 */
   107125 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
   107126   Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
   107127   Trigger *pList = 0;                  /* List of triggers to return */
   107128 
   107129   if( pParse->disableTriggers ){
   107130     return 0;
   107131   }
   107132 
   107133   if( pTmpSchema!=pTab->pSchema ){
   107134     HashElem *p;
   107135     assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
   107136     for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
   107137       Trigger *pTrig = (Trigger *)sqliteHashData(p);
   107138       if( pTrig->pTabSchema==pTab->pSchema
   107139        && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
   107140       ){
   107141         pTrig->pNext = (pList ? pList : pTab->pTrigger);
   107142         pList = pTrig;
   107143       }
   107144     }
   107145   }
   107146 
   107147   return (pList ? pList : pTab->pTrigger);
   107148 }
   107149 
   107150 /*
   107151 ** This is called by the parser when it sees a CREATE TRIGGER statement
   107152 ** up to the point of the BEGIN before the trigger actions.  A Trigger
   107153 ** structure is generated based on the information available and stored
   107154 ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
   107155 ** sqlite3FinishTrigger() function is called to complete the trigger
   107156 ** construction process.
   107157 */
   107158 SQLITE_PRIVATE void sqlite3BeginTrigger(
   107159   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
   107160   Token *pName1,      /* The name of the trigger */
   107161   Token *pName2,      /* The name of the trigger */
   107162   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
   107163   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
   107164   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
   107165   SrcList *pTableName,/* The name of the table/view the trigger applies to */
   107166   Expr *pWhen,        /* WHEN clause */
   107167   int isTemp,         /* True if the TEMPORARY keyword is present */
   107168   int noErr           /* Suppress errors if the trigger already exists */
   107169 ){
   107170   Trigger *pTrigger = 0;  /* The new trigger */
   107171   Table *pTab;            /* Table that the trigger fires off of */
   107172   char *zName = 0;        /* Name of the trigger */
   107173   sqlite3 *db = pParse->db;  /* The database connection */
   107174   int iDb;                /* The database to store the trigger in */
   107175   Token *pName;           /* The unqualified db name */
   107176   DbFixer sFix;           /* State vector for the DB fixer */
   107177   int iTabDb;             /* Index of the database holding pTab */
   107178 
   107179   assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
   107180   assert( pName2!=0 );
   107181   assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
   107182   assert( op>0 && op<0xff );
   107183   if( isTemp ){
   107184     /* If TEMP was specified, then the trigger name may not be qualified. */
   107185     if( pName2->n>0 ){
   107186       sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
   107187       goto trigger_cleanup;
   107188     }
   107189     iDb = 1;
   107190     pName = pName1;
   107191   }else{
   107192     /* Figure out the db that the trigger will be created in */
   107193     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
   107194     if( iDb<0 ){
   107195       goto trigger_cleanup;
   107196     }
   107197   }
   107198   if( !pTableName || db->mallocFailed ){
   107199     goto trigger_cleanup;
   107200   }
   107201 
   107202   /* A long-standing parser bug is that this syntax was allowed:
   107203   **
   107204   **    CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
   107205   **                                                 ^^^^^^^^
   107206   **
   107207   ** To maintain backwards compatibility, ignore the database
   107208   ** name on pTableName if we are reparsing our of SQLITE_MASTER.
   107209   */
   107210   if( db->init.busy && iDb!=1 ){
   107211     sqlite3DbFree(db, pTableName->a[0].zDatabase);
   107212     pTableName->a[0].zDatabase = 0;
   107213   }
   107214 
   107215   /* If the trigger name was unqualified, and the table is a temp table,
   107216   ** then set iDb to 1 to create the trigger in the temporary database.
   107217   ** If sqlite3SrcListLookup() returns 0, indicating the table does not
   107218   ** exist, the error is caught by the block below.
   107219   */
   107220   pTab = sqlite3SrcListLookup(pParse, pTableName);
   107221   if( db->init.busy==0 && pName2->n==0 && pTab
   107222         && pTab->pSchema==db->aDb[1].pSchema ){
   107223     iDb = 1;
   107224   }
   107225 
   107226   /* Ensure the table name matches database name and that the table exists */
   107227   if( db->mallocFailed ) goto trigger_cleanup;
   107228   assert( pTableName->nSrc==1 );
   107229   sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
   107230   if( sqlite3FixSrcList(&sFix, pTableName) ){
   107231     goto trigger_cleanup;
   107232   }
   107233   pTab = sqlite3SrcListLookup(pParse, pTableName);
   107234   if( !pTab ){
   107235     /* The table does not exist. */
   107236     if( db->init.iDb==1 ){
   107237       /* Ticket #3810.
   107238       ** Normally, whenever a table is dropped, all associated triggers are
   107239       ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
   107240       ** and the table is dropped by a different database connection, the
   107241       ** trigger is not visible to the database connection that does the
   107242       ** drop so the trigger cannot be dropped.  This results in an
   107243       ** "orphaned trigger" - a trigger whose associated table is missing.
   107244       */
   107245       db->init.orphanTrigger = 1;
   107246     }
   107247     goto trigger_cleanup;
   107248   }
   107249   if( IsVirtual(pTab) ){
   107250     sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
   107251     goto trigger_cleanup;
   107252   }
   107253 
   107254   /* Check that the trigger name is not reserved and that no trigger of the
   107255   ** specified name exists */
   107256   zName = sqlite3NameFromToken(db, pName);
   107257   if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
   107258     goto trigger_cleanup;
   107259   }
   107260   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   107261   if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
   107262                       zName, sqlite3Strlen30(zName)) ){
   107263     if( !noErr ){
   107264       sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
   107265     }else{
   107266       assert( !db->init.busy );
   107267       sqlite3CodeVerifySchema(pParse, iDb);
   107268     }
   107269     goto trigger_cleanup;
   107270   }
   107271 
   107272   /* Do not create a trigger on a system table */
   107273   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
   107274     sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
   107275     pParse->nErr++;
   107276     goto trigger_cleanup;
   107277   }
   107278 
   107279   /* INSTEAD of triggers are only for views and views only support INSTEAD
   107280   ** of triggers.
   107281   */
   107282   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
   107283     sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
   107284         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
   107285     goto trigger_cleanup;
   107286   }
   107287   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
   107288     sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
   107289         " trigger on table: %S", pTableName, 0);
   107290     goto trigger_cleanup;
   107291   }
   107292   iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   107293 
   107294 #ifndef SQLITE_OMIT_AUTHORIZATION
   107295   {
   107296     int code = SQLITE_CREATE_TRIGGER;
   107297     const char *zDb = db->aDb[iTabDb].zName;
   107298     const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
   107299     if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
   107300     if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
   107301       goto trigger_cleanup;
   107302     }
   107303     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
   107304       goto trigger_cleanup;
   107305     }
   107306   }
   107307 #endif
   107308 
   107309   /* INSTEAD OF triggers can only appear on views and BEFORE triggers
   107310   ** cannot appear on views.  So we might as well translate every
   107311   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
   107312   ** elsewhere.
   107313   */
   107314   if (tr_tm == TK_INSTEAD){
   107315     tr_tm = TK_BEFORE;
   107316   }
   107317 
   107318   /* Build the Trigger object */
   107319   pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
   107320   if( pTrigger==0 ) goto trigger_cleanup;
   107321   pTrigger->zName = zName;
   107322   zName = 0;
   107323   pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
   107324   pTrigger->pSchema = db->aDb[iDb].pSchema;
   107325   pTrigger->pTabSchema = pTab->pSchema;
   107326   pTrigger->op = (u8)op;
   107327   pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
   107328   pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
   107329   pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
   107330   assert( pParse->pNewTrigger==0 );
   107331   pParse->pNewTrigger = pTrigger;
   107332 
   107333 trigger_cleanup:
   107334   sqlite3DbFree(db, zName);
   107335   sqlite3SrcListDelete(db, pTableName);
   107336   sqlite3IdListDelete(db, pColumns);
   107337   sqlite3ExprDelete(db, pWhen);
   107338   if( !pParse->pNewTrigger ){
   107339     sqlite3DeleteTrigger(db, pTrigger);
   107340   }else{
   107341     assert( pParse->pNewTrigger==pTrigger );
   107342   }
   107343 }
   107344 
   107345 /*
   107346 ** This routine is called after all of the trigger actions have been parsed
   107347 ** in order to complete the process of building the trigger.
   107348 */
   107349 SQLITE_PRIVATE void sqlite3FinishTrigger(
   107350   Parse *pParse,          /* Parser context */
   107351   TriggerStep *pStepList, /* The triggered program */
   107352   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
   107353 ){
   107354   Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
   107355   char *zName;                            /* Name of trigger */
   107356   sqlite3 *db = pParse->db;               /* The database */
   107357   DbFixer sFix;                           /* Fixer object */
   107358   int iDb;                                /* Database containing the trigger */
   107359   Token nameToken;                        /* Trigger name for error reporting */
   107360 
   107361   pParse->pNewTrigger = 0;
   107362   if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
   107363   zName = pTrig->zName;
   107364   iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
   107365   pTrig->step_list = pStepList;
   107366   while( pStepList ){
   107367     pStepList->pTrig = pTrig;
   107368     pStepList = pStepList->pNext;
   107369   }
   107370   nameToken.z = pTrig->zName;
   107371   nameToken.n = sqlite3Strlen30(nameToken.z);
   107372   sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
   107373   if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
   107374    || sqlite3FixExpr(&sFix, pTrig->pWhen)
   107375   ){
   107376     goto triggerfinish_cleanup;
   107377   }
   107378 
   107379   /* if we are not initializing,
   107380   ** build the sqlite_master entry
   107381   */
   107382   if( !db->init.busy ){
   107383     Vdbe *v;
   107384     char *z;
   107385 
   107386     /* Make an entry in the sqlite_master table */
   107387     v = sqlite3GetVdbe(pParse);
   107388     if( v==0 ) goto triggerfinish_cleanup;
   107389     sqlite3BeginWriteOperation(pParse, 0, iDb);
   107390     z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
   107391     sqlite3NestedParse(pParse,
   107392        "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
   107393        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
   107394        pTrig->table, z);
   107395     sqlite3DbFree(db, z);
   107396     sqlite3ChangeCookie(pParse, iDb);
   107397     sqlite3VdbeAddParseSchemaOp(v, iDb,
   107398         sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
   107399   }
   107400 
   107401   if( db->init.busy ){
   107402     Trigger *pLink = pTrig;
   107403     Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
   107404     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   107405     pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
   107406     if( pTrig ){
   107407       db->mallocFailed = 1;
   107408     }else if( pLink->pSchema==pLink->pTabSchema ){
   107409       Table *pTab;
   107410       int n = sqlite3Strlen30(pLink->table);
   107411       pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
   107412       assert( pTab!=0 );
   107413       pLink->pNext = pTab->pTrigger;
   107414       pTab->pTrigger = pLink;
   107415     }
   107416   }
   107417 
   107418 triggerfinish_cleanup:
   107419   sqlite3DeleteTrigger(db, pTrig);
   107420   assert( !pParse->pNewTrigger );
   107421   sqlite3DeleteTriggerStep(db, pStepList);
   107422 }
   107423 
   107424 /*
   107425 ** Turn a SELECT statement (that the pSelect parameter points to) into
   107426 ** a trigger step.  Return a pointer to a TriggerStep structure.
   107427 **
   107428 ** The parser calls this routine when it finds a SELECT statement in
   107429 ** body of a TRIGGER.
   107430 */
   107431 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
   107432   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
   107433   if( pTriggerStep==0 ) {
   107434     sqlite3SelectDelete(db, pSelect);
   107435     return 0;
   107436   }
   107437   pTriggerStep->op = TK_SELECT;
   107438   pTriggerStep->pSelect = pSelect;
   107439   pTriggerStep->orconf = OE_Default;
   107440   return pTriggerStep;
   107441 }
   107442 
   107443 /*
   107444 ** Allocate space to hold a new trigger step.  The allocated space
   107445 ** holds both the TriggerStep object and the TriggerStep.target.z string.
   107446 **
   107447 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
   107448 */
   107449 static TriggerStep *triggerStepAllocate(
   107450   sqlite3 *db,                /* Database connection */
   107451   u8 op,                      /* Trigger opcode */
   107452   Token *pName                /* The target name */
   107453 ){
   107454   TriggerStep *pTriggerStep;
   107455 
   107456   pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
   107457   if( pTriggerStep ){
   107458     char *z = (char*)&pTriggerStep[1];
   107459     memcpy(z, pName->z, pName->n);
   107460     pTriggerStep->target.z = z;
   107461     pTriggerStep->target.n = pName->n;
   107462     pTriggerStep->op = op;
   107463   }
   107464   return pTriggerStep;
   107465 }
   107466 
   107467 /*
   107468 ** Build a trigger step out of an INSERT statement.  Return a pointer
   107469 ** to the new trigger step.
   107470 **
   107471 ** The parser calls this routine when it sees an INSERT inside the
   107472 ** body of a trigger.
   107473 */
   107474 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
   107475   sqlite3 *db,        /* The database connection */
   107476   Token *pTableName,  /* Name of the table into which we insert */
   107477   IdList *pColumn,    /* List of columns in pTableName to insert into */
   107478   Select *pSelect,    /* A SELECT statement that supplies values */
   107479   u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
   107480 ){
   107481   TriggerStep *pTriggerStep;
   107482 
   107483   assert(pSelect != 0 || db->mallocFailed);
   107484 
   107485   pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
   107486   if( pTriggerStep ){
   107487     pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
   107488     pTriggerStep->pIdList = pColumn;
   107489     pTriggerStep->orconf = orconf;
   107490   }else{
   107491     sqlite3IdListDelete(db, pColumn);
   107492   }
   107493   sqlite3SelectDelete(db, pSelect);
   107494 
   107495   return pTriggerStep;
   107496 }
   107497 
   107498 /*
   107499 ** Construct a trigger step that implements an UPDATE statement and return
   107500 ** a pointer to that trigger step.  The parser calls this routine when it
   107501 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
   107502 */
   107503 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
   107504   sqlite3 *db,         /* The database connection */
   107505   Token *pTableName,   /* Name of the table to be updated */
   107506   ExprList *pEList,    /* The SET clause: list of column and new values */
   107507   Expr *pWhere,        /* The WHERE clause */
   107508   u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
   107509 ){
   107510   TriggerStep *pTriggerStep;
   107511 
   107512   pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
   107513   if( pTriggerStep ){
   107514     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
   107515     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
   107516     pTriggerStep->orconf = orconf;
   107517   }
   107518   sqlite3ExprListDelete(db, pEList);
   107519   sqlite3ExprDelete(db, pWhere);
   107520   return pTriggerStep;
   107521 }
   107522 
   107523 /*
   107524 ** Construct a trigger step that implements a DELETE statement and return
   107525 ** a pointer to that trigger step.  The parser calls this routine when it
   107526 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
   107527 */
   107528 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
   107529   sqlite3 *db,            /* Database connection */
   107530   Token *pTableName,      /* The table from which rows are deleted */
   107531   Expr *pWhere            /* The WHERE clause */
   107532 ){
   107533   TriggerStep *pTriggerStep;
   107534 
   107535   pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
   107536   if( pTriggerStep ){
   107537     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
   107538     pTriggerStep->orconf = OE_Default;
   107539   }
   107540   sqlite3ExprDelete(db, pWhere);
   107541   return pTriggerStep;
   107542 }
   107543 
   107544 /*
   107545 ** Recursively delete a Trigger structure
   107546 */
   107547 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
   107548   if( pTrigger==0 ) return;
   107549   sqlite3DeleteTriggerStep(db, pTrigger->step_list);
   107550   sqlite3DbFree(db, pTrigger->zName);
   107551   sqlite3DbFree(db, pTrigger->table);
   107552   sqlite3ExprDelete(db, pTrigger->pWhen);
   107553   sqlite3IdListDelete(db, pTrigger->pColumns);
   107554   sqlite3DbFree(db, pTrigger);
   107555 }
   107556 
   107557 /*
   107558 ** This function is called to drop a trigger from the database schema.
   107559 **
   107560 ** This may be called directly from the parser and therefore identifies
   107561 ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
   107562 ** same job as this routine except it takes a pointer to the trigger
   107563 ** instead of the trigger name.
   107564 **/
   107565 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
   107566   Trigger *pTrigger = 0;
   107567   int i;
   107568   const char *zDb;
   107569   const char *zName;
   107570   int nName;
   107571   sqlite3 *db = pParse->db;
   107572 
   107573   if( db->mallocFailed ) goto drop_trigger_cleanup;
   107574   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   107575     goto drop_trigger_cleanup;
   107576   }
   107577 
   107578   assert( pName->nSrc==1 );
   107579   zDb = pName->a[0].zDatabase;
   107580   zName = pName->a[0].zName;
   107581   nName = sqlite3Strlen30(zName);
   107582   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
   107583   for(i=OMIT_TEMPDB; i<db->nDb; i++){
   107584     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
   107585     if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
   107586     assert( sqlite3SchemaMutexHeld(db, j, 0) );
   107587     pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
   107588     if( pTrigger ) break;
   107589   }
   107590   if( !pTrigger ){
   107591     if( !noErr ){
   107592       sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
   107593     }else{
   107594       sqlite3CodeVerifyNamedSchema(pParse, zDb);
   107595     }
   107596     pParse->checkSchema = 1;
   107597     goto drop_trigger_cleanup;
   107598   }
   107599   sqlite3DropTriggerPtr(pParse, pTrigger);
   107600 
   107601 drop_trigger_cleanup:
   107602   sqlite3SrcListDelete(db, pName);
   107603 }
   107604 
   107605 /*
   107606 ** Return a pointer to the Table structure for the table that a trigger
   107607 ** is set on.
   107608 */
   107609 static Table *tableOfTrigger(Trigger *pTrigger){
   107610   int n = sqlite3Strlen30(pTrigger->table);
   107611   return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
   107612 }
   107613 
   107614 
   107615 /*
   107616 ** Drop a trigger given a pointer to that trigger.
   107617 */
   107618 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
   107619   Table   *pTable;
   107620   Vdbe *v;
   107621   sqlite3 *db = pParse->db;
   107622   int iDb;
   107623 
   107624   iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
   107625   assert( iDb>=0 && iDb<db->nDb );
   107626   pTable = tableOfTrigger(pTrigger);
   107627   assert( pTable );
   107628   assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
   107629 #ifndef SQLITE_OMIT_AUTHORIZATION
   107630   {
   107631     int code = SQLITE_DROP_TRIGGER;
   107632     const char *zDb = db->aDb[iDb].zName;
   107633     const char *zTab = SCHEMA_TABLE(iDb);
   107634     if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
   107635     if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
   107636       sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
   107637       return;
   107638     }
   107639   }
   107640 #endif
   107641 
   107642   /* Generate code to destroy the database record of the trigger.
   107643   */
   107644   assert( pTable!=0 );
   107645   if( (v = sqlite3GetVdbe(pParse))!=0 ){
   107646     int base;
   107647     static const int iLn = VDBE_OFFSET_LINENO(2);
   107648     static const VdbeOpList dropTrigger[] = {
   107649       { OP_Rewind,     0, ADDR(9),  0},
   107650       { OP_String8,    0, 1,        0}, /* 1 */
   107651       { OP_Column,     0, 1,        2},
   107652       { OP_Ne,         2, ADDR(8),  1},
   107653       { OP_String8,    0, 1,        0}, /* 4: "trigger" */
   107654       { OP_Column,     0, 0,        2},
   107655       { OP_Ne,         2, ADDR(8),  1},
   107656       { OP_Delete,     0, 0,        0},
   107657       { OP_Next,       0, ADDR(1),  0}, /* 8 */
   107658     };
   107659 
   107660     sqlite3BeginWriteOperation(pParse, 0, iDb);
   107661     sqlite3OpenMasterTable(pParse, iDb);
   107662     base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger, iLn);
   107663     sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
   107664     sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
   107665     sqlite3ChangeCookie(pParse, iDb);
   107666     sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
   107667     sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
   107668     if( pParse->nMem<3 ){
   107669       pParse->nMem = 3;
   107670     }
   107671   }
   107672 }
   107673 
   107674 /*
   107675 ** Remove a trigger from the hash tables of the sqlite* pointer.
   107676 */
   107677 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
   107678   Trigger *pTrigger;
   107679   Hash *pHash;
   107680 
   107681   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   107682   pHash = &(db->aDb[iDb].pSchema->trigHash);
   107683   pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
   107684   if( ALWAYS(pTrigger) ){
   107685     if( pTrigger->pSchema==pTrigger->pTabSchema ){
   107686       Table *pTab = tableOfTrigger(pTrigger);
   107687       Trigger **pp;
   107688       for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
   107689       *pp = (*pp)->pNext;
   107690     }
   107691     sqlite3DeleteTrigger(db, pTrigger);
   107692     db->flags |= SQLITE_InternChanges;
   107693   }
   107694 }
   107695 
   107696 /*
   107697 ** pEList is the SET clause of an UPDATE statement.  Each entry
   107698 ** in pEList is of the format <id>=<expr>.  If any of the entries
   107699 ** in pEList have an <id> which matches an identifier in pIdList,
   107700 ** then return TRUE.  If pIdList==NULL, then it is considered a
   107701 ** wildcard that matches anything.  Likewise if pEList==NULL then
   107702 ** it matches anything so always return true.  Return false only
   107703 ** if there is no match.
   107704 */
   107705 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
   107706   int e;
   107707   if( pIdList==0 || NEVER(pEList==0) ) return 1;
   107708   for(e=0; e<pEList->nExpr; e++){
   107709     if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
   107710   }
   107711   return 0;
   107712 }
   107713 
   107714 /*
   107715 ** Return a list of all triggers on table pTab if there exists at least
   107716 ** one trigger that must be fired when an operation of type 'op' is
   107717 ** performed on the table, and, if that operation is an UPDATE, if at
   107718 ** least one of the columns in pChanges is being modified.
   107719 */
   107720 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
   107721   Parse *pParse,          /* Parse context */
   107722   Table *pTab,            /* The table the contains the triggers */
   107723   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
   107724   ExprList *pChanges,     /* Columns that change in an UPDATE statement */
   107725   int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
   107726 ){
   107727   int mask = 0;
   107728   Trigger *pList = 0;
   107729   Trigger *p;
   107730 
   107731   if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
   107732     pList = sqlite3TriggerList(pParse, pTab);
   107733   }
   107734   assert( pList==0 || IsVirtual(pTab)==0 );
   107735   for(p=pList; p; p=p->pNext){
   107736     if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
   107737       mask |= p->tr_tm;
   107738     }
   107739   }
   107740   if( pMask ){
   107741     *pMask = mask;
   107742   }
   107743   return (mask ? pList : 0);
   107744 }
   107745 
   107746 /*
   107747 ** Convert the pStep->target token into a SrcList and return a pointer
   107748 ** to that SrcList.
   107749 **
   107750 ** This routine adds a specific database name, if needed, to the target when
   107751 ** forming the SrcList.  This prevents a trigger in one database from
   107752 ** referring to a target in another database.  An exception is when the
   107753 ** trigger is in TEMP in which case it can refer to any other database it
   107754 ** wants.
   107755 */
   107756 static SrcList *targetSrcList(
   107757   Parse *pParse,       /* The parsing context */
   107758   TriggerStep *pStep   /* The trigger containing the target token */
   107759 ){
   107760   int iDb;             /* Index of the database to use */
   107761   SrcList *pSrc;       /* SrcList to be returned */
   107762 
   107763   pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
   107764   if( pSrc ){
   107765     assert( pSrc->nSrc>0 );
   107766     assert( pSrc->a!=0 );
   107767     iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
   107768     if( iDb==0 || iDb>=2 ){
   107769       sqlite3 *db = pParse->db;
   107770       assert( iDb<pParse->db->nDb );
   107771       pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
   107772     }
   107773   }
   107774   return pSrc;
   107775 }
   107776 
   107777 /*
   107778 ** Generate VDBE code for the statements inside the body of a single
   107779 ** trigger.
   107780 */
   107781 static int codeTriggerProgram(
   107782   Parse *pParse,            /* The parser context */
   107783   TriggerStep *pStepList,   /* List of statements inside the trigger body */
   107784   int orconf                /* Conflict algorithm. (OE_Abort, etc) */
   107785 ){
   107786   TriggerStep *pStep;
   107787   Vdbe *v = pParse->pVdbe;
   107788   sqlite3 *db = pParse->db;
   107789 
   107790   assert( pParse->pTriggerTab && pParse->pToplevel );
   107791   assert( pStepList );
   107792   assert( v!=0 );
   107793   for(pStep=pStepList; pStep; pStep=pStep->pNext){
   107794     /* Figure out the ON CONFLICT policy that will be used for this step
   107795     ** of the trigger program. If the statement that caused this trigger
   107796     ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
   107797     ** the ON CONFLICT policy that was specified as part of the trigger
   107798     ** step statement. Example:
   107799     **
   107800     **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
   107801     **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
   107802     **   END;
   107803     **
   107804     **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
   107805     **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
   107806     */
   107807     pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
   107808     assert( pParse->okConstFactor==0 );
   107809 
   107810     switch( pStep->op ){
   107811       case TK_UPDATE: {
   107812         sqlite3Update(pParse,
   107813           targetSrcList(pParse, pStep),
   107814           sqlite3ExprListDup(db, pStep->pExprList, 0),
   107815           sqlite3ExprDup(db, pStep->pWhere, 0),
   107816           pParse->eOrconf
   107817         );
   107818         break;
   107819       }
   107820       case TK_INSERT: {
   107821         sqlite3Insert(pParse,
   107822           targetSrcList(pParse, pStep),
   107823           sqlite3SelectDup(db, pStep->pSelect, 0),
   107824           sqlite3IdListDup(db, pStep->pIdList),
   107825           pParse->eOrconf
   107826         );
   107827         break;
   107828       }
   107829       case TK_DELETE: {
   107830         sqlite3DeleteFrom(pParse,
   107831           targetSrcList(pParse, pStep),
   107832           sqlite3ExprDup(db, pStep->pWhere, 0)
   107833         );
   107834         break;
   107835       }
   107836       default: assert( pStep->op==TK_SELECT ); {
   107837         SelectDest sDest;
   107838         Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
   107839         sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
   107840         sqlite3Select(pParse, pSelect, &sDest);
   107841         sqlite3SelectDelete(db, pSelect);
   107842         break;
   107843       }
   107844     }
   107845     if( pStep->op!=TK_SELECT ){
   107846       sqlite3VdbeAddOp0(v, OP_ResetCount);
   107847     }
   107848   }
   107849 
   107850   return 0;
   107851 }
   107852 
   107853 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
   107854 /*
   107855 ** This function is used to add VdbeComment() annotations to a VDBE
   107856 ** program. It is not used in production code, only for debugging.
   107857 */
   107858 static const char *onErrorText(int onError){
   107859   switch( onError ){
   107860     case OE_Abort:    return "abort";
   107861     case OE_Rollback: return "rollback";
   107862     case OE_Fail:     return "fail";
   107863     case OE_Replace:  return "replace";
   107864     case OE_Ignore:   return "ignore";
   107865     case OE_Default:  return "default";
   107866   }
   107867   return "n/a";
   107868 }
   107869 #endif
   107870 
   107871 /*
   107872 ** Parse context structure pFrom has just been used to create a sub-vdbe
   107873 ** (trigger program). If an error has occurred, transfer error information
   107874 ** from pFrom to pTo.
   107875 */
   107876 static void transferParseError(Parse *pTo, Parse *pFrom){
   107877   assert( pFrom->zErrMsg==0 || pFrom->nErr );
   107878   assert( pTo->zErrMsg==0 || pTo->nErr );
   107879   if( pTo->nErr==0 ){
   107880     pTo->zErrMsg = pFrom->zErrMsg;
   107881     pTo->nErr = pFrom->nErr;
   107882   }else{
   107883     sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
   107884   }
   107885 }
   107886 
   107887 /*
   107888 ** Create and populate a new TriggerPrg object with a sub-program
   107889 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
   107890 */
   107891 static TriggerPrg *codeRowTrigger(
   107892   Parse *pParse,       /* Current parse context */
   107893   Trigger *pTrigger,   /* Trigger to code */
   107894   Table *pTab,         /* The table pTrigger is attached to */
   107895   int orconf           /* ON CONFLICT policy to code trigger program with */
   107896 ){
   107897   Parse *pTop = sqlite3ParseToplevel(pParse);
   107898   sqlite3 *db = pParse->db;   /* Database handle */
   107899   TriggerPrg *pPrg;           /* Value to return */
   107900   Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
   107901   Vdbe *v;                    /* Temporary VM */
   107902   NameContext sNC;            /* Name context for sub-vdbe */
   107903   SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
   107904   Parse *pSubParse;           /* Parse context for sub-vdbe */
   107905   int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
   107906 
   107907   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
   107908   assert( pTop->pVdbe );
   107909 
   107910   /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
   107911   ** are freed if an error occurs, link them into the Parse.pTriggerPrg
   107912   ** list of the top-level Parse object sooner rather than later.  */
   107913   pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
   107914   if( !pPrg ) return 0;
   107915   pPrg->pNext = pTop->pTriggerPrg;
   107916   pTop->pTriggerPrg = pPrg;
   107917   pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
   107918   if( !pProgram ) return 0;
   107919   sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
   107920   pPrg->pTrigger = pTrigger;
   107921   pPrg->orconf = orconf;
   107922   pPrg->aColmask[0] = 0xffffffff;
   107923   pPrg->aColmask[1] = 0xffffffff;
   107924 
   107925   /* Allocate and populate a new Parse context to use for coding the
   107926   ** trigger sub-program.  */
   107927   pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
   107928   if( !pSubParse ) return 0;
   107929   memset(&sNC, 0, sizeof(sNC));
   107930   sNC.pParse = pSubParse;
   107931   pSubParse->db = db;
   107932   pSubParse->pTriggerTab = pTab;
   107933   pSubParse->pToplevel = pTop;
   107934   pSubParse->zAuthContext = pTrigger->zName;
   107935   pSubParse->eTriggerOp = pTrigger->op;
   107936   pSubParse->nQueryLoop = pParse->nQueryLoop;
   107937 
   107938   v = sqlite3GetVdbe(pSubParse);
   107939   if( v ){
   107940     VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
   107941       pTrigger->zName, onErrorText(orconf),
   107942       (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
   107943         (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
   107944         (pTrigger->op==TK_INSERT ? "INSERT" : ""),
   107945         (pTrigger->op==TK_DELETE ? "DELETE" : ""),
   107946       pTab->zName
   107947     ));
   107948 #ifndef SQLITE_OMIT_TRACE
   107949     sqlite3VdbeChangeP4(v, -1,
   107950       sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
   107951     );
   107952 #endif
   107953 
   107954     /* If one was specified, code the WHEN clause. If it evaluates to false
   107955     ** (or NULL) the sub-vdbe is immediately halted by jumping to the
   107956     ** OP_Halt inserted at the end of the program.  */
   107957     if( pTrigger->pWhen ){
   107958       pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
   107959       if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
   107960        && db->mallocFailed==0
   107961       ){
   107962         iEndTrigger = sqlite3VdbeMakeLabel(v);
   107963         sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
   107964       }
   107965       sqlite3ExprDelete(db, pWhen);
   107966     }
   107967 
   107968     /* Code the trigger program into the sub-vdbe. */
   107969     codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
   107970 
   107971     /* Insert an OP_Halt at the end of the sub-program. */
   107972     if( iEndTrigger ){
   107973       sqlite3VdbeResolveLabel(v, iEndTrigger);
   107974     }
   107975     sqlite3VdbeAddOp0(v, OP_Halt);
   107976     VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
   107977 
   107978     transferParseError(pParse, pSubParse);
   107979     if( db->mallocFailed==0 ){
   107980       pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
   107981     }
   107982     pProgram->nMem = pSubParse->nMem;
   107983     pProgram->nCsr = pSubParse->nTab;
   107984     pProgram->nOnce = pSubParse->nOnce;
   107985     pProgram->token = (void *)pTrigger;
   107986     pPrg->aColmask[0] = pSubParse->oldmask;
   107987     pPrg->aColmask[1] = pSubParse->newmask;
   107988     sqlite3VdbeDelete(v);
   107989   }
   107990 
   107991   assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
   107992   assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
   107993   sqlite3ParserReset(pSubParse);
   107994   sqlite3StackFree(db, pSubParse);
   107995 
   107996   return pPrg;
   107997 }
   107998 
   107999 /*
   108000 ** Return a pointer to a TriggerPrg object containing the sub-program for
   108001 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
   108002 ** TriggerPrg object exists, a new object is allocated and populated before
   108003 ** being returned.
   108004 */
   108005 static TriggerPrg *getRowTrigger(
   108006   Parse *pParse,       /* Current parse context */
   108007   Trigger *pTrigger,   /* Trigger to code */
   108008   Table *pTab,         /* The table trigger pTrigger is attached to */
   108009   int orconf           /* ON CONFLICT algorithm. */
   108010 ){
   108011   Parse *pRoot = sqlite3ParseToplevel(pParse);
   108012   TriggerPrg *pPrg;
   108013 
   108014   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
   108015 
   108016   /* It may be that this trigger has already been coded (or is in the
   108017   ** process of being coded). If this is the case, then an entry with
   108018   ** a matching TriggerPrg.pTrigger field will be present somewhere
   108019   ** in the Parse.pTriggerPrg list. Search for such an entry.  */
   108020   for(pPrg=pRoot->pTriggerPrg;
   108021       pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
   108022       pPrg=pPrg->pNext
   108023   );
   108024 
   108025   /* If an existing TriggerPrg could not be located, create a new one. */
   108026   if( !pPrg ){
   108027     pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
   108028   }
   108029 
   108030   return pPrg;
   108031 }
   108032 
   108033 /*
   108034 ** Generate code for the trigger program associated with trigger p on
   108035 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
   108036 ** function are the same as those described in the header function for
   108037 ** sqlite3CodeRowTrigger()
   108038 */
   108039 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
   108040   Parse *pParse,       /* Parse context */
   108041   Trigger *p,          /* Trigger to code */
   108042   Table *pTab,         /* The table to code triggers from */
   108043   int reg,             /* Reg array containing OLD.* and NEW.* values */
   108044   int orconf,          /* ON CONFLICT policy */
   108045   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
   108046 ){
   108047   Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
   108048   TriggerPrg *pPrg;
   108049   pPrg = getRowTrigger(pParse, p, pTab, orconf);
   108050   assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
   108051 
   108052   /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
   108053   ** is a pointer to the sub-vdbe containing the trigger program.  */
   108054   if( pPrg ){
   108055     int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
   108056 
   108057     sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
   108058     sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
   108059     VdbeComment(
   108060         (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
   108061 
   108062     /* Set the P5 operand of the OP_Program instruction to non-zero if
   108063     ** recursive invocation of this trigger program is disallowed. Recursive
   108064     ** invocation is disallowed if (a) the sub-program is really a trigger,
   108065     ** not a foreign key action, and (b) the flag to enable recursive triggers
   108066     ** is clear.  */
   108067     sqlite3VdbeChangeP5(v, (u8)bRecursive);
   108068   }
   108069 }
   108070 
   108071 /*
   108072 ** This is called to code the required FOR EACH ROW triggers for an operation
   108073 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
   108074 ** is given by the op parameter. The tr_tm parameter determines whether the
   108075 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
   108076 ** parameter pChanges is passed the list of columns being modified.
   108077 **
   108078 ** If there are no triggers that fire at the specified time for the specified
   108079 ** operation on pTab, this function is a no-op.
   108080 **
   108081 ** The reg argument is the address of the first in an array of registers
   108082 ** that contain the values substituted for the new.* and old.* references
   108083 ** in the trigger program. If N is the number of columns in table pTab
   108084 ** (a copy of pTab->nCol), then registers are populated as follows:
   108085 **
   108086 **   Register       Contains
   108087 **   ------------------------------------------------------
   108088 **   reg+0          OLD.rowid
   108089 **   reg+1          OLD.* value of left-most column of pTab
   108090 **   ...            ...
   108091 **   reg+N          OLD.* value of right-most column of pTab
   108092 **   reg+N+1        NEW.rowid
   108093 **   reg+N+2        OLD.* value of left-most column of pTab
   108094 **   ...            ...
   108095 **   reg+N+N+1      NEW.* value of right-most column of pTab
   108096 **
   108097 ** For ON DELETE triggers, the registers containing the NEW.* values will
   108098 ** never be accessed by the trigger program, so they are not allocated or
   108099 ** populated by the caller (there is no data to populate them with anyway).
   108100 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
   108101 ** are never accessed, and so are not allocated by the caller. So, for an
   108102 ** ON INSERT trigger, the value passed to this function as parameter reg
   108103 ** is not a readable register, although registers (reg+N) through
   108104 ** (reg+N+N+1) are.
   108105 **
   108106 ** Parameter orconf is the default conflict resolution algorithm for the
   108107 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
   108108 ** is the instruction that control should jump to if a trigger program
   108109 ** raises an IGNORE exception.
   108110 */
   108111 SQLITE_PRIVATE void sqlite3CodeRowTrigger(
   108112   Parse *pParse,       /* Parse context */
   108113   Trigger *pTrigger,   /* List of triggers on table pTab */
   108114   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
   108115   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
   108116   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
   108117   Table *pTab,         /* The table to code triggers from */
   108118   int reg,             /* The first in an array of registers (see above) */
   108119   int orconf,          /* ON CONFLICT policy */
   108120   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
   108121 ){
   108122   Trigger *p;          /* Used to iterate through pTrigger list */
   108123 
   108124   assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
   108125   assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
   108126   assert( (op==TK_UPDATE)==(pChanges!=0) );
   108127 
   108128   for(p=pTrigger; p; p=p->pNext){
   108129 
   108130     /* Sanity checking:  The schema for the trigger and for the table are
   108131     ** always defined.  The trigger must be in the same schema as the table
   108132     ** or else it must be a TEMP trigger. */
   108133     assert( p->pSchema!=0 );
   108134     assert( p->pTabSchema!=0 );
   108135     assert( p->pSchema==p->pTabSchema
   108136          || p->pSchema==pParse->db->aDb[1].pSchema );
   108137 
   108138     /* Determine whether we should code this trigger */
   108139     if( p->op==op
   108140      && p->tr_tm==tr_tm
   108141      && checkColumnOverlap(p->pColumns, pChanges)
   108142     ){
   108143       sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
   108144     }
   108145   }
   108146 }
   108147 
   108148 /*
   108149 ** Triggers may access values stored in the old.* or new.* pseudo-table.
   108150 ** This function returns a 32-bit bitmask indicating which columns of the
   108151 ** old.* or new.* tables actually are used by triggers. This information
   108152 ** may be used by the caller, for example, to avoid having to load the entire
   108153 ** old.* record into memory when executing an UPDATE or DELETE command.
   108154 **
   108155 ** Bit 0 of the returned mask is set if the left-most column of the
   108156 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
   108157 ** the second leftmost column value is required, and so on. If there
   108158 ** are more than 32 columns in the table, and at least one of the columns
   108159 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
   108160 **
   108161 ** It is not possible to determine if the old.rowid or new.rowid column is
   108162 ** accessed by triggers. The caller must always assume that it is.
   108163 **
   108164 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
   108165 ** applies to the old.* table. If 1, the new.* table.
   108166 **
   108167 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
   108168 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
   108169 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
   108170 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
   108171 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
   108172 */
   108173 SQLITE_PRIVATE u32 sqlite3TriggerColmask(
   108174   Parse *pParse,       /* Parse context */
   108175   Trigger *pTrigger,   /* List of triggers on table pTab */
   108176   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
   108177   int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
   108178   int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
   108179   Table *pTab,         /* The table to code triggers from */
   108180   int orconf           /* Default ON CONFLICT policy for trigger steps */
   108181 ){
   108182   const int op = pChanges ? TK_UPDATE : TK_DELETE;
   108183   u32 mask = 0;
   108184   Trigger *p;
   108185 
   108186   assert( isNew==1 || isNew==0 );
   108187   for(p=pTrigger; p; p=p->pNext){
   108188     if( p->op==op && (tr_tm&p->tr_tm)
   108189      && checkColumnOverlap(p->pColumns,pChanges)
   108190     ){
   108191       TriggerPrg *pPrg;
   108192       pPrg = getRowTrigger(pParse, p, pTab, orconf);
   108193       if( pPrg ){
   108194         mask |= pPrg->aColmask[isNew];
   108195       }
   108196     }
   108197   }
   108198 
   108199   return mask;
   108200 }
   108201 
   108202 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
   108203 
   108204 /************** End of trigger.c *********************************************/
   108205 /************** Begin file update.c ******************************************/
   108206 /*
   108207 ** 2001 September 15
   108208 **
   108209 ** The author disclaims copyright to this source code.  In place of
   108210 ** a legal notice, here is a blessing:
   108211 **
   108212 **    May you do good and not evil.
   108213 **    May you find forgiveness for yourself and forgive others.
   108214 **    May you share freely, never taking more than you give.
   108215 **
   108216 *************************************************************************
   108217 ** This file contains C code routines that are called by the parser
   108218 ** to handle UPDATE statements.
   108219 */
   108220 
   108221 #ifndef SQLITE_OMIT_VIRTUALTABLE
   108222 /* Forward declaration */
   108223 static void updateVirtualTable(
   108224   Parse *pParse,       /* The parsing context */
   108225   SrcList *pSrc,       /* The virtual table to be modified */
   108226   Table *pTab,         /* The virtual table */
   108227   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
   108228   Expr *pRowidExpr,    /* Expression used to recompute the rowid */
   108229   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
   108230   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
   108231   int onError          /* ON CONFLICT strategy */
   108232 );
   108233 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   108234 
   108235 /*
   108236 ** The most recently coded instruction was an OP_Column to retrieve the
   108237 ** i-th column of table pTab. This routine sets the P4 parameter of the
   108238 ** OP_Column to the default value, if any.
   108239 **
   108240 ** The default value of a column is specified by a DEFAULT clause in the
   108241 ** column definition. This was either supplied by the user when the table
   108242 ** was created, or added later to the table definition by an ALTER TABLE
   108243 ** command. If the latter, then the row-records in the table btree on disk
   108244 ** may not contain a value for the column and the default value, taken
   108245 ** from the P4 parameter of the OP_Column instruction, is returned instead.
   108246 ** If the former, then all row-records are guaranteed to include a value
   108247 ** for the column and the P4 value is not required.
   108248 **
   108249 ** Column definitions created by an ALTER TABLE command may only have
   108250 ** literal default values specified: a number, null or a string. (If a more
   108251 ** complicated default expression value was provided, it is evaluated
   108252 ** when the ALTER TABLE is executed and one of the literal values written
   108253 ** into the sqlite_master table.)
   108254 **
   108255 ** Therefore, the P4 parameter is only required if the default value for
   108256 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
   108257 ** function is capable of transforming these types of expressions into
   108258 ** sqlite3_value objects.
   108259 **
   108260 ** If parameter iReg is not negative, code an OP_RealAffinity instruction
   108261 ** on register iReg. This is used when an equivalent integer value is
   108262 ** stored in place of an 8-byte floating point value in order to save
   108263 ** space.
   108264 */
   108265 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
   108266   assert( pTab!=0 );
   108267   if( !pTab->pSelect ){
   108268     sqlite3_value *pValue = 0;
   108269     u8 enc = ENC(sqlite3VdbeDb(v));
   108270     Column *pCol = &pTab->aCol[i];
   108271     VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
   108272     assert( i<pTab->nCol );
   108273     sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
   108274                          pCol->affinity, &pValue);
   108275     if( pValue ){
   108276       sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
   108277     }
   108278 #ifndef SQLITE_OMIT_FLOATING_POINT
   108279     if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
   108280       sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
   108281     }
   108282 #endif
   108283   }
   108284 }
   108285 
   108286 /*
   108287 ** Process an UPDATE statement.
   108288 **
   108289 **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
   108290 **          \_______/ \________/     \______/       \________________/
   108291 *            onError   pTabList      pChanges             pWhere
   108292 */
   108293 SQLITE_PRIVATE void sqlite3Update(
   108294   Parse *pParse,         /* The parser context */
   108295   SrcList *pTabList,     /* The table in which we should change things */
   108296   ExprList *pChanges,    /* Things to be changed */
   108297   Expr *pWhere,          /* The WHERE clause.  May be null */
   108298   int onError            /* How to handle constraint errors */
   108299 ){
   108300   int i, j;              /* Loop counters */
   108301   Table *pTab;           /* The table to be updated */
   108302   int addrTop = 0;       /* VDBE instruction address of the start of the loop */
   108303   WhereInfo *pWInfo;     /* Information about the WHERE clause */
   108304   Vdbe *v;               /* The virtual database engine */
   108305   Index *pIdx;           /* For looping over indices */
   108306   Index *pPk;            /* The PRIMARY KEY index for WITHOUT ROWID tables */
   108307   int nIdx;              /* Number of indices that need updating */
   108308   int iBaseCur;          /* Base cursor number */
   108309   int iDataCur;          /* Cursor for the canonical data btree */
   108310   int iIdxCur;           /* Cursor for the first index */
   108311   sqlite3 *db;           /* The database structure */
   108312   int *aRegIdx = 0;      /* One register assigned to each index to be updated */
   108313   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
   108314                          ** an expression for the i-th column of the table.
   108315                          ** aXRef[i]==-1 if the i-th column is not changed. */
   108316   u8 *aToOpen;           /* 1 for tables and indices to be opened */
   108317   u8 chngPk;             /* PRIMARY KEY changed in a WITHOUT ROWID table */
   108318   u8 chngRowid;          /* Rowid changed in a normal table */
   108319   u8 chngKey;            /* Either chngPk or chngRowid */
   108320   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
   108321   AuthContext sContext;  /* The authorization context */
   108322   NameContext sNC;       /* The name-context to resolve expressions in */
   108323   int iDb;               /* Database containing the table being updated */
   108324   int okOnePass;         /* True for one-pass algorithm without the FIFO */
   108325   int hasFK;             /* True if foreign key processing is required */
   108326   int labelBreak;        /* Jump here to break out of UPDATE loop */
   108327   int labelContinue;     /* Jump here to continue next step of UPDATE loop */
   108328 
   108329 #ifndef SQLITE_OMIT_TRIGGER
   108330   int isView;            /* True when updating a view (INSTEAD OF trigger) */
   108331   Trigger *pTrigger;     /* List of triggers on pTab, if required */
   108332   int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
   108333 #endif
   108334   int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
   108335   int iEph = 0;          /* Ephemeral table holding all primary key values */
   108336   int nKey = 0;          /* Number of elements in regKey for WITHOUT ROWID */
   108337   int aiCurOnePass[2];   /* The write cursors opened by WHERE_ONEPASS */
   108338 
   108339   /* Register Allocations */
   108340   int regRowCount = 0;   /* A count of rows changed */
   108341   int regOldRowid;       /* The old rowid */
   108342   int regNewRowid;       /* The new rowid */
   108343   int regNew;            /* Content of the NEW.* table in triggers */
   108344   int regOld = 0;        /* Content of OLD.* table in triggers */
   108345   int regRowSet = 0;     /* Rowset of rows to be updated */
   108346   int regKey = 0;        /* composite PRIMARY KEY value */
   108347 
   108348   memset(&sContext, 0, sizeof(sContext));
   108349   db = pParse->db;
   108350   if( pParse->nErr || db->mallocFailed ){
   108351     goto update_cleanup;
   108352   }
   108353   assert( pTabList->nSrc==1 );
   108354 
   108355   /* Locate the table which we want to update.
   108356   */
   108357   pTab = sqlite3SrcListLookup(pParse, pTabList);
   108358   if( pTab==0 ) goto update_cleanup;
   108359   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   108360 
   108361   /* Figure out if we have any triggers and if the table being
   108362   ** updated is a view.
   108363   */
   108364 #ifndef SQLITE_OMIT_TRIGGER
   108365   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
   108366   isView = pTab->pSelect!=0;
   108367   assert( pTrigger || tmask==0 );
   108368 #else
   108369 # define pTrigger 0
   108370 # define isView 0
   108371 # define tmask 0
   108372 #endif
   108373 #ifdef SQLITE_OMIT_VIEW
   108374 # undef isView
   108375 # define isView 0
   108376 #endif
   108377 
   108378   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
   108379     goto update_cleanup;
   108380   }
   108381   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
   108382     goto update_cleanup;
   108383   }
   108384 
   108385   /* Allocate a cursors for the main database table and for all indices.
   108386   ** The index cursors might not be used, but if they are used they
   108387   ** need to occur right after the database cursor.  So go ahead and
   108388   ** allocate enough space, just in case.
   108389   */
   108390   pTabList->a[0].iCursor = iBaseCur = iDataCur = pParse->nTab++;
   108391   iIdxCur = iDataCur+1;
   108392   pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
   108393   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
   108394     if( IsPrimaryKeyIndex(pIdx) && pPk!=0 ){
   108395       iDataCur = pParse->nTab;
   108396       pTabList->a[0].iCursor = iDataCur;
   108397     }
   108398     pParse->nTab++;
   108399   }
   108400 
   108401   /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].
   108402   ** Initialize aXRef[] and aToOpen[] to their default values.
   108403   */
   108404   aXRef = sqlite3DbMallocRaw(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 );
   108405   if( aXRef==0 ) goto update_cleanup;
   108406   aRegIdx = aXRef+pTab->nCol;
   108407   aToOpen = (u8*)(aRegIdx+nIdx);
   108408   memset(aToOpen, 1, nIdx+1);
   108409   aToOpen[nIdx+1] = 0;
   108410   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
   108411 
   108412   /* Initialize the name-context */
   108413   memset(&sNC, 0, sizeof(sNC));
   108414   sNC.pParse = pParse;
   108415   sNC.pSrcList = pTabList;
   108416 
   108417   /* Resolve the column names in all the expressions of the
   108418   ** of the UPDATE statement.  Also find the column index
   108419   ** for each column to be updated in the pChanges array.  For each
   108420   ** column to be updated, make sure we have authorization to change
   108421   ** that column.
   108422   */
   108423   chngRowid = chngPk = 0;
   108424   for(i=0; i<pChanges->nExpr; i++){
   108425     if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
   108426       goto update_cleanup;
   108427     }
   108428     for(j=0; j<pTab->nCol; j++){
   108429       if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
   108430         if( j==pTab->iPKey ){
   108431           chngRowid = 1;
   108432           pRowidExpr = pChanges->a[i].pExpr;
   108433         }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
   108434           chngPk = 1;
   108435         }
   108436         aXRef[j] = i;
   108437         break;
   108438       }
   108439     }
   108440     if( j>=pTab->nCol ){
   108441       if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
   108442         j = -1;
   108443         chngRowid = 1;
   108444         pRowidExpr = pChanges->a[i].pExpr;
   108445       }else{
   108446         sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
   108447         pParse->checkSchema = 1;
   108448         goto update_cleanup;
   108449       }
   108450     }
   108451 #ifndef SQLITE_OMIT_AUTHORIZATION
   108452     {
   108453       int rc;
   108454       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
   108455                             j<0 ? "ROWID" : pTab->aCol[j].zName,
   108456                             db->aDb[iDb].zName);
   108457       if( rc==SQLITE_DENY ){
   108458         goto update_cleanup;
   108459       }else if( rc==SQLITE_IGNORE ){
   108460         aXRef[j] = -1;
   108461       }
   108462     }
   108463 #endif
   108464   }
   108465   assert( (chngRowid & chngPk)==0 );
   108466   assert( chngRowid==0 || chngRowid==1 );
   108467   assert( chngPk==0 || chngPk==1 );
   108468   chngKey = chngRowid + chngPk;
   108469 
   108470   /* The SET expressions are not actually used inside the WHERE loop.
   108471   ** So reset the colUsed mask
   108472   */
   108473   pTabList->a[0].colUsed = 0;
   108474 
   108475   hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
   108476 
   108477   /* There is one entry in the aRegIdx[] array for each index on the table
   108478   ** being updated.  Fill in aRegIdx[] with a register number that will hold
   108479   ** the key for accessing each index.
   108480   */
   108481   for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
   108482     int reg;
   108483     if( chngKey || hasFK || pIdx->pPartIdxWhere || pIdx==pPk ){
   108484       reg = ++pParse->nMem;
   108485     }else{
   108486       reg = 0;
   108487       for(i=0; i<pIdx->nKeyCol; i++){
   108488         if( aXRef[pIdx->aiColumn[i]]>=0 ){
   108489           reg = ++pParse->nMem;
   108490           break;
   108491         }
   108492       }
   108493     }
   108494     if( reg==0 ) aToOpen[j+1] = 0;
   108495     aRegIdx[j] = reg;
   108496   }
   108497 
   108498   /* Begin generating code. */
   108499   v = sqlite3GetVdbe(pParse);
   108500   if( v==0 ) goto update_cleanup;
   108501   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
   108502   sqlite3BeginWriteOperation(pParse, 1, iDb);
   108503 
   108504 #ifndef SQLITE_OMIT_VIRTUALTABLE
   108505   /* Virtual tables must be handled separately */
   108506   if( IsVirtual(pTab) ){
   108507     updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
   108508                        pWhere, onError);
   108509     pWhere = 0;
   108510     pTabList = 0;
   108511     goto update_cleanup;
   108512   }
   108513 #endif
   108514 
   108515   /* Allocate required registers. */
   108516   regRowSet = ++pParse->nMem;
   108517   regOldRowid = regNewRowid = ++pParse->nMem;
   108518   if( chngPk || pTrigger || hasFK ){
   108519     regOld = pParse->nMem + 1;
   108520     pParse->nMem += pTab->nCol;
   108521   }
   108522   if( chngKey || pTrigger || hasFK ){
   108523     regNewRowid = ++pParse->nMem;
   108524   }
   108525   regNew = pParse->nMem + 1;
   108526   pParse->nMem += pTab->nCol;
   108527 
   108528   /* Start the view context. */
   108529   if( isView ){
   108530     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
   108531   }
   108532 
   108533   /* If we are trying to update a view, realize that view into
   108534   ** a ephemeral table.
   108535   */
   108536 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
   108537   if( isView ){
   108538     sqlite3MaterializeView(pParse, pTab, pWhere, iDataCur);
   108539   }
   108540 #endif
   108541 
   108542   /* Resolve the column names in all the expressions in the
   108543   ** WHERE clause.
   108544   */
   108545   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
   108546     goto update_cleanup;
   108547   }
   108548 
   108549   /* Begin the database scan
   108550   */
   108551   if( HasRowid(pTab) ){
   108552     sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
   108553     pWInfo = sqlite3WhereBegin(
   108554         pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, iIdxCur
   108555     );
   108556     if( pWInfo==0 ) goto update_cleanup;
   108557     okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
   108558 
   108559     /* Remember the rowid of every item to be updated.
   108560     */
   108561     sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
   108562     if( !okOnePass ){
   108563       sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
   108564     }
   108565 
   108566     /* End the database scan loop.
   108567     */
   108568     sqlite3WhereEnd(pWInfo);
   108569   }else{
   108570     int iPk;         /* First of nPk memory cells holding PRIMARY KEY value */
   108571     i16 nPk;         /* Number of components of the PRIMARY KEY */
   108572     int addrOpen;    /* Address of the OpenEphemeral instruction */
   108573 
   108574     assert( pPk!=0 );
   108575     nPk = pPk->nKeyCol;
   108576     iPk = pParse->nMem+1;
   108577     pParse->nMem += nPk;
   108578     regKey = ++pParse->nMem;
   108579     iEph = pParse->nTab++;
   108580     sqlite3VdbeAddOp2(v, OP_Null, 0, iPk);
   108581     addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
   108582     sqlite3VdbeSetP4KeyInfo(pParse, pPk);
   108583     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0,
   108584                                WHERE_ONEPASS_DESIRED, iIdxCur);
   108585     if( pWInfo==0 ) goto update_cleanup;
   108586     okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
   108587     for(i=0; i<nPk; i++){
   108588       sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, pPk->aiColumn[i],
   108589                                       iPk+i);
   108590     }
   108591     if( okOnePass ){
   108592       sqlite3VdbeChangeToNoop(v, addrOpen);
   108593       nKey = nPk;
   108594       regKey = iPk;
   108595     }else{
   108596       sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
   108597                         sqlite3IndexAffinityStr(v, pPk), nPk);
   108598       sqlite3VdbeAddOp2(v, OP_IdxInsert, iEph, regKey);
   108599     }
   108600     sqlite3WhereEnd(pWInfo);
   108601   }
   108602 
   108603   /* Initialize the count of updated rows
   108604   */
   108605   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
   108606     regRowCount = ++pParse->nMem;
   108607     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
   108608   }
   108609 
   108610   labelBreak = sqlite3VdbeMakeLabel(v);
   108611   if( !isView ){
   108612     /*
   108613     ** Open every index that needs updating.  Note that if any
   108614     ** index could potentially invoke a REPLACE conflict resolution
   108615     ** action, then we need to open all indices because we might need
   108616     ** to be deleting some records.
   108617     */
   108618     if( onError==OE_Replace ){
   108619       memset(aToOpen, 1, nIdx+1);
   108620     }else{
   108621       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   108622         if( pIdx->onError==OE_Replace ){
   108623           memset(aToOpen, 1, nIdx+1);
   108624           break;
   108625         }
   108626       }
   108627     }
   108628     if( okOnePass ){
   108629       if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
   108630       if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
   108631     }
   108632     sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, iBaseCur, aToOpen,
   108633                                0, 0);
   108634   }
   108635 
   108636   /* Top of the update loop */
   108637   if( okOnePass ){
   108638     if( aToOpen[iDataCur-iBaseCur] ){
   108639       assert( pPk!=0 );
   108640       sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey, nKey);
   108641       VdbeCoverageNeverTaken(v);
   108642     }
   108643     labelContinue = labelBreak;
   108644     sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
   108645     VdbeCoverageIf(v, pPk==0);
   108646     VdbeCoverageIf(v, pPk!=0);
   108647   }else if( pPk ){
   108648     labelContinue = sqlite3VdbeMakeLabel(v);
   108649     sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
   108650     addrTop = sqlite3VdbeAddOp2(v, OP_RowKey, iEph, regKey);
   108651     sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
   108652     VdbeCoverage(v);
   108653   }else{
   108654     labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, labelBreak,
   108655                              regOldRowid);
   108656     VdbeCoverage(v);
   108657     sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
   108658     VdbeCoverage(v);
   108659   }
   108660 
   108661   /* If the record number will change, set register regNewRowid to
   108662   ** contain the new value. If the record number is not being modified,
   108663   ** then regNewRowid is the same register as regOldRowid, which is
   108664   ** already populated.  */
   108665   assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
   108666   if( chngRowid ){
   108667     sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
   108668     sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
   108669   }
   108670 
   108671   /* Compute the old pre-UPDATE content of the row being changed, if that
   108672   ** information is needed */
   108673   if( chngPk || hasFK || pTrigger ){
   108674     u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
   108675     oldmask |= sqlite3TriggerColmask(pParse,
   108676         pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
   108677     );
   108678     for(i=0; i<pTab->nCol; i++){
   108679       if( oldmask==0xffffffff
   108680        || (i<32 && (oldmask & MASKBIT32(i))!=0)
   108681        || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
   108682       ){
   108683         testcase(  oldmask!=0xffffffff && i==31 );
   108684         sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
   108685       }else{
   108686         sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
   108687       }
   108688     }
   108689     if( chngRowid==0 && pPk==0 ){
   108690       sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
   108691     }
   108692   }
   108693 
   108694   /* Populate the array of registers beginning at regNew with the new
   108695   ** row data. This array is used to check constaints, create the new
   108696   ** table and index records, and as the values for any new.* references
   108697   ** made by triggers.
   108698   **
   108699   ** If there are one or more BEFORE triggers, then do not populate the
   108700   ** registers associated with columns that are (a) not modified by
   108701   ** this UPDATE statement and (b) not accessed by new.* references. The
   108702   ** values for registers not modified by the UPDATE must be reloaded from
   108703   ** the database after the BEFORE triggers are fired anyway (as the trigger
   108704   ** may have modified them). So not loading those that are not going to
   108705   ** be used eliminates some redundant opcodes.
   108706   */
   108707   newmask = sqlite3TriggerColmask(
   108708       pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
   108709   );
   108710   /*sqlite3VdbeAddOp3(v, OP_Null, 0, regNew, regNew+pTab->nCol-1);*/
   108711   for(i=0; i<pTab->nCol; i++){
   108712     if( i==pTab->iPKey ){
   108713       sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
   108714     }else{
   108715       j = aXRef[i];
   108716       if( j>=0 ){
   108717         sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
   108718       }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
   108719         /* This branch loads the value of a column that will not be changed
   108720         ** into a register. This is done if there are no BEFORE triggers, or
   108721         ** if there are one or more BEFORE triggers that use this value via
   108722         ** a new.* reference in a trigger program.
   108723         */
   108724         testcase( i==31 );
   108725         testcase( i==32 );
   108726         sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
   108727       }else{
   108728         sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
   108729       }
   108730     }
   108731   }
   108732 
   108733   /* Fire any BEFORE UPDATE triggers. This happens before constraints are
   108734   ** verified. One could argue that this is wrong.
   108735   */
   108736   if( tmask&TRIGGER_BEFORE ){
   108737     sqlite3TableAffinity(v, pTab, regNew);
   108738     sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
   108739         TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
   108740 
   108741     /* The row-trigger may have deleted the row being updated. In this
   108742     ** case, jump to the next row. No updates or AFTER triggers are
   108743     ** required. This behavior - what happens when the row being updated
   108744     ** is deleted or renamed by a BEFORE trigger - is left undefined in the
   108745     ** documentation.
   108746     */
   108747     if( pPk ){
   108748       sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
   108749       VdbeCoverage(v);
   108750     }else{
   108751       sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
   108752       VdbeCoverage(v);
   108753     }
   108754 
   108755     /* If it did not delete it, the row-trigger may still have modified
   108756     ** some of the columns of the row being updated. Load the values for
   108757     ** all columns not modified by the update statement into their
   108758     ** registers in case this has happened.
   108759     */
   108760     for(i=0; i<pTab->nCol; i++){
   108761       if( aXRef[i]<0 && i!=pTab->iPKey ){
   108762         sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
   108763       }
   108764     }
   108765   }
   108766 
   108767   if( !isView ){
   108768     int j1 = 0;           /* Address of jump instruction */
   108769     int bReplace = 0;     /* True if REPLACE conflict resolution might happen */
   108770 
   108771     /* Do constraint checks. */
   108772     assert( regOldRowid>0 );
   108773     sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
   108774         regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace);
   108775 
   108776     /* Do FK constraint checks. */
   108777     if( hasFK ){
   108778       sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
   108779     }
   108780 
   108781     /* Delete the index entries associated with the current record.  */
   108782     if( bReplace || chngKey ){
   108783       if( pPk ){
   108784         j1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey);
   108785       }else{
   108786         j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
   108787       }
   108788       VdbeCoverageNeverTaken(v);
   108789     }
   108790     sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx);
   108791 
   108792     /* If changing the record number, delete the old record.  */
   108793     if( hasFK || chngKey || pPk!=0 ){
   108794       sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
   108795     }
   108796     if( bReplace || chngKey ){
   108797       sqlite3VdbeJumpHere(v, j1);
   108798     }
   108799 
   108800     if( hasFK ){
   108801       sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
   108802     }
   108803 
   108804     /* Insert the new index entries and the new record. */
   108805     sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
   108806                              regNewRowid, aRegIdx, 1, 0, 0);
   108807 
   108808     /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
   108809     ** handle rows (possibly in other tables) that refer via a foreign key
   108810     ** to the row just updated. */
   108811     if( hasFK ){
   108812       sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
   108813     }
   108814   }
   108815 
   108816   /* Increment the row counter
   108817   */
   108818   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
   108819     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
   108820   }
   108821 
   108822   sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
   108823       TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
   108824 
   108825   /* Repeat the above with the next record to be updated, until
   108826   ** all record selected by the WHERE clause have been updated.
   108827   */
   108828   if( okOnePass ){
   108829     /* Nothing to do at end-of-loop for a single-pass */
   108830   }else if( pPk ){
   108831     sqlite3VdbeResolveLabel(v, labelContinue);
   108832     sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
   108833   }else{
   108834     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelContinue);
   108835   }
   108836   sqlite3VdbeResolveLabel(v, labelBreak);
   108837 
   108838   /* Close all tables */
   108839   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
   108840     assert( aRegIdx );
   108841     if( aToOpen[i+1] ){
   108842       sqlite3VdbeAddOp2(v, OP_Close, iIdxCur+i, 0);
   108843     }
   108844   }
   108845   if( iDataCur<iIdxCur ) sqlite3VdbeAddOp2(v, OP_Close, iDataCur, 0);
   108846 
   108847   /* Update the sqlite_sequence table by storing the content of the
   108848   ** maximum rowid counter values recorded while inserting into
   108849   ** autoincrement tables.
   108850   */
   108851   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
   108852     sqlite3AutoincrementEnd(pParse);
   108853   }
   108854 
   108855   /*
   108856   ** Return the number of rows that were changed. If this routine is
   108857   ** generating code because of a call to sqlite3NestedParse(), do not
   108858   ** invoke the callback function.
   108859   */
   108860   if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
   108861     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
   108862     sqlite3VdbeSetNumCols(v, 1);
   108863     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
   108864   }
   108865 
   108866 update_cleanup:
   108867   sqlite3AuthContextPop(&sContext);
   108868   sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
   108869   sqlite3SrcListDelete(db, pTabList);
   108870   sqlite3ExprListDelete(db, pChanges);
   108871   sqlite3ExprDelete(db, pWhere);
   108872   return;
   108873 }
   108874 /* Make sure "isView" and other macros defined above are undefined. Otherwise
   108875 ** thely may interfere with compilation of other functions in this file
   108876 ** (or in another file, if this file becomes part of the amalgamation).  */
   108877 #ifdef isView
   108878  #undef isView
   108879 #endif
   108880 #ifdef pTrigger
   108881  #undef pTrigger
   108882 #endif
   108883 
   108884 #ifndef SQLITE_OMIT_VIRTUALTABLE
   108885 /*
   108886 ** Generate code for an UPDATE of a virtual table.
   108887 **
   108888 ** The strategy is that we create an ephemerial table that contains
   108889 ** for each row to be changed:
   108890 **
   108891 **   (A)  The original rowid of that row.
   108892 **   (B)  The revised rowid for the row. (note1)
   108893 **   (C)  The content of every column in the row.
   108894 **
   108895 ** Then we loop over this ephemeral table and for each row in
   108896 ** the ephermeral table call VUpdate.
   108897 **
   108898 ** When finished, drop the ephemeral table.
   108899 **
   108900 ** (note1) Actually, if we know in advance that (A) is always the same
   108901 ** as (B) we only store (A), then duplicate (A) when pulling
   108902 ** it out of the ephemeral table before calling VUpdate.
   108903 */
   108904 static void updateVirtualTable(
   108905   Parse *pParse,       /* The parsing context */
   108906   SrcList *pSrc,       /* The virtual table to be modified */
   108907   Table *pTab,         /* The virtual table */
   108908   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
   108909   Expr *pRowid,        /* Expression used to recompute the rowid */
   108910   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
   108911   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
   108912   int onError          /* ON CONFLICT strategy */
   108913 ){
   108914   Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
   108915   ExprList *pEList = 0;     /* The result set of the SELECT statement */
   108916   Select *pSelect = 0;      /* The SELECT statement */
   108917   Expr *pExpr;              /* Temporary expression */
   108918   int ephemTab;             /* Table holding the result of the SELECT */
   108919   int i;                    /* Loop counter */
   108920   int addr;                 /* Address of top of loop */
   108921   int iReg;                 /* First register in set passed to OP_VUpdate */
   108922   sqlite3 *db = pParse->db; /* Database connection */
   108923   const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
   108924   SelectDest dest;
   108925 
   108926   /* Construct the SELECT statement that will find the new values for
   108927   ** all updated rows.
   108928   */
   108929   pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
   108930   if( pRowid ){
   108931     pEList = sqlite3ExprListAppend(pParse, pEList,
   108932                                    sqlite3ExprDup(db, pRowid, 0));
   108933   }
   108934   assert( pTab->iPKey<0 );
   108935   for(i=0; i<pTab->nCol; i++){
   108936     if( aXRef[i]>=0 ){
   108937       pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
   108938     }else{
   108939       pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
   108940     }
   108941     pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
   108942   }
   108943   pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
   108944 
   108945   /* Create the ephemeral table into which the update results will
   108946   ** be stored.
   108947   */
   108948   assert( v );
   108949   ephemTab = pParse->nTab++;
   108950   sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
   108951   sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
   108952 
   108953   /* fill the ephemeral table
   108954   */
   108955   sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
   108956   sqlite3Select(pParse, pSelect, &dest);
   108957 
   108958   /* Generate code to scan the ephemeral table and call VUpdate. */
   108959   iReg = ++pParse->nMem;
   108960   pParse->nMem += pTab->nCol+1;
   108961   addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0); VdbeCoverage(v);
   108962   sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
   108963   sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
   108964   for(i=0; i<pTab->nCol; i++){
   108965     sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
   108966   }
   108967   sqlite3VtabMakeWritable(pParse, pTab);
   108968   sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
   108969   sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
   108970   sqlite3MayAbort(pParse);
   108971   sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
   108972   sqlite3VdbeJumpHere(v, addr);
   108973   sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
   108974 
   108975   /* Cleanup */
   108976   sqlite3SelectDelete(db, pSelect);
   108977 }
   108978 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   108979 
   108980 /************** End of update.c **********************************************/
   108981 /************** Begin file vacuum.c ******************************************/
   108982 /*
   108983 ** 2003 April 6
   108984 **
   108985 ** The author disclaims copyright to this source code.  In place of
   108986 ** a legal notice, here is a blessing:
   108987 **
   108988 **    May you do good and not evil.
   108989 **    May you find forgiveness for yourself and forgive others.
   108990 **    May you share freely, never taking more than you give.
   108991 **
   108992 *************************************************************************
   108993 ** This file contains code used to implement the VACUUM command.
   108994 **
   108995 ** Most of the code in this file may be omitted by defining the
   108996 ** SQLITE_OMIT_VACUUM macro.
   108997 */
   108998 
   108999 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
   109000 /*
   109001 ** Finalize a prepared statement.  If there was an error, store the
   109002 ** text of the error message in *pzErrMsg.  Return the result code.
   109003 */
   109004 static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
   109005   int rc;
   109006   rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
   109007   if( rc ){
   109008     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
   109009   }
   109010   return rc;
   109011 }
   109012 
   109013 /*
   109014 ** Execute zSql on database db. Return an error code.
   109015 */
   109016 static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
   109017   sqlite3_stmt *pStmt;
   109018   VVA_ONLY( int rc; )
   109019   if( !zSql ){
   109020     return SQLITE_NOMEM;
   109021   }
   109022   if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
   109023     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
   109024     return sqlite3_errcode(db);
   109025   }
   109026   VVA_ONLY( rc = ) sqlite3_step(pStmt);
   109027   assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
   109028   return vacuumFinalize(db, pStmt, pzErrMsg);
   109029 }
   109030 
   109031 /*
   109032 ** Execute zSql on database db. The statement returns exactly
   109033 ** one column. Execute this as SQL on the same database.
   109034 */
   109035 static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
   109036   sqlite3_stmt *pStmt;
   109037   int rc;
   109038 
   109039   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
   109040   if( rc!=SQLITE_OK ) return rc;
   109041 
   109042   while( SQLITE_ROW==sqlite3_step(pStmt) ){
   109043     rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
   109044     if( rc!=SQLITE_OK ){
   109045       vacuumFinalize(db, pStmt, pzErrMsg);
   109046       return rc;
   109047     }
   109048   }
   109049 
   109050   return vacuumFinalize(db, pStmt, pzErrMsg);
   109051 }
   109052 
   109053 /*
   109054 ** The VACUUM command is used to clean up the database,
   109055 ** collapse free space, etc.  It is modelled after the VACUUM command
   109056 ** in PostgreSQL.  The VACUUM command works as follows:
   109057 **
   109058 **   (1)  Create a new transient database file
   109059 **   (2)  Copy all content from the database being vacuumed into
   109060 **        the new transient database file
   109061 **   (3)  Copy content from the transient database back into the
   109062 **        original database.
   109063 **
   109064 ** The transient database requires temporary disk space approximately
   109065 ** equal to the size of the original database.  The copy operation of
   109066 ** step (3) requires additional temporary disk space approximately equal
   109067 ** to the size of the original database for the rollback journal.
   109068 ** Hence, temporary disk space that is approximately 2x the size of the
   109069 ** orginal database is required.  Every page of the database is written
   109070 ** approximately 3 times:  Once for step (2) and twice for step (3).
   109071 ** Two writes per page are required in step (3) because the original
   109072 ** database content must be written into the rollback journal prior to
   109073 ** overwriting the database with the vacuumed content.
   109074 **
   109075 ** Only 1x temporary space and only 1x writes would be required if
   109076 ** the copy of step (3) were replace by deleting the original database
   109077 ** and renaming the transient database as the original.  But that will
   109078 ** not work if other processes are attached to the original database.
   109079 ** And a power loss in between deleting the original and renaming the
   109080 ** transient would cause the database file to appear to be deleted
   109081 ** following reboot.
   109082 */
   109083 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
   109084   Vdbe *v = sqlite3GetVdbe(pParse);
   109085   if( v ){
   109086     sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
   109087     sqlite3VdbeUsesBtree(v, 0);
   109088   }
   109089   return;
   109090 }
   109091 
   109092 /*
   109093 ** This routine implements the OP_Vacuum opcode of the VDBE.
   109094 */
   109095 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
   109096   int rc = SQLITE_OK;     /* Return code from service routines */
   109097   Btree *pMain;           /* The database being vacuumed */
   109098   Btree *pTemp;           /* The temporary database we vacuum into */
   109099   char *zSql = 0;         /* SQL statements */
   109100   int saved_flags;        /* Saved value of the db->flags */
   109101   int saved_nChange;      /* Saved value of db->nChange */
   109102   int saved_nTotalChange; /* Saved value of db->nTotalChange */
   109103   void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
   109104   Db *pDb = 0;            /* Database to detach at end of vacuum */
   109105   int isMemDb;            /* True if vacuuming a :memory: database */
   109106   int nRes;               /* Bytes of reserved space at the end of each page */
   109107   int nDb;                /* Number of attached databases */
   109108 
   109109   if( !db->autoCommit ){
   109110     sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
   109111     return SQLITE_ERROR;
   109112   }
   109113   if( db->nVdbeActive>1 ){
   109114     sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
   109115     return SQLITE_ERROR;
   109116   }
   109117 
   109118   /* Save the current value of the database flags so that it can be
   109119   ** restored before returning. Then set the writable-schema flag, and
   109120   ** disable CHECK and foreign key constraints.  */
   109121   saved_flags = db->flags;
   109122   saved_nChange = db->nChange;
   109123   saved_nTotalChange = db->nTotalChange;
   109124   saved_xTrace = db->xTrace;
   109125   db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
   109126   db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
   109127   db->xTrace = 0;
   109128 
   109129   pMain = db->aDb[0].pBt;
   109130   isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
   109131 
   109132   /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
   109133   ** can be set to 'off' for this file, as it is not recovered if a crash
   109134   ** occurs anyway. The integrity of the database is maintained by a
   109135   ** (possibly synchronous) transaction opened on the main database before
   109136   ** sqlite3BtreeCopyFile() is called.
   109137   **
   109138   ** An optimisation would be to use a non-journaled pager.
   109139   ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
   109140   ** that actually made the VACUUM run slower.  Very little journalling
   109141   ** actually occurs when doing a vacuum since the vacuum_db is initially
   109142   ** empty.  Only the journal header is written.  Apparently it takes more
   109143   ** time to parse and run the PRAGMA to turn journalling off than it does
   109144   ** to write the journal header file.
   109145   */
   109146   nDb = db->nDb;
   109147   if( sqlite3TempInMemory(db) ){
   109148     zSql = "ATTACH ':memory:' AS vacuum_db;";
   109149   }else{
   109150     zSql = "ATTACH '' AS vacuum_db;";
   109151   }
   109152   rc = execSql(db, pzErrMsg, zSql);
   109153   if( db->nDb>nDb ){
   109154     pDb = &db->aDb[db->nDb-1];
   109155     assert( strcmp(pDb->zName,"vacuum_db")==0 );
   109156   }
   109157   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   109158   pTemp = db->aDb[db->nDb-1].pBt;
   109159 
   109160   /* The call to execSql() to attach the temp database has left the file
   109161   ** locked (as there was more than one active statement when the transaction
   109162   ** to read the schema was concluded. Unlock it here so that this doesn't
   109163   ** cause problems for the call to BtreeSetPageSize() below.  */
   109164   sqlite3BtreeCommit(pTemp);
   109165 
   109166   nRes = sqlite3BtreeGetReserve(pMain);
   109167 
   109168   /* A VACUUM cannot change the pagesize of an encrypted database. */
   109169 #ifdef SQLITE_HAS_CODEC
   109170   if( db->nextPagesize ){
   109171     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
   109172     int nKey;
   109173     char *zKey;
   109174     sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
   109175     if( nKey ) db->nextPagesize = 0;
   109176   }
   109177 #endif
   109178 
   109179   rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
   109180   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   109181 
   109182   /* Begin a transaction and take an exclusive lock on the main database
   109183   ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
   109184   ** to ensure that we do not try to change the page-size on a WAL database.
   109185   */
   109186   rc = execSql(db, pzErrMsg, "BEGIN;");
   109187   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   109188   rc = sqlite3BtreeBeginTrans(pMain, 2);
   109189   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   109190 
   109191   /* Do not attempt to change the page size for a WAL database */
   109192   if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
   109193                                                ==PAGER_JOURNALMODE_WAL ){
   109194     db->nextPagesize = 0;
   109195   }
   109196 
   109197   if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
   109198    || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
   109199    || NEVER(db->mallocFailed)
   109200   ){
   109201     rc = SQLITE_NOMEM;
   109202     goto end_of_vacuum;
   109203   }
   109204 
   109205 #ifndef SQLITE_OMIT_AUTOVACUUM
   109206   sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
   109207                                            sqlite3BtreeGetAutoVacuum(pMain));
   109208 #endif
   109209 
   109210   /* Query the schema of the main database. Create a mirror schema
   109211   ** in the temporary database.
   109212   */
   109213   rc = execExecSql(db, pzErrMsg,
   109214       "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
   109215       "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
   109216       "   AND coalesce(rootpage,1)>0"
   109217   );
   109218   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   109219   rc = execExecSql(db, pzErrMsg,
   109220       "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
   109221       "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
   109222   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   109223   rc = execExecSql(db, pzErrMsg,
   109224       "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
   109225       "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
   109226   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   109227 
   109228   /* Loop through the tables in the main database. For each, do
   109229   ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
   109230   ** the contents to the temporary database.
   109231   */
   109232   rc = execExecSql(db, pzErrMsg,
   109233       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
   109234       "|| ' SELECT * FROM main.' || quote(name) || ';'"
   109235       "FROM main.sqlite_master "
   109236       "WHERE type = 'table' AND name!='sqlite_sequence' "
   109237       "  AND coalesce(rootpage,1)>0"
   109238   );
   109239   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   109240 
   109241   /* Copy over the sequence table
   109242   */
   109243   rc = execExecSql(db, pzErrMsg,
   109244       "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
   109245       "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
   109246   );
   109247   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   109248   rc = execExecSql(db, pzErrMsg,
   109249       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
   109250       "|| ' SELECT * FROM main.' || quote(name) || ';' "
   109251       "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
   109252   );
   109253   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   109254 
   109255 
   109256   /* Copy the triggers, views, and virtual tables from the main database
   109257   ** over to the temporary database.  None of these objects has any
   109258   ** associated storage, so all we have to do is copy their entries
   109259   ** from the SQLITE_MASTER table.
   109260   */
   109261   rc = execSql(db, pzErrMsg,
   109262       "INSERT INTO vacuum_db.sqlite_master "
   109263       "  SELECT type, name, tbl_name, rootpage, sql"
   109264       "    FROM main.sqlite_master"
   109265       "   WHERE type='view' OR type='trigger'"
   109266       "      OR (type='table' AND rootpage=0)"
   109267   );
   109268   if( rc ) goto end_of_vacuum;
   109269 
   109270   /* At this point, there is a write transaction open on both the
   109271   ** vacuum database and the main database. Assuming no error occurs,
   109272   ** both transactions are closed by this block - the main database
   109273   ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
   109274   ** call to sqlite3BtreeCommit().
   109275   */
   109276   {
   109277     u32 meta;
   109278     int i;
   109279 
   109280     /* This array determines which meta meta values are preserved in the
   109281     ** vacuum.  Even entries are the meta value number and odd entries
   109282     ** are an increment to apply to the meta value after the vacuum.
   109283     ** The increment is used to increase the schema cookie so that other
   109284     ** connections to the same database will know to reread the schema.
   109285     */
   109286     static const unsigned char aCopy[] = {
   109287        BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
   109288        BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
   109289        BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
   109290        BTREE_USER_VERSION,       0,  /* Preserve the user version */
   109291        BTREE_APPLICATION_ID,     0,  /* Preserve the application id */
   109292     };
   109293 
   109294     assert( 1==sqlite3BtreeIsInTrans(pTemp) );
   109295     assert( 1==sqlite3BtreeIsInTrans(pMain) );
   109296 
   109297     /* Copy Btree meta values */
   109298     for(i=0; i<ArraySize(aCopy); i+=2){
   109299       /* GetMeta() and UpdateMeta() cannot fail in this context because
   109300       ** we already have page 1 loaded into cache and marked dirty. */
   109301       sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
   109302       rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
   109303       if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
   109304     }
   109305 
   109306     rc = sqlite3BtreeCopyFile(pMain, pTemp);
   109307     if( rc!=SQLITE_OK ) goto end_of_vacuum;
   109308     rc = sqlite3BtreeCommit(pTemp);
   109309     if( rc!=SQLITE_OK ) goto end_of_vacuum;
   109310 #ifndef SQLITE_OMIT_AUTOVACUUM
   109311     sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
   109312 #endif
   109313   }
   109314 
   109315   assert( rc==SQLITE_OK );
   109316   rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
   109317 
   109318 end_of_vacuum:
   109319   /* Restore the original value of db->flags */
   109320   db->flags = saved_flags;
   109321   db->nChange = saved_nChange;
   109322   db->nTotalChange = saved_nTotalChange;
   109323   db->xTrace = saved_xTrace;
   109324   sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
   109325 
   109326   /* Currently there is an SQL level transaction open on the vacuum
   109327   ** database. No locks are held on any other files (since the main file
   109328   ** was committed at the btree level). So it safe to end the transaction
   109329   ** by manually setting the autoCommit flag to true and detaching the
   109330   ** vacuum database. The vacuum_db journal file is deleted when the pager
   109331   ** is closed by the DETACH.
   109332   */
   109333   db->autoCommit = 1;
   109334 
   109335   if( pDb ){
   109336     sqlite3BtreeClose(pDb->pBt);
   109337     pDb->pBt = 0;
   109338     pDb->pSchema = 0;
   109339   }
   109340 
   109341   /* This both clears the schemas and reduces the size of the db->aDb[]
   109342   ** array. */
   109343   sqlite3ResetAllSchemasOfConnection(db);
   109344 
   109345   return rc;
   109346 }
   109347 
   109348 #endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
   109349 
   109350 /************** End of vacuum.c **********************************************/
   109351 /************** Begin file vtab.c ********************************************/
   109352 /*
   109353 ** 2006 June 10
   109354 **
   109355 ** The author disclaims copyright to this source code.  In place of
   109356 ** a legal notice, here is a blessing:
   109357 **
   109358 **    May you do good and not evil.
   109359 **    May you find forgiveness for yourself and forgive others.
   109360 **    May you share freely, never taking more than you give.
   109361 **
   109362 *************************************************************************
   109363 ** This file contains code used to help implement virtual tables.
   109364 */
   109365 #ifndef SQLITE_OMIT_VIRTUALTABLE
   109366 
   109367 /*
   109368 ** Before a virtual table xCreate() or xConnect() method is invoked, the
   109369 ** sqlite3.pVtabCtx member variable is set to point to an instance of
   109370 ** this struct allocated on the stack. It is used by the implementation of
   109371 ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
   109372 ** are invoked only from within xCreate and xConnect methods.
   109373 */
   109374 struct VtabCtx {
   109375   VTable *pVTable;    /* The virtual table being constructed */
   109376   Table *pTab;        /* The Table object to which the virtual table belongs */
   109377 };
   109378 
   109379 /*
   109380 ** The actual function that does the work of creating a new module.
   109381 ** This function implements the sqlite3_create_module() and
   109382 ** sqlite3_create_module_v2() interfaces.
   109383 */
   109384 static int createModule(
   109385   sqlite3 *db,                    /* Database in which module is registered */
   109386   const char *zName,              /* Name assigned to this module */
   109387   const sqlite3_module *pModule,  /* The definition of the module */
   109388   void *pAux,                     /* Context pointer for xCreate/xConnect */
   109389   void (*xDestroy)(void *)        /* Module destructor function */
   109390 ){
   109391   int rc = SQLITE_OK;
   109392   int nName;
   109393 
   109394   sqlite3_mutex_enter(db->mutex);
   109395   nName = sqlite3Strlen30(zName);
   109396   if( sqlite3HashFind(&db->aModule, zName, nName) ){
   109397     rc = SQLITE_MISUSE_BKPT;
   109398   }else{
   109399     Module *pMod;
   109400     pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
   109401     if( pMod ){
   109402       Module *pDel;
   109403       char *zCopy = (char *)(&pMod[1]);
   109404       memcpy(zCopy, zName, nName+1);
   109405       pMod->zName = zCopy;
   109406       pMod->pModule = pModule;
   109407       pMod->pAux = pAux;
   109408       pMod->xDestroy = xDestroy;
   109409       pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,nName,(void*)pMod);
   109410       assert( pDel==0 || pDel==pMod );
   109411       if( pDel ){
   109412         db->mallocFailed = 1;
   109413         sqlite3DbFree(db, pDel);
   109414       }
   109415     }
   109416   }
   109417   rc = sqlite3ApiExit(db, rc);
   109418   if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
   109419 
   109420   sqlite3_mutex_leave(db->mutex);
   109421   return rc;
   109422 }
   109423 
   109424 
   109425 /*
   109426 ** External API function used to create a new virtual-table module.
   109427 */
   109428 SQLITE_API int sqlite3_create_module(
   109429   sqlite3 *db,                    /* Database in which module is registered */
   109430   const char *zName,              /* Name assigned to this module */
   109431   const sqlite3_module *pModule,  /* The definition of the module */
   109432   void *pAux                      /* Context pointer for xCreate/xConnect */
   109433 ){
   109434   return createModule(db, zName, pModule, pAux, 0);
   109435 }
   109436 
   109437 /*
   109438 ** External API function used to create a new virtual-table module.
   109439 */
   109440 SQLITE_API int sqlite3_create_module_v2(
   109441   sqlite3 *db,                    /* Database in which module is registered */
   109442   const char *zName,              /* Name assigned to this module */
   109443   const sqlite3_module *pModule,  /* The definition of the module */
   109444   void *pAux,                     /* Context pointer for xCreate/xConnect */
   109445   void (*xDestroy)(void *)        /* Module destructor function */
   109446 ){
   109447   return createModule(db, zName, pModule, pAux, xDestroy);
   109448 }
   109449 
   109450 /*
   109451 ** Lock the virtual table so that it cannot be disconnected.
   109452 ** Locks nest.  Every lock should have a corresponding unlock.
   109453 ** If an unlock is omitted, resources leaks will occur.
   109454 **
   109455 ** If a disconnect is attempted while a virtual table is locked,
   109456 ** the disconnect is deferred until all locks have been removed.
   109457 */
   109458 SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
   109459   pVTab->nRef++;
   109460 }
   109461 
   109462 
   109463 /*
   109464 ** pTab is a pointer to a Table structure representing a virtual-table.
   109465 ** Return a pointer to the VTable object used by connection db to access
   109466 ** this virtual-table, if one has been created, or NULL otherwise.
   109467 */
   109468 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
   109469   VTable *pVtab;
   109470   assert( IsVirtual(pTab) );
   109471   for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
   109472   return pVtab;
   109473 }
   109474 
   109475 /*
   109476 ** Decrement the ref-count on a virtual table object. When the ref-count
   109477 ** reaches zero, call the xDisconnect() method to delete the object.
   109478 */
   109479 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
   109480   sqlite3 *db = pVTab->db;
   109481 
   109482   assert( db );
   109483   assert( pVTab->nRef>0 );
   109484   assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
   109485 
   109486   pVTab->nRef--;
   109487   if( pVTab->nRef==0 ){
   109488     sqlite3_vtab *p = pVTab->pVtab;
   109489     if( p ){
   109490       p->pModule->xDisconnect(p);
   109491     }
   109492     sqlite3DbFree(db, pVTab);
   109493   }
   109494 }
   109495 
   109496 /*
   109497 ** Table p is a virtual table. This function moves all elements in the
   109498 ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
   109499 ** database connections to be disconnected at the next opportunity.
   109500 ** Except, if argument db is not NULL, then the entry associated with
   109501 ** connection db is left in the p->pVTable list.
   109502 */
   109503 static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
   109504   VTable *pRet = 0;
   109505   VTable *pVTable = p->pVTable;
   109506   p->pVTable = 0;
   109507 
   109508   /* Assert that the mutex (if any) associated with the BtShared database
   109509   ** that contains table p is held by the caller. See header comments
   109510   ** above function sqlite3VtabUnlockList() for an explanation of why
   109511   ** this makes it safe to access the sqlite3.pDisconnect list of any
   109512   ** database connection that may have an entry in the p->pVTable list.
   109513   */
   109514   assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
   109515 
   109516   while( pVTable ){
   109517     sqlite3 *db2 = pVTable->db;
   109518     VTable *pNext = pVTable->pNext;
   109519     assert( db2 );
   109520     if( db2==db ){
   109521       pRet = pVTable;
   109522       p->pVTable = pRet;
   109523       pRet->pNext = 0;
   109524     }else{
   109525       pVTable->pNext = db2->pDisconnect;
   109526       db2->pDisconnect = pVTable;
   109527     }
   109528     pVTable = pNext;
   109529   }
   109530 
   109531   assert( !db || pRet );
   109532   return pRet;
   109533 }
   109534 
   109535 /*
   109536 ** Table *p is a virtual table. This function removes the VTable object
   109537 ** for table *p associated with database connection db from the linked
   109538 ** list in p->pVTab. It also decrements the VTable ref count. This is
   109539 ** used when closing database connection db to free all of its VTable
   109540 ** objects without disturbing the rest of the Schema object (which may
   109541 ** be being used by other shared-cache connections).
   109542 */
   109543 SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
   109544   VTable **ppVTab;
   109545 
   109546   assert( IsVirtual(p) );
   109547   assert( sqlite3BtreeHoldsAllMutexes(db) );
   109548   assert( sqlite3_mutex_held(db->mutex) );
   109549 
   109550   for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
   109551     if( (*ppVTab)->db==db  ){
   109552       VTable *pVTab = *ppVTab;
   109553       *ppVTab = pVTab->pNext;
   109554       sqlite3VtabUnlock(pVTab);
   109555       break;
   109556     }
   109557   }
   109558 }
   109559 
   109560 
   109561 /*
   109562 ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
   109563 **
   109564 ** This function may only be called when the mutexes associated with all
   109565 ** shared b-tree databases opened using connection db are held by the
   109566 ** caller. This is done to protect the sqlite3.pDisconnect list. The
   109567 ** sqlite3.pDisconnect list is accessed only as follows:
   109568 **
   109569 **   1) By this function. In this case, all BtShared mutexes and the mutex
   109570 **      associated with the database handle itself must be held.
   109571 **
   109572 **   2) By function vtabDisconnectAll(), when it adds a VTable entry to
   109573 **      the sqlite3.pDisconnect list. In this case either the BtShared mutex
   109574 **      associated with the database the virtual table is stored in is held
   109575 **      or, if the virtual table is stored in a non-sharable database, then
   109576 **      the database handle mutex is held.
   109577 **
   109578 ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
   109579 ** by multiple threads. It is thread-safe.
   109580 */
   109581 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
   109582   VTable *p = db->pDisconnect;
   109583   db->pDisconnect = 0;
   109584 
   109585   assert( sqlite3BtreeHoldsAllMutexes(db) );
   109586   assert( sqlite3_mutex_held(db->mutex) );
   109587 
   109588   if( p ){
   109589     sqlite3ExpirePreparedStatements(db);
   109590     do {
   109591       VTable *pNext = p->pNext;
   109592       sqlite3VtabUnlock(p);
   109593       p = pNext;
   109594     }while( p );
   109595   }
   109596 }
   109597 
   109598 /*
   109599 ** Clear any and all virtual-table information from the Table record.
   109600 ** This routine is called, for example, just before deleting the Table
   109601 ** record.
   109602 **
   109603 ** Since it is a virtual-table, the Table structure contains a pointer
   109604 ** to the head of a linked list of VTable structures. Each VTable
   109605 ** structure is associated with a single sqlite3* user of the schema.
   109606 ** The reference count of the VTable structure associated with database
   109607 ** connection db is decremented immediately (which may lead to the
   109608 ** structure being xDisconnected and free). Any other VTable structures
   109609 ** in the list are moved to the sqlite3.pDisconnect list of the associated
   109610 ** database connection.
   109611 */
   109612 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
   109613   if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
   109614   if( p->azModuleArg ){
   109615     int i;
   109616     for(i=0; i<p->nModuleArg; i++){
   109617       if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
   109618     }
   109619     sqlite3DbFree(db, p->azModuleArg);
   109620   }
   109621 }
   109622 
   109623 /*
   109624 ** Add a new module argument to pTable->azModuleArg[].
   109625 ** The string is not copied - the pointer is stored.  The
   109626 ** string will be freed automatically when the table is
   109627 ** deleted.
   109628 */
   109629 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
   109630   int i = pTable->nModuleArg++;
   109631   int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
   109632   char **azModuleArg;
   109633   azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
   109634   if( azModuleArg==0 ){
   109635     int j;
   109636     for(j=0; j<i; j++){
   109637       sqlite3DbFree(db, pTable->azModuleArg[j]);
   109638     }
   109639     sqlite3DbFree(db, zArg);
   109640     sqlite3DbFree(db, pTable->azModuleArg);
   109641     pTable->nModuleArg = 0;
   109642   }else{
   109643     azModuleArg[i] = zArg;
   109644     azModuleArg[i+1] = 0;
   109645   }
   109646   pTable->azModuleArg = azModuleArg;
   109647 }
   109648 
   109649 /*
   109650 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
   109651 ** statement.  The module name has been parsed, but the optional list
   109652 ** of parameters that follow the module name are still pending.
   109653 */
   109654 SQLITE_PRIVATE void sqlite3VtabBeginParse(
   109655   Parse *pParse,        /* Parsing context */
   109656   Token *pName1,        /* Name of new table, or database name */
   109657   Token *pName2,        /* Name of new table or NULL */
   109658   Token *pModuleName,   /* Name of the module for the virtual table */
   109659   int ifNotExists       /* No error if the table already exists */
   109660 ){
   109661   int iDb;              /* The database the table is being created in */
   109662   Table *pTable;        /* The new virtual table */
   109663   sqlite3 *db;          /* Database connection */
   109664 
   109665   sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
   109666   pTable = pParse->pNewTable;
   109667   if( pTable==0 ) return;
   109668   assert( 0==pTable->pIndex );
   109669 
   109670   db = pParse->db;
   109671   iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
   109672   assert( iDb>=0 );
   109673 
   109674   pTable->tabFlags |= TF_Virtual;
   109675   pTable->nModuleArg = 0;
   109676   addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
   109677   addModuleArgument(db, pTable, 0);
   109678   addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
   109679   pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
   109680 
   109681 #ifndef SQLITE_OMIT_AUTHORIZATION
   109682   /* Creating a virtual table invokes the authorization callback twice.
   109683   ** The first invocation, to obtain permission to INSERT a row into the
   109684   ** sqlite_master table, has already been made by sqlite3StartTable().
   109685   ** The second call, to obtain permission to create the table, is made now.
   109686   */
   109687   if( pTable->azModuleArg ){
   109688     sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
   109689             pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
   109690   }
   109691 #endif
   109692 }
   109693 
   109694 /*
   109695 ** This routine takes the module argument that has been accumulating
   109696 ** in pParse->zArg[] and appends it to the list of arguments on the
   109697 ** virtual table currently under construction in pParse->pTable.
   109698 */
   109699 static void addArgumentToVtab(Parse *pParse){
   109700   if( pParse->sArg.z && pParse->pNewTable ){
   109701     const char *z = (const char*)pParse->sArg.z;
   109702     int n = pParse->sArg.n;
   109703     sqlite3 *db = pParse->db;
   109704     addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
   109705   }
   109706 }
   109707 
   109708 /*
   109709 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
   109710 ** has been completely parsed.
   109711 */
   109712 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
   109713   Table *pTab = pParse->pNewTable;  /* The table being constructed */
   109714   sqlite3 *db = pParse->db;         /* The database connection */
   109715 
   109716   if( pTab==0 ) return;
   109717   addArgumentToVtab(pParse);
   109718   pParse->sArg.z = 0;
   109719   if( pTab->nModuleArg<1 ) return;
   109720 
   109721   /* If the CREATE VIRTUAL TABLE statement is being entered for the
   109722   ** first time (in other words if the virtual table is actually being
   109723   ** created now instead of just being read out of sqlite_master) then
   109724   ** do additional initialization work and store the statement text
   109725   ** in the sqlite_master table.
   109726   */
   109727   if( !db->init.busy ){
   109728     char *zStmt;
   109729     char *zWhere;
   109730     int iDb;
   109731     Vdbe *v;
   109732 
   109733     /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
   109734     if( pEnd ){
   109735       pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
   109736     }
   109737     zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
   109738 
   109739     /* A slot for the record has already been allocated in the
   109740     ** SQLITE_MASTER table.  We just need to update that slot with all
   109741     ** the information we've collected.
   109742     **
   109743     ** The VM register number pParse->regRowid holds the rowid of an
   109744     ** entry in the sqlite_master table tht was created for this vtab
   109745     ** by sqlite3StartTable().
   109746     */
   109747     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   109748     sqlite3NestedParse(pParse,
   109749       "UPDATE %Q.%s "
   109750          "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
   109751        "WHERE rowid=#%d",
   109752       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
   109753       pTab->zName,
   109754       pTab->zName,
   109755       zStmt,
   109756       pParse->regRowid
   109757     );
   109758     sqlite3DbFree(db, zStmt);
   109759     v = sqlite3GetVdbe(pParse);
   109760     sqlite3ChangeCookie(pParse, iDb);
   109761 
   109762     sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
   109763     zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
   109764     sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
   109765     sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
   109766                          pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
   109767   }
   109768 
   109769   /* If we are rereading the sqlite_master table create the in-memory
   109770   ** record of the table. The xConnect() method is not called until
   109771   ** the first time the virtual table is used in an SQL statement. This
   109772   ** allows a schema that contains virtual tables to be loaded before
   109773   ** the required virtual table implementations are registered.  */
   109774   else {
   109775     Table *pOld;
   109776     Schema *pSchema = pTab->pSchema;
   109777     const char *zName = pTab->zName;
   109778     int nName = sqlite3Strlen30(zName);
   109779     assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
   109780     pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
   109781     if( pOld ){
   109782       db->mallocFailed = 1;
   109783       assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
   109784       return;
   109785     }
   109786     pParse->pNewTable = 0;
   109787   }
   109788 }
   109789 
   109790 /*
   109791 ** The parser calls this routine when it sees the first token
   109792 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
   109793 */
   109794 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
   109795   addArgumentToVtab(pParse);
   109796   pParse->sArg.z = 0;
   109797   pParse->sArg.n = 0;
   109798 }
   109799 
   109800 /*
   109801 ** The parser calls this routine for each token after the first token
   109802 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
   109803 */
   109804 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
   109805   Token *pArg = &pParse->sArg;
   109806   if( pArg->z==0 ){
   109807     pArg->z = p->z;
   109808     pArg->n = p->n;
   109809   }else{
   109810     assert(pArg->z < p->z);
   109811     pArg->n = (int)(&p->z[p->n] - pArg->z);
   109812   }
   109813 }
   109814 
   109815 /*
   109816 ** Invoke a virtual table constructor (either xCreate or xConnect). The
   109817 ** pointer to the function to invoke is passed as the fourth parameter
   109818 ** to this procedure.
   109819 */
   109820 static int vtabCallConstructor(
   109821   sqlite3 *db,
   109822   Table *pTab,
   109823   Module *pMod,
   109824   int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
   109825   char **pzErr
   109826 ){
   109827   VtabCtx sCtx, *pPriorCtx;
   109828   VTable *pVTable;
   109829   int rc;
   109830   const char *const*azArg = (const char *const*)pTab->azModuleArg;
   109831   int nArg = pTab->nModuleArg;
   109832   char *zErr = 0;
   109833   char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
   109834   int iDb;
   109835 
   109836   if( !zModuleName ){
   109837     return SQLITE_NOMEM;
   109838   }
   109839 
   109840   pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
   109841   if( !pVTable ){
   109842     sqlite3DbFree(db, zModuleName);
   109843     return SQLITE_NOMEM;
   109844   }
   109845   pVTable->db = db;
   109846   pVTable->pMod = pMod;
   109847 
   109848   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   109849   pTab->azModuleArg[1] = db->aDb[iDb].zName;
   109850 
   109851   /* Invoke the virtual table constructor */
   109852   assert( &db->pVtabCtx );
   109853   assert( xConstruct );
   109854   sCtx.pTab = pTab;
   109855   sCtx.pVTable = pVTable;
   109856   pPriorCtx = db->pVtabCtx;
   109857   db->pVtabCtx = &sCtx;
   109858   rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
   109859   db->pVtabCtx = pPriorCtx;
   109860   if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
   109861 
   109862   if( SQLITE_OK!=rc ){
   109863     if( zErr==0 ){
   109864       *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
   109865     }else {
   109866       *pzErr = sqlite3MPrintf(db, "%s", zErr);
   109867       sqlite3_free(zErr);
   109868     }
   109869     sqlite3DbFree(db, pVTable);
   109870   }else if( ALWAYS(pVTable->pVtab) ){
   109871     /* Justification of ALWAYS():  A correct vtab constructor must allocate
   109872     ** the sqlite3_vtab object if successful.  */
   109873     pVTable->pVtab->pModule = pMod->pModule;
   109874     pVTable->nRef = 1;
   109875     if( sCtx.pTab ){
   109876       const char *zFormat = "vtable constructor did not declare schema: %s";
   109877       *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
   109878       sqlite3VtabUnlock(pVTable);
   109879       rc = SQLITE_ERROR;
   109880     }else{
   109881       int iCol;
   109882       /* If everything went according to plan, link the new VTable structure
   109883       ** into the linked list headed by pTab->pVTable. Then loop through the
   109884       ** columns of the table to see if any of them contain the token "hidden".
   109885       ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
   109886       ** the type string.  */
   109887       pVTable->pNext = pTab->pVTable;
   109888       pTab->pVTable = pVTable;
   109889 
   109890       for(iCol=0; iCol<pTab->nCol; iCol++){
   109891         char *zType = pTab->aCol[iCol].zType;
   109892         int nType;
   109893         int i = 0;
   109894         if( !zType ) continue;
   109895         nType = sqlite3Strlen30(zType);
   109896         if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
   109897           for(i=0; i<nType; i++){
   109898             if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
   109899              && (zType[i+7]=='\0' || zType[i+7]==' ')
   109900             ){
   109901               i++;
   109902               break;
   109903             }
   109904           }
   109905         }
   109906         if( i<nType ){
   109907           int j;
   109908           int nDel = 6 + (zType[i+6] ? 1 : 0);
   109909           for(j=i; (j+nDel)<=nType; j++){
   109910             zType[j] = zType[j+nDel];
   109911           }
   109912           if( zType[i]=='\0' && i>0 ){
   109913             assert(zType[i-1]==' ');
   109914             zType[i-1] = '\0';
   109915           }
   109916           pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
   109917         }
   109918       }
   109919     }
   109920   }
   109921 
   109922   sqlite3DbFree(db, zModuleName);
   109923   return rc;
   109924 }
   109925 
   109926 /*
   109927 ** This function is invoked by the parser to call the xConnect() method
   109928 ** of the virtual table pTab. If an error occurs, an error code is returned
   109929 ** and an error left in pParse.
   109930 **
   109931 ** This call is a no-op if table pTab is not a virtual table.
   109932 */
   109933 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
   109934   sqlite3 *db = pParse->db;
   109935   const char *zMod;
   109936   Module *pMod;
   109937   int rc;
   109938 
   109939   assert( pTab );
   109940   if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
   109941     return SQLITE_OK;
   109942   }
   109943 
   109944   /* Locate the required virtual table module */
   109945   zMod = pTab->azModuleArg[0];
   109946   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
   109947 
   109948   if( !pMod ){
   109949     const char *zModule = pTab->azModuleArg[0];
   109950     sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
   109951     rc = SQLITE_ERROR;
   109952   }else{
   109953     char *zErr = 0;
   109954     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
   109955     if( rc!=SQLITE_OK ){
   109956       sqlite3ErrorMsg(pParse, "%s", zErr);
   109957     }
   109958     sqlite3DbFree(db, zErr);
   109959   }
   109960 
   109961   return rc;
   109962 }
   109963 /*
   109964 ** Grow the db->aVTrans[] array so that there is room for at least one
   109965 ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
   109966 */
   109967 static int growVTrans(sqlite3 *db){
   109968   const int ARRAY_INCR = 5;
   109969 
   109970   /* Grow the sqlite3.aVTrans array if required */
   109971   if( (db->nVTrans%ARRAY_INCR)==0 ){
   109972     VTable **aVTrans;
   109973     int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
   109974     aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
   109975     if( !aVTrans ){
   109976       return SQLITE_NOMEM;
   109977     }
   109978     memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
   109979     db->aVTrans = aVTrans;
   109980   }
   109981 
   109982   return SQLITE_OK;
   109983 }
   109984 
   109985 /*
   109986 ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
   109987 ** have already been reserved using growVTrans().
   109988 */
   109989 static void addToVTrans(sqlite3 *db, VTable *pVTab){
   109990   /* Add pVtab to the end of sqlite3.aVTrans */
   109991   db->aVTrans[db->nVTrans++] = pVTab;
   109992   sqlite3VtabLock(pVTab);
   109993 }
   109994 
   109995 /*
   109996 ** This function is invoked by the vdbe to call the xCreate method
   109997 ** of the virtual table named zTab in database iDb.
   109998 **
   109999 ** If an error occurs, *pzErr is set to point an an English language
   110000 ** description of the error and an SQLITE_XXX error code is returned.
   110001 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
   110002 */
   110003 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
   110004   int rc = SQLITE_OK;
   110005   Table *pTab;
   110006   Module *pMod;
   110007   const char *zMod;
   110008 
   110009   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
   110010   assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
   110011 
   110012   /* Locate the required virtual table module */
   110013   zMod = pTab->azModuleArg[0];
   110014   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
   110015 
   110016   /* If the module has been registered and includes a Create method,
   110017   ** invoke it now. If the module has not been registered, return an
   110018   ** error. Otherwise, do nothing.
   110019   */
   110020   if( !pMod ){
   110021     *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
   110022     rc = SQLITE_ERROR;
   110023   }else{
   110024     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
   110025   }
   110026 
   110027   /* Justification of ALWAYS():  The xConstructor method is required to
   110028   ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
   110029   if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
   110030     rc = growVTrans(db);
   110031     if( rc==SQLITE_OK ){
   110032       addToVTrans(db, sqlite3GetVTable(db, pTab));
   110033     }
   110034   }
   110035 
   110036   return rc;
   110037 }
   110038 
   110039 /*
   110040 ** This function is used to set the schema of a virtual table.  It is only
   110041 ** valid to call this function from within the xCreate() or xConnect() of a
   110042 ** virtual table module.
   110043 */
   110044 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
   110045   Parse *pParse;
   110046 
   110047   int rc = SQLITE_OK;
   110048   Table *pTab;
   110049   char *zErr = 0;
   110050 
   110051   sqlite3_mutex_enter(db->mutex);
   110052   if( !db->pVtabCtx || !(pTab = db->pVtabCtx->pTab) ){
   110053     sqlite3Error(db, SQLITE_MISUSE, 0);
   110054     sqlite3_mutex_leave(db->mutex);
   110055     return SQLITE_MISUSE_BKPT;
   110056   }
   110057   assert( (pTab->tabFlags & TF_Virtual)!=0 );
   110058 
   110059   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
   110060   if( pParse==0 ){
   110061     rc = SQLITE_NOMEM;
   110062   }else{
   110063     pParse->declareVtab = 1;
   110064     pParse->db = db;
   110065     pParse->nQueryLoop = 1;
   110066 
   110067     if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
   110068      && pParse->pNewTable
   110069      && !db->mallocFailed
   110070      && !pParse->pNewTable->pSelect
   110071      && (pParse->pNewTable->tabFlags & TF_Virtual)==0
   110072     ){
   110073       if( !pTab->aCol ){
   110074         pTab->aCol = pParse->pNewTable->aCol;
   110075         pTab->nCol = pParse->pNewTable->nCol;
   110076         pParse->pNewTable->nCol = 0;
   110077         pParse->pNewTable->aCol = 0;
   110078       }
   110079       db->pVtabCtx->pTab = 0;
   110080     }else{
   110081       sqlite3Error(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
   110082       sqlite3DbFree(db, zErr);
   110083       rc = SQLITE_ERROR;
   110084     }
   110085     pParse->declareVtab = 0;
   110086 
   110087     if( pParse->pVdbe ){
   110088       sqlite3VdbeFinalize(pParse->pVdbe);
   110089     }
   110090     sqlite3DeleteTable(db, pParse->pNewTable);
   110091     sqlite3ParserReset(pParse);
   110092     sqlite3StackFree(db, pParse);
   110093   }
   110094 
   110095   assert( (rc&0xff)==rc );
   110096   rc = sqlite3ApiExit(db, rc);
   110097   sqlite3_mutex_leave(db->mutex);
   110098   return rc;
   110099 }
   110100 
   110101 /*
   110102 ** This function is invoked by the vdbe to call the xDestroy method
   110103 ** of the virtual table named zTab in database iDb. This occurs
   110104 ** when a DROP TABLE is mentioned.
   110105 **
   110106 ** This call is a no-op if zTab is not a virtual table.
   110107 */
   110108 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
   110109   int rc = SQLITE_OK;
   110110   Table *pTab;
   110111 
   110112   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
   110113   if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
   110114     VTable *p = vtabDisconnectAll(db, pTab);
   110115 
   110116     assert( rc==SQLITE_OK );
   110117     rc = p->pMod->pModule->xDestroy(p->pVtab);
   110118 
   110119     /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
   110120     if( rc==SQLITE_OK ){
   110121       assert( pTab->pVTable==p && p->pNext==0 );
   110122       p->pVtab = 0;
   110123       pTab->pVTable = 0;
   110124       sqlite3VtabUnlock(p);
   110125     }
   110126   }
   110127 
   110128   return rc;
   110129 }
   110130 
   110131 /*
   110132 ** This function invokes either the xRollback or xCommit method
   110133 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
   110134 ** called is identified by the second argument, "offset", which is
   110135 ** the offset of the method to call in the sqlite3_module structure.
   110136 **
   110137 ** The array is cleared after invoking the callbacks.
   110138 */
   110139 static void callFinaliser(sqlite3 *db, int offset){
   110140   int i;
   110141   if( db->aVTrans ){
   110142     for(i=0; i<db->nVTrans; i++){
   110143       VTable *pVTab = db->aVTrans[i];
   110144       sqlite3_vtab *p = pVTab->pVtab;
   110145       if( p ){
   110146         int (*x)(sqlite3_vtab *);
   110147         x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
   110148         if( x ) x(p);
   110149       }
   110150       pVTab->iSavepoint = 0;
   110151       sqlite3VtabUnlock(pVTab);
   110152     }
   110153     sqlite3DbFree(db, db->aVTrans);
   110154     db->nVTrans = 0;
   110155     db->aVTrans = 0;
   110156   }
   110157 }
   110158 
   110159 /*
   110160 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
   110161 ** array. Return the error code for the first error that occurs, or
   110162 ** SQLITE_OK if all xSync operations are successful.
   110163 **
   110164 ** If an error message is available, leave it in p->zErrMsg.
   110165 */
   110166 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
   110167   int i;
   110168   int rc = SQLITE_OK;
   110169   VTable **aVTrans = db->aVTrans;
   110170 
   110171   db->aVTrans = 0;
   110172   for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
   110173     int (*x)(sqlite3_vtab *);
   110174     sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
   110175     if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
   110176       rc = x(pVtab);
   110177       sqlite3VtabImportErrmsg(p, pVtab);
   110178     }
   110179   }
   110180   db->aVTrans = aVTrans;
   110181   return rc;
   110182 }
   110183 
   110184 /*
   110185 ** Invoke the xRollback method of all virtual tables in the
   110186 ** sqlite3.aVTrans array. Then clear the array itself.
   110187 */
   110188 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
   110189   callFinaliser(db, offsetof(sqlite3_module,xRollback));
   110190   return SQLITE_OK;
   110191 }
   110192 
   110193 /*
   110194 ** Invoke the xCommit method of all virtual tables in the
   110195 ** sqlite3.aVTrans array. Then clear the array itself.
   110196 */
   110197 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
   110198   callFinaliser(db, offsetof(sqlite3_module,xCommit));
   110199   return SQLITE_OK;
   110200 }
   110201 
   110202 /*
   110203 ** If the virtual table pVtab supports the transaction interface
   110204 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
   110205 ** not currently open, invoke the xBegin method now.
   110206 **
   110207 ** If the xBegin call is successful, place the sqlite3_vtab pointer
   110208 ** in the sqlite3.aVTrans array.
   110209 */
   110210 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
   110211   int rc = SQLITE_OK;
   110212   const sqlite3_module *pModule;
   110213 
   110214   /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
   110215   ** than zero, then this function is being called from within a
   110216   ** virtual module xSync() callback. It is illegal to write to
   110217   ** virtual module tables in this case, so return SQLITE_LOCKED.
   110218   */
   110219   if( sqlite3VtabInSync(db) ){
   110220     return SQLITE_LOCKED;
   110221   }
   110222   if( !pVTab ){
   110223     return SQLITE_OK;
   110224   }
   110225   pModule = pVTab->pVtab->pModule;
   110226 
   110227   if( pModule->xBegin ){
   110228     int i;
   110229 
   110230     /* If pVtab is already in the aVTrans array, return early */
   110231     for(i=0; i<db->nVTrans; i++){
   110232       if( db->aVTrans[i]==pVTab ){
   110233         return SQLITE_OK;
   110234       }
   110235     }
   110236 
   110237     /* Invoke the xBegin method. If successful, add the vtab to the
   110238     ** sqlite3.aVTrans[] array. */
   110239     rc = growVTrans(db);
   110240     if( rc==SQLITE_OK ){
   110241       rc = pModule->xBegin(pVTab->pVtab);
   110242       if( rc==SQLITE_OK ){
   110243         addToVTrans(db, pVTab);
   110244       }
   110245     }
   110246   }
   110247   return rc;
   110248 }
   110249 
   110250 /*
   110251 ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
   110252 ** virtual tables that currently have an open transaction. Pass iSavepoint
   110253 ** as the second argument to the virtual table method invoked.
   110254 **
   110255 ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
   110256 ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
   110257 ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
   110258 ** an open transaction is invoked.
   110259 **
   110260 ** If any virtual table method returns an error code other than SQLITE_OK,
   110261 ** processing is abandoned and the error returned to the caller of this
   110262 ** function immediately. If all calls to virtual table methods are successful,
   110263 ** SQLITE_OK is returned.
   110264 */
   110265 SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
   110266   int rc = SQLITE_OK;
   110267 
   110268   assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
   110269   assert( iSavepoint>=0 );
   110270   if( db->aVTrans ){
   110271     int i;
   110272     for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
   110273       VTable *pVTab = db->aVTrans[i];
   110274       const sqlite3_module *pMod = pVTab->pMod->pModule;
   110275       if( pVTab->pVtab && pMod->iVersion>=2 ){
   110276         int (*xMethod)(sqlite3_vtab *, int);
   110277         switch( op ){
   110278           case SAVEPOINT_BEGIN:
   110279             xMethod = pMod->xSavepoint;
   110280             pVTab->iSavepoint = iSavepoint+1;
   110281             break;
   110282           case SAVEPOINT_ROLLBACK:
   110283             xMethod = pMod->xRollbackTo;
   110284             break;
   110285           default:
   110286             xMethod = pMod->xRelease;
   110287             break;
   110288         }
   110289         if( xMethod && pVTab->iSavepoint>iSavepoint ){
   110290           rc = xMethod(pVTab->pVtab, iSavepoint);
   110291         }
   110292       }
   110293     }
   110294   }
   110295   return rc;
   110296 }
   110297 
   110298 /*
   110299 ** The first parameter (pDef) is a function implementation.  The
   110300 ** second parameter (pExpr) is the first argument to this function.
   110301 ** If pExpr is a column in a virtual table, then let the virtual
   110302 ** table implementation have an opportunity to overload the function.
   110303 **
   110304 ** This routine is used to allow virtual table implementations to
   110305 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
   110306 **
   110307 ** Return either the pDef argument (indicating no change) or a
   110308 ** new FuncDef structure that is marked as ephemeral using the
   110309 ** SQLITE_FUNC_EPHEM flag.
   110310 */
   110311 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
   110312   sqlite3 *db,    /* Database connection for reporting malloc problems */
   110313   FuncDef *pDef,  /* Function to possibly overload */
   110314   int nArg,       /* Number of arguments to the function */
   110315   Expr *pExpr     /* First argument to the function */
   110316 ){
   110317   Table *pTab;
   110318   sqlite3_vtab *pVtab;
   110319   sqlite3_module *pMod;
   110320   void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
   110321   void *pArg = 0;
   110322   FuncDef *pNew;
   110323   int rc = 0;
   110324   char *zLowerName;
   110325   unsigned char *z;
   110326 
   110327 
   110328   /* Check to see the left operand is a column in a virtual table */
   110329   if( NEVER(pExpr==0) ) return pDef;
   110330   if( pExpr->op!=TK_COLUMN ) return pDef;
   110331   pTab = pExpr->pTab;
   110332   if( NEVER(pTab==0) ) return pDef;
   110333   if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
   110334   pVtab = sqlite3GetVTable(db, pTab)->pVtab;
   110335   assert( pVtab!=0 );
   110336   assert( pVtab->pModule!=0 );
   110337   pMod = (sqlite3_module *)pVtab->pModule;
   110338   if( pMod->xFindFunction==0 ) return pDef;
   110339 
   110340   /* Call the xFindFunction method on the virtual table implementation
   110341   ** to see if the implementation wants to overload this function
   110342   */
   110343   zLowerName = sqlite3DbStrDup(db, pDef->zName);
   110344   if( zLowerName ){
   110345     for(z=(unsigned char*)zLowerName; *z; z++){
   110346       *z = sqlite3UpperToLower[*z];
   110347     }
   110348     rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
   110349     sqlite3DbFree(db, zLowerName);
   110350   }
   110351   if( rc==0 ){
   110352     return pDef;
   110353   }
   110354 
   110355   /* Create a new ephemeral function definition for the overloaded
   110356   ** function */
   110357   pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
   110358                              + sqlite3Strlen30(pDef->zName) + 1);
   110359   if( pNew==0 ){
   110360     return pDef;
   110361   }
   110362   *pNew = *pDef;
   110363   pNew->zName = (char *)&pNew[1];
   110364   memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
   110365   pNew->xFunc = xFunc;
   110366   pNew->pUserData = pArg;
   110367   pNew->funcFlags |= SQLITE_FUNC_EPHEM;
   110368   return pNew;
   110369 }
   110370 
   110371 /*
   110372 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
   110373 ** array so that an OP_VBegin will get generated for it.  Add pTab to the
   110374 ** array if it is missing.  If pTab is already in the array, this routine
   110375 ** is a no-op.
   110376 */
   110377 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
   110378   Parse *pToplevel = sqlite3ParseToplevel(pParse);
   110379   int i, n;
   110380   Table **apVtabLock;
   110381 
   110382   assert( IsVirtual(pTab) );
   110383   for(i=0; i<pToplevel->nVtabLock; i++){
   110384     if( pTab==pToplevel->apVtabLock[i] ) return;
   110385   }
   110386   n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
   110387   apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
   110388   if( apVtabLock ){
   110389     pToplevel->apVtabLock = apVtabLock;
   110390     pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
   110391   }else{
   110392     pToplevel->db->mallocFailed = 1;
   110393   }
   110394 }
   110395 
   110396 /*
   110397 ** Return the ON CONFLICT resolution mode in effect for the virtual
   110398 ** table update operation currently in progress.
   110399 **
   110400 ** The results of this routine are undefined unless it is called from
   110401 ** within an xUpdate method.
   110402 */
   110403 SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
   110404   static const unsigned char aMap[] = {
   110405     SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
   110406   };
   110407   assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
   110408   assert( OE_Ignore==4 && OE_Replace==5 );
   110409   assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
   110410   return (int)aMap[db->vtabOnConflict-1];
   110411 }
   110412 
   110413 /*
   110414 ** Call from within the xCreate() or xConnect() methods to provide
   110415 ** the SQLite core with additional information about the behavior
   110416 ** of the virtual table being implemented.
   110417 */
   110418 SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
   110419   va_list ap;
   110420   int rc = SQLITE_OK;
   110421 
   110422   sqlite3_mutex_enter(db->mutex);
   110423 
   110424   va_start(ap, op);
   110425   switch( op ){
   110426     case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
   110427       VtabCtx *p = db->pVtabCtx;
   110428       if( !p ){
   110429         rc = SQLITE_MISUSE_BKPT;
   110430       }else{
   110431         assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
   110432         p->pVTable->bConstraint = (u8)va_arg(ap, int);
   110433       }
   110434       break;
   110435     }
   110436     default:
   110437       rc = SQLITE_MISUSE_BKPT;
   110438       break;
   110439   }
   110440   va_end(ap);
   110441 
   110442   if( rc!=SQLITE_OK ) sqlite3Error(db, rc, 0);
   110443   sqlite3_mutex_leave(db->mutex);
   110444   return rc;
   110445 }
   110446 
   110447 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   110448 
   110449 /************** End of vtab.c ************************************************/
   110450 /************** Begin file where.c *******************************************/
   110451 /*
   110452 ** 2001 September 15
   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 ** This module contains C code that generates VDBE code used to process
   110463 ** the WHERE clause of SQL statements.  This module is responsible for
   110464 ** generating the code that loops through a table looking for applicable
   110465 ** rows.  Indices are selected and used to speed the search when doing
   110466 ** so is applicable.  Because this module is responsible for selecting
   110467 ** indices, you might also think of this module as the "query optimizer".
   110468 */
   110469 /************** Include whereInt.h in the middle of where.c ******************/
   110470 /************** Begin file whereInt.h ****************************************/
   110471 /*
   110472 ** 2013-11-12
   110473 **
   110474 ** The author disclaims copyright to this source code.  In place of
   110475 ** a legal notice, here is a blessing:
   110476 **
   110477 **    May you do good and not evil.
   110478 **    May you find forgiveness for yourself and forgive others.
   110479 **    May you share freely, never taking more than you give.
   110480 **
   110481 *************************************************************************
   110482 **
   110483 ** This file contains structure and macro definitions for the query
   110484 ** planner logic in "where.c".  These definitions are broken out into
   110485 ** a separate source file for easier editing.
   110486 */
   110487 
   110488 /*
   110489 ** Trace output macros
   110490 */
   110491 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
   110492 /***/ int sqlite3WhereTrace = 0;
   110493 #endif
   110494 #if defined(SQLITE_DEBUG) \
   110495     && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
   110496 # define WHERETRACE(K,X)  if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
   110497 # define WHERETRACE_ENABLED 1
   110498 #else
   110499 # define WHERETRACE(K,X)
   110500 #endif
   110501 
   110502 /* Forward references
   110503 */
   110504 typedef struct WhereClause WhereClause;
   110505 typedef struct WhereMaskSet WhereMaskSet;
   110506 typedef struct WhereOrInfo WhereOrInfo;
   110507 typedef struct WhereAndInfo WhereAndInfo;
   110508 typedef struct WhereLevel WhereLevel;
   110509 typedef struct WhereLoop WhereLoop;
   110510 typedef struct WherePath WherePath;
   110511 typedef struct WhereTerm WhereTerm;
   110512 typedef struct WhereLoopBuilder WhereLoopBuilder;
   110513 typedef struct WhereScan WhereScan;
   110514 typedef struct WhereOrCost WhereOrCost;
   110515 typedef struct WhereOrSet WhereOrSet;
   110516 
   110517 /*
   110518 ** This object contains information needed to implement a single nested
   110519 ** loop in WHERE clause.
   110520 **
   110521 ** Contrast this object with WhereLoop.  This object describes the
   110522 ** implementation of the loop.  WhereLoop describes the algorithm.
   110523 ** This object contains a pointer to the WhereLoop algorithm as one of
   110524 ** its elements.
   110525 **
   110526 ** The WhereInfo object contains a single instance of this object for
   110527 ** each term in the FROM clause (which is to say, for each of the
   110528 ** nested loops as implemented).  The order of WhereLevel objects determines
   110529 ** the loop nested order, with WhereInfo.a[0] being the outer loop and
   110530 ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
   110531 */
   110532 struct WhereLevel {
   110533   int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
   110534   int iTabCur;          /* The VDBE cursor used to access the table */
   110535   int iIdxCur;          /* The VDBE cursor used to access pIdx */
   110536   int addrBrk;          /* Jump here to break out of the loop */
   110537   int addrNxt;          /* Jump here to start the next IN combination */
   110538   int addrSkip;         /* Jump here for next iteration of skip-scan */
   110539   int addrCont;         /* Jump here to continue with the next loop cycle */
   110540   int addrFirst;        /* First instruction of interior of the loop */
   110541   int addrBody;         /* Beginning of the body of this loop */
   110542   u8 iFrom;             /* Which entry in the FROM clause */
   110543   u8 op, p3, p5;        /* Opcode, P3 & P5 of the opcode that ends the loop */
   110544   int p1, p2;           /* Operands of the opcode used to ends the loop */
   110545   union {               /* Information that depends on pWLoop->wsFlags */
   110546     struct {
   110547       int nIn;              /* Number of entries in aInLoop[] */
   110548       struct InLoop {
   110549         int iCur;              /* The VDBE cursor used by this IN operator */
   110550         int addrInTop;         /* Top of the IN loop */
   110551         u8 eEndLoopOp;         /* IN Loop terminator. OP_Next or OP_Prev */
   110552       } *aInLoop;           /* Information about each nested IN operator */
   110553     } in;                 /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
   110554     Index *pCovidx;       /* Possible covering index for WHERE_MULTI_OR */
   110555   } u;
   110556   struct WhereLoop *pWLoop;  /* The selected WhereLoop object */
   110557   Bitmask notReady;          /* FROM entries not usable at this level */
   110558 };
   110559 
   110560 /*
   110561 ** Each instance of this object represents an algorithm for evaluating one
   110562 ** term of a join.  Every term of the FROM clause will have at least
   110563 ** one corresponding WhereLoop object (unless INDEXED BY constraints
   110564 ** prevent a query solution - which is an error) and many terms of the
   110565 ** FROM clause will have multiple WhereLoop objects, each describing a
   110566 ** potential way of implementing that FROM-clause term, together with
   110567 ** dependencies and cost estimates for using the chosen algorithm.
   110568 **
   110569 ** Query planning consists of building up a collection of these WhereLoop
   110570 ** objects, then computing a particular sequence of WhereLoop objects, with
   110571 ** one WhereLoop object per FROM clause term, that satisfy all dependencies
   110572 ** and that minimize the overall cost.
   110573 */
   110574 struct WhereLoop {
   110575   Bitmask prereq;       /* Bitmask of other loops that must run first */
   110576   Bitmask maskSelf;     /* Bitmask identifying table iTab */
   110577 #ifdef SQLITE_DEBUG
   110578   char cId;             /* Symbolic ID of this loop for debugging use */
   110579 #endif
   110580   u8 iTab;              /* Position in FROM clause of table for this loop */
   110581   u8 iSortIdx;          /* Sorting index number.  0==None */
   110582   LogEst rSetup;        /* One-time setup cost (ex: create transient index) */
   110583   LogEst rRun;          /* Cost of running each loop */
   110584   LogEst nOut;          /* Estimated number of output rows */
   110585   union {
   110586     struct {               /* Information for internal btree tables */
   110587       u16 nEq;               /* Number of equality constraints */
   110588       u16 nSkip;             /* Number of initial index columns to skip */
   110589       Index *pIndex;         /* Index used, or NULL */
   110590     } btree;
   110591     struct {               /* Information for virtual tables */
   110592       int idxNum;            /* Index number */
   110593       u8 needFree;           /* True if sqlite3_free(idxStr) is needed */
   110594       i8 isOrdered;          /* True if satisfies ORDER BY */
   110595       u16 omitMask;          /* Terms that may be omitted */
   110596       char *idxStr;          /* Index identifier string */
   110597     } vtab;
   110598   } u;
   110599   u32 wsFlags;          /* WHERE_* flags describing the plan */
   110600   u16 nLTerm;           /* Number of entries in aLTerm[] */
   110601   /**** whereLoopXfer() copies fields above ***********************/
   110602 # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
   110603   u16 nLSlot;           /* Number of slots allocated for aLTerm[] */
   110604   WhereTerm **aLTerm;   /* WhereTerms used */
   110605   WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
   110606   WhereTerm *aLTermSpace[4];  /* Initial aLTerm[] space */
   110607 };
   110608 
   110609 /* This object holds the prerequisites and the cost of running a
   110610 ** subquery on one operand of an OR operator in the WHERE clause.
   110611 ** See WhereOrSet for additional information
   110612 */
   110613 struct WhereOrCost {
   110614   Bitmask prereq;     /* Prerequisites */
   110615   LogEst rRun;        /* Cost of running this subquery */
   110616   LogEst nOut;        /* Number of outputs for this subquery */
   110617 };
   110618 
   110619 /* The WhereOrSet object holds a set of possible WhereOrCosts that
   110620 ** correspond to the subquery(s) of OR-clause processing.  Only the
   110621 ** best N_OR_COST elements are retained.
   110622 */
   110623 #define N_OR_COST 3
   110624 struct WhereOrSet {
   110625   u16 n;                      /* Number of valid a[] entries */
   110626   WhereOrCost a[N_OR_COST];   /* Set of best costs */
   110627 };
   110628 
   110629 
   110630 /* Forward declaration of methods */
   110631 static int whereLoopResize(sqlite3*, WhereLoop*, int);
   110632 
   110633 /*
   110634 ** Each instance of this object holds a sequence of WhereLoop objects
   110635 ** that implement some or all of a query plan.
   110636 **
   110637 ** Think of each WhereLoop object as a node in a graph with arcs
   110638 ** showing dependencies and costs for travelling between nodes.  (That is
   110639 ** not a completely accurate description because WhereLoop costs are a
   110640 ** vector, not a scalar, and because dependencies are many-to-one, not
   110641 ** one-to-one as are graph nodes.  But it is a useful visualization aid.)
   110642 ** Then a WherePath object is a path through the graph that visits some
   110643 ** or all of the WhereLoop objects once.
   110644 **
   110645 ** The "solver" works by creating the N best WherePath objects of length
   110646 ** 1.  Then using those as a basis to compute the N best WherePath objects
   110647 ** of length 2.  And so forth until the length of WherePaths equals the
   110648 ** number of nodes in the FROM clause.  The best (lowest cost) WherePath
   110649 ** at the end is the choosen query plan.
   110650 */
   110651 struct WherePath {
   110652   Bitmask maskLoop;     /* Bitmask of all WhereLoop objects in this path */
   110653   Bitmask revLoop;      /* aLoop[]s that should be reversed for ORDER BY */
   110654   LogEst nRow;          /* Estimated number of rows generated by this path */
   110655   LogEst rCost;         /* Total cost of this path */
   110656   LogEst rUnsorted;     /* Total cost of this path ignoring sorting costs */
   110657   i8 isOrdered;         /* No. of ORDER BY terms satisfied. -1 for unknown */
   110658   WhereLoop **aLoop;    /* Array of WhereLoop objects implementing this path */
   110659 };
   110660 
   110661 /*
   110662 ** The query generator uses an array of instances of this structure to
   110663 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
   110664 ** clause subexpression is separated from the others by AND operators,
   110665 ** usually, or sometimes subexpressions separated by OR.
   110666 **
   110667 ** All WhereTerms are collected into a single WhereClause structure.
   110668 ** The following identity holds:
   110669 **
   110670 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
   110671 **
   110672 ** When a term is of the form:
   110673 **
   110674 **              X <op> <expr>
   110675 **
   110676 ** where X is a column name and <op> is one of certain operators,
   110677 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
   110678 ** cursor number and column number for X.  WhereTerm.eOperator records
   110679 ** the <op> using a bitmask encoding defined by WO_xxx below.  The
   110680 ** use of a bitmask encoding for the operator allows us to search
   110681 ** quickly for terms that match any of several different operators.
   110682 **
   110683 ** A WhereTerm might also be two or more subterms connected by OR:
   110684 **
   110685 **         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
   110686 **
   110687 ** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
   110688 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
   110689 ** is collected about the OR clause.
   110690 **
   110691 ** If a term in the WHERE clause does not match either of the two previous
   110692 ** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
   110693 ** to the original subexpression content and wtFlags is set up appropriately
   110694 ** but no other fields in the WhereTerm object are meaningful.
   110695 **
   110696 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
   110697 ** but they do so indirectly.  A single WhereMaskSet structure translates
   110698 ** cursor number into bits and the translated bit is stored in the prereq
   110699 ** fields.  The translation is used in order to maximize the number of
   110700 ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
   110701 ** spread out over the non-negative integers.  For example, the cursor
   110702 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
   110703 ** translates these sparse cursor numbers into consecutive integers
   110704 ** beginning with 0 in order to make the best possible use of the available
   110705 ** bits in the Bitmask.  So, in the example above, the cursor numbers
   110706 ** would be mapped into integers 0 through 7.
   110707 **
   110708 ** The number of terms in a join is limited by the number of bits
   110709 ** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
   110710 ** is only able to process joins with 64 or fewer tables.
   110711 */
   110712 struct WhereTerm {
   110713   Expr *pExpr;            /* Pointer to the subexpression that is this term */
   110714   int iParent;            /* Disable pWC->a[iParent] when this term disabled */
   110715   int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
   110716   union {
   110717     int leftColumn;         /* Column number of X in "X <op> <expr>" */
   110718     WhereOrInfo *pOrInfo;   /* Extra information if (eOperator & WO_OR)!=0 */
   110719     WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
   110720   } u;
   110721   LogEst truthProb;       /* Probability of truth for this expression */
   110722   u16 eOperator;          /* A WO_xx value describing <op> */
   110723   u8 wtFlags;             /* TERM_xxx bit flags.  See below */
   110724   u8 nChild;              /* Number of children that must disable us */
   110725   WhereClause *pWC;       /* The clause this term is part of */
   110726   Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
   110727   Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
   110728 };
   110729 
   110730 /*
   110731 ** Allowed values of WhereTerm.wtFlags
   110732 */
   110733 #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
   110734 #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
   110735 #define TERM_CODED      0x04   /* This term is already coded */
   110736 #define TERM_COPIED     0x08   /* Has a child */
   110737 #define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
   110738 #define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
   110739 #define TERM_OR_OK      0x40   /* Used during OR-clause processing */
   110740 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   110741 #  define TERM_VNULL    0x80   /* Manufactured x>NULL or x<=NULL term */
   110742 #else
   110743 #  define TERM_VNULL    0x00   /* Disabled if not using stat3 */
   110744 #endif
   110745 
   110746 /*
   110747 ** An instance of the WhereScan object is used as an iterator for locating
   110748 ** terms in the WHERE clause that are useful to the query planner.
   110749 */
   110750 struct WhereScan {
   110751   WhereClause *pOrigWC;      /* Original, innermost WhereClause */
   110752   WhereClause *pWC;          /* WhereClause currently being scanned */
   110753   char *zCollName;           /* Required collating sequence, if not NULL */
   110754   char idxaff;               /* Must match this affinity, if zCollName!=NULL */
   110755   unsigned char nEquiv;      /* Number of entries in aEquiv[] */
   110756   unsigned char iEquiv;      /* Next unused slot in aEquiv[] */
   110757   u32 opMask;                /* Acceptable operators */
   110758   int k;                     /* Resume scanning at this->pWC->a[this->k] */
   110759   int aEquiv[22];            /* Cursor,Column pairs for equivalence classes */
   110760 };
   110761 
   110762 /*
   110763 ** An instance of the following structure holds all information about a
   110764 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
   110765 **
   110766 ** Explanation of pOuter:  For a WHERE clause of the form
   110767 **
   110768 **           a AND ((b AND c) OR (d AND e)) AND f
   110769 **
   110770 ** There are separate WhereClause objects for the whole clause and for
   110771 ** the subclauses "(b AND c)" and "(d AND e)".  The pOuter field of the
   110772 ** subclauses points to the WhereClause object for the whole clause.
   110773 */
   110774 struct WhereClause {
   110775   WhereInfo *pWInfo;       /* WHERE clause processing context */
   110776   WhereClause *pOuter;     /* Outer conjunction */
   110777   u8 op;                   /* Split operator.  TK_AND or TK_OR */
   110778   int nTerm;               /* Number of terms */
   110779   int nSlot;               /* Number of entries in a[] */
   110780   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
   110781 #if defined(SQLITE_SMALL_STACK)
   110782   WhereTerm aStatic[1];    /* Initial static space for a[] */
   110783 #else
   110784   WhereTerm aStatic[8];    /* Initial static space for a[] */
   110785 #endif
   110786 };
   110787 
   110788 /*
   110789 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
   110790 ** a dynamically allocated instance of the following structure.
   110791 */
   110792 struct WhereOrInfo {
   110793   WhereClause wc;          /* Decomposition into subterms */
   110794   Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
   110795 };
   110796 
   110797 /*
   110798 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
   110799 ** a dynamically allocated instance of the following structure.
   110800 */
   110801 struct WhereAndInfo {
   110802   WhereClause wc;          /* The subexpression broken out */
   110803 };
   110804 
   110805 /*
   110806 ** An instance of the following structure keeps track of a mapping
   110807 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
   110808 **
   110809 ** The VDBE cursor numbers are small integers contained in
   110810 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE
   110811 ** clause, the cursor numbers might not begin with 0 and they might
   110812 ** contain gaps in the numbering sequence.  But we want to make maximum
   110813 ** use of the bits in our bitmasks.  This structure provides a mapping
   110814 ** from the sparse cursor numbers into consecutive integers beginning
   110815 ** with 0.
   110816 **
   110817 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
   110818 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
   110819 **
   110820 ** For example, if the WHERE clause expression used these VDBE
   110821 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
   110822 ** would map those cursor numbers into bits 0 through 5.
   110823 **
   110824 ** Note that the mapping is not necessarily ordered.  In the example
   110825 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
   110826 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
   110827 ** does not really matter.  What is important is that sparse cursor
   110828 ** numbers all get mapped into bit numbers that begin with 0 and contain
   110829 ** no gaps.
   110830 */
   110831 struct WhereMaskSet {
   110832   int n;                        /* Number of assigned cursor values */
   110833   int ix[BMS];                  /* Cursor assigned to each bit */
   110834 };
   110835 
   110836 /*
   110837 ** This object is a convenience wrapper holding all information needed
   110838 ** to construct WhereLoop objects for a particular query.
   110839 */
   110840 struct WhereLoopBuilder {
   110841   WhereInfo *pWInfo;        /* Information about this WHERE */
   110842   WhereClause *pWC;         /* WHERE clause terms */
   110843   ExprList *pOrderBy;       /* ORDER BY clause */
   110844   WhereLoop *pNew;          /* Template WhereLoop */
   110845   WhereOrSet *pOrSet;       /* Record best loops here, if not NULL */
   110846 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   110847   UnpackedRecord *pRec;     /* Probe for stat4 (if required) */
   110848   int nRecValid;            /* Number of valid fields currently in pRec */
   110849 #endif
   110850 };
   110851 
   110852 /*
   110853 ** The WHERE clause processing routine has two halves.  The
   110854 ** first part does the start of the WHERE loop and the second
   110855 ** half does the tail of the WHERE loop.  An instance of
   110856 ** this structure is returned by the first half and passed
   110857 ** into the second half to give some continuity.
   110858 **
   110859 ** An instance of this object holds the complete state of the query
   110860 ** planner.
   110861 */
   110862 struct WhereInfo {
   110863   Parse *pParse;            /* Parsing and code generating context */
   110864   SrcList *pTabList;        /* List of tables in the join */
   110865   ExprList *pOrderBy;       /* The ORDER BY clause or NULL */
   110866   ExprList *pResultSet;     /* Result set. DISTINCT operates on these */
   110867   WhereLoop *pLoops;        /* List of all WhereLoop objects */
   110868   Bitmask revMask;          /* Mask of ORDER BY terms that need reversing */
   110869   LogEst nRowOut;           /* Estimated number of output rows */
   110870   u16 wctrlFlags;           /* Flags originally passed to sqlite3WhereBegin() */
   110871   i8 nOBSat;                /* Number of ORDER BY terms satisfied by indices */
   110872   u8 sorted;                /* True if really sorted (not just grouped) */
   110873   u8 okOnePass;             /* Ok to use one-pass algorithm for UPDATE/DELETE */
   110874   u8 untestedTerms;         /* Not all WHERE terms resolved by outer loop */
   110875   u8 eDistinct;             /* One of the WHERE_DISTINCT_* values below */
   110876   u8 nLevel;                /* Number of nested loop */
   110877   int iTop;                 /* The very beginning of the WHERE loop */
   110878   int iContinue;            /* Jump here to continue with next record */
   110879   int iBreak;               /* Jump here to break out of the loop */
   110880   int savedNQueryLoop;      /* pParse->nQueryLoop outside the WHERE loop */
   110881   int aiCurOnePass[2];      /* OP_OpenWrite cursors for the ONEPASS opt */
   110882   WhereMaskSet sMaskSet;    /* Map cursor numbers to bitmasks */
   110883   WhereClause sWC;          /* Decomposition of the WHERE clause */
   110884   WhereLevel a[1];          /* Information about each nest loop in WHERE */
   110885 };
   110886 
   110887 /*
   110888 ** Bitmasks for the operators on WhereTerm objects.  These are all
   110889 ** operators that are of interest to the query planner.  An
   110890 ** OR-ed combination of these values can be used when searching for
   110891 ** particular WhereTerms within a WhereClause.
   110892 */
   110893 #define WO_IN     0x001
   110894 #define WO_EQ     0x002
   110895 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
   110896 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
   110897 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
   110898 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
   110899 #define WO_MATCH  0x040
   110900 #define WO_ISNULL 0x080
   110901 #define WO_OR     0x100       /* Two or more OR-connected terms */
   110902 #define WO_AND    0x200       /* Two or more AND-connected terms */
   110903 #define WO_EQUIV  0x400       /* Of the form A==B, both columns */
   110904 #define WO_NOOP   0x800       /* This term does not restrict search space */
   110905 
   110906 #define WO_ALL    0xfff       /* Mask of all possible WO_* values */
   110907 #define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
   110908 
   110909 /*
   110910 ** These are definitions of bits in the WhereLoop.wsFlags field.
   110911 ** The particular combination of bits in each WhereLoop help to
   110912 ** determine the algorithm that WhereLoop represents.
   110913 */
   110914 #define WHERE_COLUMN_EQ    0x00000001  /* x=EXPR */
   110915 #define WHERE_COLUMN_RANGE 0x00000002  /* x<EXPR and/or x>EXPR */
   110916 #define WHERE_COLUMN_IN    0x00000004  /* x IN (...) */
   110917 #define WHERE_COLUMN_NULL  0x00000008  /* x IS NULL */
   110918 #define WHERE_CONSTRAINT   0x0000000f  /* Any of the WHERE_COLUMN_xxx values */
   110919 #define WHERE_TOP_LIMIT    0x00000010  /* x<EXPR or x<=EXPR constraint */
   110920 #define WHERE_BTM_LIMIT    0x00000020  /* x>EXPR or x>=EXPR constraint */
   110921 #define WHERE_BOTH_LIMIT   0x00000030  /* Both x>EXPR and x<EXPR */
   110922 #define WHERE_IDX_ONLY     0x00000040  /* Use index only - omit table */
   110923 #define WHERE_IPK          0x00000100  /* x is the INTEGER PRIMARY KEY */
   110924 #define WHERE_INDEXED      0x00000200  /* WhereLoop.u.btree.pIndex is valid */
   110925 #define WHERE_VIRTUALTABLE 0x00000400  /* WhereLoop.u.vtab is valid */
   110926 #define WHERE_IN_ABLE      0x00000800  /* Able to support an IN operator */
   110927 #define WHERE_ONEROW       0x00001000  /* Selects no more than one row */
   110928 #define WHERE_MULTI_OR     0x00002000  /* OR using multiple indices */
   110929 #define WHERE_AUTO_INDEX   0x00004000  /* Uses an ephemeral index */
   110930 #define WHERE_SKIPSCAN     0x00008000  /* Uses the skip-scan algorithm */
   110931 #define WHERE_UNQ_WANTED   0x00010000  /* WHERE_ONEROW would have been helpful*/
   110932 
   110933 /************** End of whereInt.h ********************************************/
   110934 /************** Continuing where we left off in where.c **********************/
   110935 
   110936 /*
   110937 ** Return the estimated number of output rows from a WHERE clause
   110938 */
   110939 SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
   110940   return sqlite3LogEstToInt(pWInfo->nRowOut);
   110941 }
   110942 
   110943 /*
   110944 ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
   110945 ** WHERE clause returns outputs for DISTINCT processing.
   110946 */
   110947 SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
   110948   return pWInfo->eDistinct;
   110949 }
   110950 
   110951 /*
   110952 ** Return TRUE if the WHERE clause returns rows in ORDER BY order.
   110953 ** Return FALSE if the output needs to be sorted.
   110954 */
   110955 SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
   110956   return pWInfo->nOBSat;
   110957 }
   110958 
   110959 /*
   110960 ** Return the VDBE address or label to jump to in order to continue
   110961 ** immediately with the next row of a WHERE clause.
   110962 */
   110963 SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
   110964   assert( pWInfo->iContinue!=0 );
   110965   return pWInfo->iContinue;
   110966 }
   110967 
   110968 /*
   110969 ** Return the VDBE address or label to jump to in order to break
   110970 ** out of a WHERE loop.
   110971 */
   110972 SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
   110973   return pWInfo->iBreak;
   110974 }
   110975 
   110976 /*
   110977 ** Return TRUE if an UPDATE or DELETE statement can operate directly on
   110978 ** the rowids returned by a WHERE clause.  Return FALSE if doing an
   110979 ** UPDATE or DELETE might change subsequent WHERE clause results.
   110980 **
   110981 ** If the ONEPASS optimization is used (if this routine returns true)
   110982 ** then also write the indices of open cursors used by ONEPASS
   110983 ** into aiCur[0] and aiCur[1].  iaCur[0] gets the cursor of the data
   110984 ** table and iaCur[1] gets the cursor used by an auxiliary index.
   110985 ** Either value may be -1, indicating that cursor is not used.
   110986 ** Any cursors returned will have been opened for writing.
   110987 **
   110988 ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
   110989 ** unable to use the ONEPASS optimization.
   110990 */
   110991 SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
   110992   memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
   110993   return pWInfo->okOnePass;
   110994 }
   110995 
   110996 /*
   110997 ** Move the content of pSrc into pDest
   110998 */
   110999 static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
   111000   pDest->n = pSrc->n;
   111001   memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
   111002 }
   111003 
   111004 /*
   111005 ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
   111006 **
   111007 ** The new entry might overwrite an existing entry, or it might be
   111008 ** appended, or it might be discarded.  Do whatever is the right thing
   111009 ** so that pSet keeps the N_OR_COST best entries seen so far.
   111010 */
   111011 static int whereOrInsert(
   111012   WhereOrSet *pSet,      /* The WhereOrSet to be updated */
   111013   Bitmask prereq,        /* Prerequisites of the new entry */
   111014   LogEst rRun,           /* Run-cost of the new entry */
   111015   LogEst nOut            /* Number of outputs for the new entry */
   111016 ){
   111017   u16 i;
   111018   WhereOrCost *p;
   111019   for(i=pSet->n, p=pSet->a; i>0; i--, p++){
   111020     if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
   111021       goto whereOrInsert_done;
   111022     }
   111023     if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
   111024       return 0;
   111025     }
   111026   }
   111027   if( pSet->n<N_OR_COST ){
   111028     p = &pSet->a[pSet->n++];
   111029     p->nOut = nOut;
   111030   }else{
   111031     p = pSet->a;
   111032     for(i=1; i<pSet->n; i++){
   111033       if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
   111034     }
   111035     if( p->rRun<=rRun ) return 0;
   111036   }
   111037 whereOrInsert_done:
   111038   p->prereq = prereq;
   111039   p->rRun = rRun;
   111040   if( p->nOut>nOut ) p->nOut = nOut;
   111041   return 1;
   111042 }
   111043 
   111044 /*
   111045 ** Initialize a preallocated WhereClause structure.
   111046 */
   111047 static void whereClauseInit(
   111048   WhereClause *pWC,        /* The WhereClause to be initialized */
   111049   WhereInfo *pWInfo        /* The WHERE processing context */
   111050 ){
   111051   pWC->pWInfo = pWInfo;
   111052   pWC->pOuter = 0;
   111053   pWC->nTerm = 0;
   111054   pWC->nSlot = ArraySize(pWC->aStatic);
   111055   pWC->a = pWC->aStatic;
   111056 }
   111057 
   111058 /* Forward reference */
   111059 static void whereClauseClear(WhereClause*);
   111060 
   111061 /*
   111062 ** Deallocate all memory associated with a WhereOrInfo object.
   111063 */
   111064 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
   111065   whereClauseClear(&p->wc);
   111066   sqlite3DbFree(db, p);
   111067 }
   111068 
   111069 /*
   111070 ** Deallocate all memory associated with a WhereAndInfo object.
   111071 */
   111072 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
   111073   whereClauseClear(&p->wc);
   111074   sqlite3DbFree(db, p);
   111075 }
   111076 
   111077 /*
   111078 ** Deallocate a WhereClause structure.  The WhereClause structure
   111079 ** itself is not freed.  This routine is the inverse of whereClauseInit().
   111080 */
   111081 static void whereClauseClear(WhereClause *pWC){
   111082   int i;
   111083   WhereTerm *a;
   111084   sqlite3 *db = pWC->pWInfo->pParse->db;
   111085   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
   111086     if( a->wtFlags & TERM_DYNAMIC ){
   111087       sqlite3ExprDelete(db, a->pExpr);
   111088     }
   111089     if( a->wtFlags & TERM_ORINFO ){
   111090       whereOrInfoDelete(db, a->u.pOrInfo);
   111091     }else if( a->wtFlags & TERM_ANDINFO ){
   111092       whereAndInfoDelete(db, a->u.pAndInfo);
   111093     }
   111094   }
   111095   if( pWC->a!=pWC->aStatic ){
   111096     sqlite3DbFree(db, pWC->a);
   111097   }
   111098 }
   111099 
   111100 /*
   111101 ** Add a single new WhereTerm entry to the WhereClause object pWC.
   111102 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
   111103 ** The index in pWC->a[] of the new WhereTerm is returned on success.
   111104 ** 0 is returned if the new WhereTerm could not be added due to a memory
   111105 ** allocation error.  The memory allocation failure will be recorded in
   111106 ** the db->mallocFailed flag so that higher-level functions can detect it.
   111107 **
   111108 ** This routine will increase the size of the pWC->a[] array as necessary.
   111109 **
   111110 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
   111111 ** for freeing the expression p is assumed by the WhereClause object pWC.
   111112 ** This is true even if this routine fails to allocate a new WhereTerm.
   111113 **
   111114 ** WARNING:  This routine might reallocate the space used to store
   111115 ** WhereTerms.  All pointers to WhereTerms should be invalidated after
   111116 ** calling this routine.  Such pointers may be reinitialized by referencing
   111117 ** the pWC->a[] array.
   111118 */
   111119 static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
   111120   WhereTerm *pTerm;
   111121   int idx;
   111122   testcase( wtFlags & TERM_VIRTUAL );
   111123   if( pWC->nTerm>=pWC->nSlot ){
   111124     WhereTerm *pOld = pWC->a;
   111125     sqlite3 *db = pWC->pWInfo->pParse->db;
   111126     pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
   111127     if( pWC->a==0 ){
   111128       if( wtFlags & TERM_DYNAMIC ){
   111129         sqlite3ExprDelete(db, p);
   111130       }
   111131       pWC->a = pOld;
   111132       return 0;
   111133     }
   111134     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
   111135     if( pOld!=pWC->aStatic ){
   111136       sqlite3DbFree(db, pOld);
   111137     }
   111138     pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
   111139   }
   111140   pTerm = &pWC->a[idx = pWC->nTerm++];
   111141   if( p && ExprHasProperty(p, EP_Unlikely) ){
   111142     pTerm->truthProb = sqlite3LogEst(p->iTable) - 99;
   111143   }else{
   111144     pTerm->truthProb = 1;
   111145   }
   111146   pTerm->pExpr = sqlite3ExprSkipCollate(p);
   111147   pTerm->wtFlags = wtFlags;
   111148   pTerm->pWC = pWC;
   111149   pTerm->iParent = -1;
   111150   return idx;
   111151 }
   111152 
   111153 /*
   111154 ** This routine identifies subexpressions in the WHERE clause where
   111155 ** each subexpression is separated by the AND operator or some other
   111156 ** operator specified in the op parameter.  The WhereClause structure
   111157 ** is filled with pointers to subexpressions.  For example:
   111158 **
   111159 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
   111160 **           \________/     \_______________/     \________________/
   111161 **            slot[0]            slot[1]               slot[2]
   111162 **
   111163 ** The original WHERE clause in pExpr is unaltered.  All this routine
   111164 ** does is make slot[] entries point to substructure within pExpr.
   111165 **
   111166 ** In the previous sentence and in the diagram, "slot[]" refers to
   111167 ** the WhereClause.a[] array.  The slot[] array grows as needed to contain
   111168 ** all terms of the WHERE clause.
   111169 */
   111170 static void whereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
   111171   pWC->op = op;
   111172   if( pExpr==0 ) return;
   111173   if( pExpr->op!=op ){
   111174     whereClauseInsert(pWC, pExpr, 0);
   111175   }else{
   111176     whereSplit(pWC, pExpr->pLeft, op);
   111177     whereSplit(pWC, pExpr->pRight, op);
   111178   }
   111179 }
   111180 
   111181 /*
   111182 ** Initialize a WhereMaskSet object
   111183 */
   111184 #define initMaskSet(P)  (P)->n=0
   111185 
   111186 /*
   111187 ** Return the bitmask for the given cursor number.  Return 0 if
   111188 ** iCursor is not in the set.
   111189 */
   111190 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
   111191   int i;
   111192   assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
   111193   for(i=0; i<pMaskSet->n; i++){
   111194     if( pMaskSet->ix[i]==iCursor ){
   111195       return MASKBIT(i);
   111196     }
   111197   }
   111198   return 0;
   111199 }
   111200 
   111201 /*
   111202 ** Create a new mask for cursor iCursor.
   111203 **
   111204 ** There is one cursor per table in the FROM clause.  The number of
   111205 ** tables in the FROM clause is limited by a test early in the
   111206 ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
   111207 ** array will never overflow.
   111208 */
   111209 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
   111210   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
   111211   pMaskSet->ix[pMaskSet->n++] = iCursor;
   111212 }
   111213 
   111214 /*
   111215 ** These routines walk (recursively) an expression tree and generate
   111216 ** a bitmask indicating which tables are used in that expression
   111217 ** tree.
   111218 */
   111219 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
   111220 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
   111221 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
   111222   Bitmask mask = 0;
   111223   if( p==0 ) return 0;
   111224   if( p->op==TK_COLUMN ){
   111225     mask = getMask(pMaskSet, p->iTable);
   111226     return mask;
   111227   }
   111228   mask = exprTableUsage(pMaskSet, p->pRight);
   111229   mask |= exprTableUsage(pMaskSet, p->pLeft);
   111230   if( ExprHasProperty(p, EP_xIsSelect) ){
   111231     mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
   111232   }else{
   111233     mask |= exprListTableUsage(pMaskSet, p->x.pList);
   111234   }
   111235   return mask;
   111236 }
   111237 static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
   111238   int i;
   111239   Bitmask mask = 0;
   111240   if( pList ){
   111241     for(i=0; i<pList->nExpr; i++){
   111242       mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
   111243     }
   111244   }
   111245   return mask;
   111246 }
   111247 static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
   111248   Bitmask mask = 0;
   111249   while( pS ){
   111250     SrcList *pSrc = pS->pSrc;
   111251     mask |= exprListTableUsage(pMaskSet, pS->pEList);
   111252     mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
   111253     mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
   111254     mask |= exprTableUsage(pMaskSet, pS->pWhere);
   111255     mask |= exprTableUsage(pMaskSet, pS->pHaving);
   111256     if( ALWAYS(pSrc!=0) ){
   111257       int i;
   111258       for(i=0; i<pSrc->nSrc; i++){
   111259         mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
   111260         mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
   111261       }
   111262     }
   111263     pS = pS->pPrior;
   111264   }
   111265   return mask;
   111266 }
   111267 
   111268 /*
   111269 ** Return TRUE if the given operator is one of the operators that is
   111270 ** allowed for an indexable WHERE clause term.  The allowed operators are
   111271 ** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
   111272 */
   111273 static int allowedOp(int op){
   111274   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
   111275   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
   111276   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
   111277   assert( TK_GE==TK_EQ+4 );
   111278   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
   111279 }
   111280 
   111281 /*
   111282 ** Swap two objects of type TYPE.
   111283 */
   111284 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
   111285 
   111286 /*
   111287 ** Commute a comparison operator.  Expressions of the form "X op Y"
   111288 ** are converted into "Y op X".
   111289 **
   111290 ** If left/right precedence rules come into play when determining the
   111291 ** collating sequence, then COLLATE operators are adjusted to ensure
   111292 ** that the collating sequence does not change.  For example:
   111293 ** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
   111294 ** the left hand side of a comparison overrides any collation sequence
   111295 ** attached to the right. For the same reason the EP_Collate flag
   111296 ** is not commuted.
   111297 */
   111298 static void exprCommute(Parse *pParse, Expr *pExpr){
   111299   u16 expRight = (pExpr->pRight->flags & EP_Collate);
   111300   u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
   111301   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
   111302   if( expRight==expLeft ){
   111303     /* Either X and Y both have COLLATE operator or neither do */
   111304     if( expRight ){
   111305       /* Both X and Y have COLLATE operators.  Make sure X is always
   111306       ** used by clearing the EP_Collate flag from Y. */
   111307       pExpr->pRight->flags &= ~EP_Collate;
   111308     }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
   111309       /* Neither X nor Y have COLLATE operators, but X has a non-default
   111310       ** collating sequence.  So add the EP_Collate marker on X to cause
   111311       ** it to be searched first. */
   111312       pExpr->pLeft->flags |= EP_Collate;
   111313     }
   111314   }
   111315   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
   111316   if( pExpr->op>=TK_GT ){
   111317     assert( TK_LT==TK_GT+2 );
   111318     assert( TK_GE==TK_LE+2 );
   111319     assert( TK_GT>TK_EQ );
   111320     assert( TK_GT<TK_LE );
   111321     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
   111322     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
   111323   }
   111324 }
   111325 
   111326 /*
   111327 ** Translate from TK_xx operator to WO_xx bitmask.
   111328 */
   111329 static u16 operatorMask(int op){
   111330   u16 c;
   111331   assert( allowedOp(op) );
   111332   if( op==TK_IN ){
   111333     c = WO_IN;
   111334   }else if( op==TK_ISNULL ){
   111335     c = WO_ISNULL;
   111336   }else{
   111337     assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
   111338     c = (u16)(WO_EQ<<(op-TK_EQ));
   111339   }
   111340   assert( op!=TK_ISNULL || c==WO_ISNULL );
   111341   assert( op!=TK_IN || c==WO_IN );
   111342   assert( op!=TK_EQ || c==WO_EQ );
   111343   assert( op!=TK_LT || c==WO_LT );
   111344   assert( op!=TK_LE || c==WO_LE );
   111345   assert( op!=TK_GT || c==WO_GT );
   111346   assert( op!=TK_GE || c==WO_GE );
   111347   return c;
   111348 }
   111349 
   111350 /*
   111351 ** Advance to the next WhereTerm that matches according to the criteria
   111352 ** established when the pScan object was initialized by whereScanInit().
   111353 ** Return NULL if there are no more matching WhereTerms.
   111354 */
   111355 static WhereTerm *whereScanNext(WhereScan *pScan){
   111356   int iCur;            /* The cursor on the LHS of the term */
   111357   int iColumn;         /* The column on the LHS of the term.  -1 for IPK */
   111358   Expr *pX;            /* An expression being tested */
   111359   WhereClause *pWC;    /* Shorthand for pScan->pWC */
   111360   WhereTerm *pTerm;    /* The term being tested */
   111361   int k = pScan->k;    /* Where to start scanning */
   111362 
   111363   while( pScan->iEquiv<=pScan->nEquiv ){
   111364     iCur = pScan->aEquiv[pScan->iEquiv-2];
   111365     iColumn = pScan->aEquiv[pScan->iEquiv-1];
   111366     while( (pWC = pScan->pWC)!=0 ){
   111367       for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
   111368         if( pTerm->leftCursor==iCur
   111369          && pTerm->u.leftColumn==iColumn
   111370          && (pScan->iEquiv<=2 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
   111371         ){
   111372           if( (pTerm->eOperator & WO_EQUIV)!=0
   111373            && pScan->nEquiv<ArraySize(pScan->aEquiv)
   111374           ){
   111375             int j;
   111376             pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
   111377             assert( pX->op==TK_COLUMN );
   111378             for(j=0; j<pScan->nEquiv; j+=2){
   111379               if( pScan->aEquiv[j]==pX->iTable
   111380                && pScan->aEquiv[j+1]==pX->iColumn ){
   111381                   break;
   111382               }
   111383             }
   111384             if( j==pScan->nEquiv ){
   111385               pScan->aEquiv[j] = pX->iTable;
   111386               pScan->aEquiv[j+1] = pX->iColumn;
   111387               pScan->nEquiv += 2;
   111388             }
   111389           }
   111390           if( (pTerm->eOperator & pScan->opMask)!=0 ){
   111391             /* Verify the affinity and collating sequence match */
   111392             if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
   111393               CollSeq *pColl;
   111394               Parse *pParse = pWC->pWInfo->pParse;
   111395               pX = pTerm->pExpr;
   111396               if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
   111397                 continue;
   111398               }
   111399               assert(pX->pLeft);
   111400               pColl = sqlite3BinaryCompareCollSeq(pParse,
   111401                                                   pX->pLeft, pX->pRight);
   111402               if( pColl==0 ) pColl = pParse->db->pDfltColl;
   111403               if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
   111404                 continue;
   111405               }
   111406             }
   111407             if( (pTerm->eOperator & WO_EQ)!=0
   111408              && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
   111409              && pX->iTable==pScan->aEquiv[0]
   111410              && pX->iColumn==pScan->aEquiv[1]
   111411             ){
   111412               continue;
   111413             }
   111414             pScan->k = k+1;
   111415             return pTerm;
   111416           }
   111417         }
   111418       }
   111419       pScan->pWC = pScan->pWC->pOuter;
   111420       k = 0;
   111421     }
   111422     pScan->pWC = pScan->pOrigWC;
   111423     k = 0;
   111424     pScan->iEquiv += 2;
   111425   }
   111426   return 0;
   111427 }
   111428 
   111429 /*
   111430 ** Initialize a WHERE clause scanner object.  Return a pointer to the
   111431 ** first match.  Return NULL if there are no matches.
   111432 **
   111433 ** The scanner will be searching the WHERE clause pWC.  It will look
   111434 ** for terms of the form "X <op> <expr>" where X is column iColumn of table
   111435 ** iCur.  The <op> must be one of the operators described by opMask.
   111436 **
   111437 ** If the search is for X and the WHERE clause contains terms of the
   111438 ** form X=Y then this routine might also return terms of the form
   111439 ** "Y <op> <expr>".  The number of levels of transitivity is limited,
   111440 ** but is enough to handle most commonly occurring SQL statements.
   111441 **
   111442 ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
   111443 ** index pIdx.
   111444 */
   111445 static WhereTerm *whereScanInit(
   111446   WhereScan *pScan,       /* The WhereScan object being initialized */
   111447   WhereClause *pWC,       /* The WHERE clause to be scanned */
   111448   int iCur,               /* Cursor to scan for */
   111449   int iColumn,            /* Column to scan for */
   111450   u32 opMask,             /* Operator(s) to scan for */
   111451   Index *pIdx             /* Must be compatible with this index */
   111452 ){
   111453   int j;
   111454 
   111455   /* memset(pScan, 0, sizeof(*pScan)); */
   111456   pScan->pOrigWC = pWC;
   111457   pScan->pWC = pWC;
   111458   if( pIdx && iColumn>=0 ){
   111459     pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
   111460     for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
   111461       if( NEVER(j>pIdx->nColumn) ) return 0;
   111462     }
   111463     pScan->zCollName = pIdx->azColl[j];
   111464   }else{
   111465     pScan->idxaff = 0;
   111466     pScan->zCollName = 0;
   111467   }
   111468   pScan->opMask = opMask;
   111469   pScan->k = 0;
   111470   pScan->aEquiv[0] = iCur;
   111471   pScan->aEquiv[1] = iColumn;
   111472   pScan->nEquiv = 2;
   111473   pScan->iEquiv = 2;
   111474   return whereScanNext(pScan);
   111475 }
   111476 
   111477 /*
   111478 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
   111479 ** where X is a reference to the iColumn of table iCur and <op> is one of
   111480 ** the WO_xx operator codes specified by the op parameter.
   111481 ** Return a pointer to the term.  Return 0 if not found.
   111482 **
   111483 ** The term returned might by Y=<expr> if there is another constraint in
   111484 ** the WHERE clause that specifies that X=Y.  Any such constraints will be
   111485 ** identified by the WO_EQUIV bit in the pTerm->eOperator field.  The
   111486 ** aEquiv[] array holds X and all its equivalents, with each SQL variable
   111487 ** taking up two slots in aEquiv[].  The first slot is for the cursor number
   111488 ** and the second is for the column number.  There are 22 slots in aEquiv[]
   111489 ** so that means we can look for X plus up to 10 other equivalent values.
   111490 ** Hence a search for X will return <expr> if X=A1 and A1=A2 and A2=A3
   111491 ** and ... and A9=A10 and A10=<expr>.
   111492 **
   111493 ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
   111494 ** then try for the one with no dependencies on <expr> - in other words where
   111495 ** <expr> is a constant expression of some kind.  Only return entries of
   111496 ** the form "X <op> Y" where Y is a column in another table if no terms of
   111497 ** the form "X <op> <const-expr>" exist.   If no terms with a constant RHS
   111498 ** exist, try to return a term that does not use WO_EQUIV.
   111499 */
   111500 static WhereTerm *findTerm(
   111501   WhereClause *pWC,     /* The WHERE clause to be searched */
   111502   int iCur,             /* Cursor number of LHS */
   111503   int iColumn,          /* Column number of LHS */
   111504   Bitmask notReady,     /* RHS must not overlap with this mask */
   111505   u32 op,               /* Mask of WO_xx values describing operator */
   111506   Index *pIdx           /* Must be compatible with this index, if not NULL */
   111507 ){
   111508   WhereTerm *pResult = 0;
   111509   WhereTerm *p;
   111510   WhereScan scan;
   111511 
   111512   p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
   111513   while( p ){
   111514     if( (p->prereqRight & notReady)==0 ){
   111515       if( p->prereqRight==0 && (p->eOperator&WO_EQ)!=0 ){
   111516         return p;
   111517       }
   111518       if( pResult==0 ) pResult = p;
   111519     }
   111520     p = whereScanNext(&scan);
   111521   }
   111522   return pResult;
   111523 }
   111524 
   111525 /* Forward reference */
   111526 static void exprAnalyze(SrcList*, WhereClause*, int);
   111527 
   111528 /*
   111529 ** Call exprAnalyze on all terms in a WHERE clause.
   111530 */
   111531 static void exprAnalyzeAll(
   111532   SrcList *pTabList,       /* the FROM clause */
   111533   WhereClause *pWC         /* the WHERE clause to be analyzed */
   111534 ){
   111535   int i;
   111536   for(i=pWC->nTerm-1; i>=0; i--){
   111537     exprAnalyze(pTabList, pWC, i);
   111538   }
   111539 }
   111540 
   111541 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
   111542 /*
   111543 ** Check to see if the given expression is a LIKE or GLOB operator that
   111544 ** can be optimized using inequality constraints.  Return TRUE if it is
   111545 ** so and false if not.
   111546 **
   111547 ** In order for the operator to be optimizible, the RHS must be a string
   111548 ** literal that does not begin with a wildcard.
   111549 */
   111550 static int isLikeOrGlob(
   111551   Parse *pParse,    /* Parsing and code generating context */
   111552   Expr *pExpr,      /* Test this expression */
   111553   Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
   111554   int *pisComplete, /* True if the only wildcard is % in the last character */
   111555   int *pnoCase      /* True if uppercase is equivalent to lowercase */
   111556 ){
   111557   const char *z = 0;         /* String on RHS of LIKE operator */
   111558   Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
   111559   ExprList *pList;           /* List of operands to the LIKE operator */
   111560   int c;                     /* One character in z[] */
   111561   int cnt;                   /* Number of non-wildcard prefix characters */
   111562   char wc[3];                /* Wildcard characters */
   111563   sqlite3 *db = pParse->db;  /* Database connection */
   111564   sqlite3_value *pVal = 0;
   111565   int op;                    /* Opcode of pRight */
   111566 
   111567   if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
   111568     return 0;
   111569   }
   111570 #ifdef SQLITE_EBCDIC
   111571   if( *pnoCase ) return 0;
   111572 #endif
   111573   pList = pExpr->x.pList;
   111574   pLeft = pList->a[1].pExpr;
   111575   if( pLeft->op!=TK_COLUMN
   111576    || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
   111577    || IsVirtual(pLeft->pTab)
   111578   ){
   111579     /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
   111580     ** be the name of an indexed column with TEXT affinity. */
   111581     return 0;
   111582   }
   111583   assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
   111584 
   111585   pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
   111586   op = pRight->op;
   111587   if( op==TK_VARIABLE ){
   111588     Vdbe *pReprepare = pParse->pReprepare;
   111589     int iCol = pRight->iColumn;
   111590     pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_NONE);
   111591     if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
   111592       z = (char *)sqlite3_value_text(pVal);
   111593     }
   111594     sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
   111595     assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
   111596   }else if( op==TK_STRING ){
   111597     z = pRight->u.zToken;
   111598   }
   111599   if( z ){
   111600     cnt = 0;
   111601     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
   111602       cnt++;
   111603     }
   111604     if( cnt!=0 && 255!=(u8)z[cnt-1] ){
   111605       Expr *pPrefix;
   111606       *pisComplete = c==wc[0] && z[cnt+1]==0;
   111607       pPrefix = sqlite3Expr(db, TK_STRING, z);
   111608       if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
   111609       *ppPrefix = pPrefix;
   111610       if( op==TK_VARIABLE ){
   111611         Vdbe *v = pParse->pVdbe;
   111612         sqlite3VdbeSetVarmask(v, pRight->iColumn);
   111613         if( *pisComplete && pRight->u.zToken[1] ){
   111614           /* If the rhs of the LIKE expression is a variable, and the current
   111615           ** value of the variable means there is no need to invoke the LIKE
   111616           ** function, then no OP_Variable will be added to the program.
   111617           ** This causes problems for the sqlite3_bind_parameter_name()
   111618           ** API. To workaround them, add a dummy OP_Variable here.
   111619           */
   111620           int r1 = sqlite3GetTempReg(pParse);
   111621           sqlite3ExprCodeTarget(pParse, pRight, r1);
   111622           sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
   111623           sqlite3ReleaseTempReg(pParse, r1);
   111624         }
   111625       }
   111626     }else{
   111627       z = 0;
   111628     }
   111629   }
   111630 
   111631   sqlite3ValueFree(pVal);
   111632   return (z!=0);
   111633 }
   111634 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
   111635 
   111636 
   111637 #ifndef SQLITE_OMIT_VIRTUALTABLE
   111638 /*
   111639 ** Check to see if the given expression is of the form
   111640 **
   111641 **         column MATCH expr
   111642 **
   111643 ** If it is then return TRUE.  If not, return FALSE.
   111644 */
   111645 static int isMatchOfColumn(
   111646   Expr *pExpr      /* Test this expression */
   111647 ){
   111648   ExprList *pList;
   111649 
   111650   if( pExpr->op!=TK_FUNCTION ){
   111651     return 0;
   111652   }
   111653   if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
   111654     return 0;
   111655   }
   111656   pList = pExpr->x.pList;
   111657   if( pList->nExpr!=2 ){
   111658     return 0;
   111659   }
   111660   if( pList->a[1].pExpr->op != TK_COLUMN ){
   111661     return 0;
   111662   }
   111663   return 1;
   111664 }
   111665 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   111666 
   111667 /*
   111668 ** If the pBase expression originated in the ON or USING clause of
   111669 ** a join, then transfer the appropriate markings over to derived.
   111670 */
   111671 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
   111672   if( pDerived ){
   111673     pDerived->flags |= pBase->flags & EP_FromJoin;
   111674     pDerived->iRightJoinTable = pBase->iRightJoinTable;
   111675   }
   111676 }
   111677 
   111678 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
   111679 /*
   111680 ** Analyze a term that consists of two or more OR-connected
   111681 ** subterms.  So in:
   111682 **
   111683 **     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
   111684 **                          ^^^^^^^^^^^^^^^^^^^^
   111685 **
   111686 ** This routine analyzes terms such as the middle term in the above example.
   111687 ** A WhereOrTerm object is computed and attached to the term under
   111688 ** analysis, regardless of the outcome of the analysis.  Hence:
   111689 **
   111690 **     WhereTerm.wtFlags   |=  TERM_ORINFO
   111691 **     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
   111692 **
   111693 ** The term being analyzed must have two or more of OR-connected subterms.
   111694 ** A single subterm might be a set of AND-connected sub-subterms.
   111695 ** Examples of terms under analysis:
   111696 **
   111697 **     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
   111698 **     (B)     x=expr1 OR expr2=x OR x=expr3
   111699 **     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
   111700 **     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
   111701 **     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
   111702 **
   111703 ** CASE 1:
   111704 **
   111705 ** If all subterms are of the form T.C=expr for some single column of C and
   111706 ** a single table T (as shown in example B above) then create a new virtual
   111707 ** term that is an equivalent IN expression.  In other words, if the term
   111708 ** being analyzed is:
   111709 **
   111710 **      x = expr1  OR  expr2 = x  OR  x = expr3
   111711 **
   111712 ** then create a new virtual term like this:
   111713 **
   111714 **      x IN (expr1,expr2,expr3)
   111715 **
   111716 ** CASE 2:
   111717 **
   111718 ** If all subterms are indexable by a single table T, then set
   111719 **
   111720 **     WhereTerm.eOperator              =  WO_OR
   111721 **     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
   111722 **
   111723 ** A subterm is "indexable" if it is of the form
   111724 ** "T.C <op> <expr>" where C is any column of table T and
   111725 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
   111726 ** A subterm is also indexable if it is an AND of two or more
   111727 ** subsubterms at least one of which is indexable.  Indexable AND
   111728 ** subterms have their eOperator set to WO_AND and they have
   111729 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
   111730 **
   111731 ** From another point of view, "indexable" means that the subterm could
   111732 ** potentially be used with an index if an appropriate index exists.
   111733 ** This analysis does not consider whether or not the index exists; that
   111734 ** is decided elsewhere.  This analysis only looks at whether subterms
   111735 ** appropriate for indexing exist.
   111736 **
   111737 ** All examples A through E above satisfy case 2.  But if a term
   111738 ** also statisfies case 1 (such as B) we know that the optimizer will
   111739 ** always prefer case 1, so in that case we pretend that case 2 is not
   111740 ** satisfied.
   111741 **
   111742 ** It might be the case that multiple tables are indexable.  For example,
   111743 ** (E) above is indexable on tables P, Q, and R.
   111744 **
   111745 ** Terms that satisfy case 2 are candidates for lookup by using
   111746 ** separate indices to find rowids for each subterm and composing
   111747 ** the union of all rowids using a RowSet object.  This is similar
   111748 ** to "bitmap indices" in other database engines.
   111749 **
   111750 ** OTHERWISE:
   111751 **
   111752 ** If neither case 1 nor case 2 apply, then leave the eOperator set to
   111753 ** zero.  This term is not useful for search.
   111754 */
   111755 static void exprAnalyzeOrTerm(
   111756   SrcList *pSrc,            /* the FROM clause */
   111757   WhereClause *pWC,         /* the complete WHERE clause */
   111758   int idxTerm               /* Index of the OR-term to be analyzed */
   111759 ){
   111760   WhereInfo *pWInfo = pWC->pWInfo;        /* WHERE clause processing context */
   111761   Parse *pParse = pWInfo->pParse;         /* Parser context */
   111762   sqlite3 *db = pParse->db;               /* Database connection */
   111763   WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
   111764   Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
   111765   int i;                                  /* Loop counters */
   111766   WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
   111767   WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
   111768   WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
   111769   Bitmask chngToIN;         /* Tables that might satisfy case 1 */
   111770   Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
   111771 
   111772   /*
   111773   ** Break the OR clause into its separate subterms.  The subterms are
   111774   ** stored in a WhereClause structure containing within the WhereOrInfo
   111775   ** object that is attached to the original OR clause term.
   111776   */
   111777   assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
   111778   assert( pExpr->op==TK_OR );
   111779   pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
   111780   if( pOrInfo==0 ) return;
   111781   pTerm->wtFlags |= TERM_ORINFO;
   111782   pOrWc = &pOrInfo->wc;
   111783   whereClauseInit(pOrWc, pWInfo);
   111784   whereSplit(pOrWc, pExpr, TK_OR);
   111785   exprAnalyzeAll(pSrc, pOrWc);
   111786   if( db->mallocFailed ) return;
   111787   assert( pOrWc->nTerm>=2 );
   111788 
   111789   /*
   111790   ** Compute the set of tables that might satisfy cases 1 or 2.
   111791   */
   111792   indexable = ~(Bitmask)0;
   111793   chngToIN = ~(Bitmask)0;
   111794   for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
   111795     if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
   111796       WhereAndInfo *pAndInfo;
   111797       assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
   111798       chngToIN = 0;
   111799       pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
   111800       if( pAndInfo ){
   111801         WhereClause *pAndWC;
   111802         WhereTerm *pAndTerm;
   111803         int j;
   111804         Bitmask b = 0;
   111805         pOrTerm->u.pAndInfo = pAndInfo;
   111806         pOrTerm->wtFlags |= TERM_ANDINFO;
   111807         pOrTerm->eOperator = WO_AND;
   111808         pAndWC = &pAndInfo->wc;
   111809         whereClauseInit(pAndWC, pWC->pWInfo);
   111810         whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
   111811         exprAnalyzeAll(pSrc, pAndWC);
   111812         pAndWC->pOuter = pWC;
   111813         testcase( db->mallocFailed );
   111814         if( !db->mallocFailed ){
   111815           for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
   111816             assert( pAndTerm->pExpr );
   111817             if( allowedOp(pAndTerm->pExpr->op) ){
   111818               b |= getMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
   111819             }
   111820           }
   111821         }
   111822         indexable &= b;
   111823       }
   111824     }else if( pOrTerm->wtFlags & TERM_COPIED ){
   111825       /* Skip this term for now.  We revisit it when we process the
   111826       ** corresponding TERM_VIRTUAL term */
   111827     }else{
   111828       Bitmask b;
   111829       b = getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
   111830       if( pOrTerm->wtFlags & TERM_VIRTUAL ){
   111831         WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
   111832         b |= getMask(&pWInfo->sMaskSet, pOther->leftCursor);
   111833       }
   111834       indexable &= b;
   111835       if( (pOrTerm->eOperator & WO_EQ)==0 ){
   111836         chngToIN = 0;
   111837       }else{
   111838         chngToIN &= b;
   111839       }
   111840     }
   111841   }
   111842 
   111843   /*
   111844   ** Record the set of tables that satisfy case 2.  The set might be
   111845   ** empty.
   111846   */
   111847   pOrInfo->indexable = indexable;
   111848   pTerm->eOperator = indexable==0 ? 0 : WO_OR;
   111849 
   111850   /*
   111851   ** chngToIN holds a set of tables that *might* satisfy case 1.  But
   111852   ** we have to do some additional checking to see if case 1 really
   111853   ** is satisfied.
   111854   **
   111855   ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
   111856   ** that there is no possibility of transforming the OR clause into an
   111857   ** IN operator because one or more terms in the OR clause contain
   111858   ** something other than == on a column in the single table.  The 1-bit
   111859   ** case means that every term of the OR clause is of the form
   111860   ** "table.column=expr" for some single table.  The one bit that is set
   111861   ** will correspond to the common table.  We still need to check to make
   111862   ** sure the same column is used on all terms.  The 2-bit case is when
   111863   ** the all terms are of the form "table1.column=table2.column".  It
   111864   ** might be possible to form an IN operator with either table1.column
   111865   ** or table2.column as the LHS if either is common to every term of
   111866   ** the OR clause.
   111867   **
   111868   ** Note that terms of the form "table.column1=table.column2" (the
   111869   ** same table on both sizes of the ==) cannot be optimized.
   111870   */
   111871   if( chngToIN ){
   111872     int okToChngToIN = 0;     /* True if the conversion to IN is valid */
   111873     int iColumn = -1;         /* Column index on lhs of IN operator */
   111874     int iCursor = -1;         /* Table cursor common to all terms */
   111875     int j = 0;                /* Loop counter */
   111876 
   111877     /* Search for a table and column that appears on one side or the
   111878     ** other of the == operator in every subterm.  That table and column
   111879     ** will be recorded in iCursor and iColumn.  There might not be any
   111880     ** such table and column.  Set okToChngToIN if an appropriate table
   111881     ** and column is found but leave okToChngToIN false if not found.
   111882     */
   111883     for(j=0; j<2 && !okToChngToIN; j++){
   111884       pOrTerm = pOrWc->a;
   111885       for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
   111886         assert( pOrTerm->eOperator & WO_EQ );
   111887         pOrTerm->wtFlags &= ~TERM_OR_OK;
   111888         if( pOrTerm->leftCursor==iCursor ){
   111889           /* This is the 2-bit case and we are on the second iteration and
   111890           ** current term is from the first iteration.  So skip this term. */
   111891           assert( j==1 );
   111892           continue;
   111893         }
   111894         if( (chngToIN & getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){
   111895           /* This term must be of the form t1.a==t2.b where t2 is in the
   111896           ** chngToIN set but t1 is not.  This term will be either preceeded
   111897           ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term
   111898           ** and use its inversion. */
   111899           testcase( pOrTerm->wtFlags & TERM_COPIED );
   111900           testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
   111901           assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
   111902           continue;
   111903         }
   111904         iColumn = pOrTerm->u.leftColumn;
   111905         iCursor = pOrTerm->leftCursor;
   111906         break;
   111907       }
   111908       if( i<0 ){
   111909         /* No candidate table+column was found.  This can only occur
   111910         ** on the second iteration */
   111911         assert( j==1 );
   111912         assert( IsPowerOfTwo(chngToIN) );
   111913         assert( chngToIN==getMask(&pWInfo->sMaskSet, iCursor) );
   111914         break;
   111915       }
   111916       testcase( j==1 );
   111917 
   111918       /* We have found a candidate table and column.  Check to see if that
   111919       ** table and column is common to every term in the OR clause */
   111920       okToChngToIN = 1;
   111921       for(; i>=0 && okToChngToIN; i--, pOrTerm++){
   111922         assert( pOrTerm->eOperator & WO_EQ );
   111923         if( pOrTerm->leftCursor!=iCursor ){
   111924           pOrTerm->wtFlags &= ~TERM_OR_OK;
   111925         }else if( pOrTerm->u.leftColumn!=iColumn ){
   111926           okToChngToIN = 0;
   111927         }else{
   111928           int affLeft, affRight;
   111929           /* If the right-hand side is also a column, then the affinities
   111930           ** of both right and left sides must be such that no type
   111931           ** conversions are required on the right.  (Ticket #2249)
   111932           */
   111933           affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
   111934           affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
   111935           if( affRight!=0 && affRight!=affLeft ){
   111936             okToChngToIN = 0;
   111937           }else{
   111938             pOrTerm->wtFlags |= TERM_OR_OK;
   111939           }
   111940         }
   111941       }
   111942     }
   111943 
   111944     /* At this point, okToChngToIN is true if original pTerm satisfies
   111945     ** case 1.  In that case, construct a new virtual term that is
   111946     ** pTerm converted into an IN operator.
   111947     */
   111948     if( okToChngToIN ){
   111949       Expr *pDup;            /* A transient duplicate expression */
   111950       ExprList *pList = 0;   /* The RHS of the IN operator */
   111951       Expr *pLeft = 0;       /* The LHS of the IN operator */
   111952       Expr *pNew;            /* The complete IN operator */
   111953 
   111954       for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
   111955         if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
   111956         assert( pOrTerm->eOperator & WO_EQ );
   111957         assert( pOrTerm->leftCursor==iCursor );
   111958         assert( pOrTerm->u.leftColumn==iColumn );
   111959         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
   111960         pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
   111961         pLeft = pOrTerm->pExpr->pLeft;
   111962       }
   111963       assert( pLeft!=0 );
   111964       pDup = sqlite3ExprDup(db, pLeft, 0);
   111965       pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
   111966       if( pNew ){
   111967         int idxNew;
   111968         transferJoinMarkings(pNew, pExpr);
   111969         assert( !ExprHasProperty(pNew, EP_xIsSelect) );
   111970         pNew->x.pList = pList;
   111971         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
   111972         testcase( idxNew==0 );
   111973         exprAnalyze(pSrc, pWC, idxNew);
   111974         pTerm = &pWC->a[idxTerm];
   111975         pWC->a[idxNew].iParent = idxTerm;
   111976         pTerm->nChild = 1;
   111977       }else{
   111978         sqlite3ExprListDelete(db, pList);
   111979       }
   111980       pTerm->eOperator = WO_NOOP;  /* case 1 trumps case 2 */
   111981     }
   111982   }
   111983 }
   111984 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
   111985 
   111986 /*
   111987 ** The input to this routine is an WhereTerm structure with only the
   111988 ** "pExpr" field filled in.  The job of this routine is to analyze the
   111989 ** subexpression and populate all the other fields of the WhereTerm
   111990 ** structure.
   111991 **
   111992 ** If the expression is of the form "<expr> <op> X" it gets commuted
   111993 ** to the standard form of "X <op> <expr>".
   111994 **
   111995 ** If the expression is of the form "X <op> Y" where both X and Y are
   111996 ** columns, then the original expression is unchanged and a new virtual
   111997 ** term of the form "Y <op> X" is added to the WHERE clause and
   111998 ** analyzed separately.  The original term is marked with TERM_COPIED
   111999 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
   112000 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
   112001 ** is a commuted copy of a prior term.)  The original term has nChild=1
   112002 ** and the copy has idxParent set to the index of the original term.
   112003 */
   112004 static void exprAnalyze(
   112005   SrcList *pSrc,            /* the FROM clause */
   112006   WhereClause *pWC,         /* the WHERE clause */
   112007   int idxTerm               /* Index of the term to be analyzed */
   112008 ){
   112009   WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
   112010   WhereTerm *pTerm;                /* The term to be analyzed */
   112011   WhereMaskSet *pMaskSet;          /* Set of table index masks */
   112012   Expr *pExpr;                     /* The expression to be analyzed */
   112013   Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
   112014   Bitmask prereqAll;               /* Prerequesites of pExpr */
   112015   Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
   112016   Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
   112017   int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
   112018   int noCase = 0;                  /* LIKE/GLOB distinguishes case */
   112019   int op;                          /* Top-level operator.  pExpr->op */
   112020   Parse *pParse = pWInfo->pParse;  /* Parsing context */
   112021   sqlite3 *db = pParse->db;        /* Database connection */
   112022 
   112023   if( db->mallocFailed ){
   112024     return;
   112025   }
   112026   pTerm = &pWC->a[idxTerm];
   112027   pMaskSet = &pWInfo->sMaskSet;
   112028   pExpr = pTerm->pExpr;
   112029   assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
   112030   prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
   112031   op = pExpr->op;
   112032   if( op==TK_IN ){
   112033     assert( pExpr->pRight==0 );
   112034     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   112035       pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
   112036     }else{
   112037       pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
   112038     }
   112039   }else if( op==TK_ISNULL ){
   112040     pTerm->prereqRight = 0;
   112041   }else{
   112042     pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
   112043   }
   112044   prereqAll = exprTableUsage(pMaskSet, pExpr);
   112045   if( ExprHasProperty(pExpr, EP_FromJoin) ){
   112046     Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
   112047     prereqAll |= x;
   112048     extraRight = x-1;  /* ON clause terms may not be used with an index
   112049                        ** on left table of a LEFT JOIN.  Ticket #3015 */
   112050   }
   112051   pTerm->prereqAll = prereqAll;
   112052   pTerm->leftCursor = -1;
   112053   pTerm->iParent = -1;
   112054   pTerm->eOperator = 0;
   112055   if( allowedOp(op) ){
   112056     Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
   112057     Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
   112058     u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
   112059     if( pLeft->op==TK_COLUMN ){
   112060       pTerm->leftCursor = pLeft->iTable;
   112061       pTerm->u.leftColumn = pLeft->iColumn;
   112062       pTerm->eOperator = operatorMask(op) & opMask;
   112063     }
   112064     if( pRight && pRight->op==TK_COLUMN ){
   112065       WhereTerm *pNew;
   112066       Expr *pDup;
   112067       u16 eExtraOp = 0;        /* Extra bits for pNew->eOperator */
   112068       if( pTerm->leftCursor>=0 ){
   112069         int idxNew;
   112070         pDup = sqlite3ExprDup(db, pExpr, 0);
   112071         if( db->mallocFailed ){
   112072           sqlite3ExprDelete(db, pDup);
   112073           return;
   112074         }
   112075         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
   112076         if( idxNew==0 ) return;
   112077         pNew = &pWC->a[idxNew];
   112078         pNew->iParent = idxTerm;
   112079         pTerm = &pWC->a[idxTerm];
   112080         pTerm->nChild = 1;
   112081         pTerm->wtFlags |= TERM_COPIED;
   112082         if( pExpr->op==TK_EQ
   112083          && !ExprHasProperty(pExpr, EP_FromJoin)
   112084          && OptimizationEnabled(db, SQLITE_Transitive)
   112085         ){
   112086           pTerm->eOperator |= WO_EQUIV;
   112087           eExtraOp = WO_EQUIV;
   112088         }
   112089       }else{
   112090         pDup = pExpr;
   112091         pNew = pTerm;
   112092       }
   112093       exprCommute(pParse, pDup);
   112094       pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
   112095       pNew->leftCursor = pLeft->iTable;
   112096       pNew->u.leftColumn = pLeft->iColumn;
   112097       testcase( (prereqLeft | extraRight) != prereqLeft );
   112098       pNew->prereqRight = prereqLeft | extraRight;
   112099       pNew->prereqAll = prereqAll;
   112100       pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
   112101     }
   112102   }
   112103 
   112104 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
   112105   /* If a term is the BETWEEN operator, create two new virtual terms
   112106   ** that define the range that the BETWEEN implements.  For example:
   112107   **
   112108   **      a BETWEEN b AND c
   112109   **
   112110   ** is converted into:
   112111   **
   112112   **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
   112113   **
   112114   ** The two new terms are added onto the end of the WhereClause object.
   112115   ** The new terms are "dynamic" and are children of the original BETWEEN
   112116   ** term.  That means that if the BETWEEN term is coded, the children are
   112117   ** skipped.  Or, if the children are satisfied by an index, the original
   112118   ** BETWEEN term is skipped.
   112119   */
   112120   else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
   112121     ExprList *pList = pExpr->x.pList;
   112122     int i;
   112123     static const u8 ops[] = {TK_GE, TK_LE};
   112124     assert( pList!=0 );
   112125     assert( pList->nExpr==2 );
   112126     for(i=0; i<2; i++){
   112127       Expr *pNewExpr;
   112128       int idxNew;
   112129       pNewExpr = sqlite3PExpr(pParse, ops[i],
   112130                              sqlite3ExprDup(db, pExpr->pLeft, 0),
   112131                              sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
   112132       transferJoinMarkings(pNewExpr, pExpr);
   112133       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
   112134       testcase( idxNew==0 );
   112135       exprAnalyze(pSrc, pWC, idxNew);
   112136       pTerm = &pWC->a[idxTerm];
   112137       pWC->a[idxNew].iParent = idxTerm;
   112138     }
   112139     pTerm->nChild = 2;
   112140   }
   112141 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
   112142 
   112143 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
   112144   /* Analyze a term that is composed of two or more subterms connected by
   112145   ** an OR operator.
   112146   */
   112147   else if( pExpr->op==TK_OR ){
   112148     assert( pWC->op==TK_AND );
   112149     exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
   112150     pTerm = &pWC->a[idxTerm];
   112151   }
   112152 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
   112153 
   112154 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
   112155   /* Add constraints to reduce the search space on a LIKE or GLOB
   112156   ** operator.
   112157   **
   112158   ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
   112159   **
   112160   **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
   112161   **
   112162   ** The last character of the prefix "abc" is incremented to form the
   112163   ** termination condition "abd".
   112164   */
   112165   if( pWC->op==TK_AND
   112166    && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
   112167   ){
   112168     Expr *pLeft;       /* LHS of LIKE/GLOB operator */
   112169     Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
   112170     Expr *pNewExpr1;
   112171     Expr *pNewExpr2;
   112172     int idxNew1;
   112173     int idxNew2;
   112174     Token sCollSeqName;  /* Name of collating sequence */
   112175 
   112176     pLeft = pExpr->x.pList->a[1].pExpr;
   112177     pStr2 = sqlite3ExprDup(db, pStr1, 0);
   112178     if( !db->mallocFailed ){
   112179       u8 c, *pC;       /* Last character before the first wildcard */
   112180       pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
   112181       c = *pC;
   112182       if( noCase ){
   112183         /* The point is to increment the last character before the first
   112184         ** wildcard.  But if we increment '@', that will push it into the
   112185         ** alphabetic range where case conversions will mess up the
   112186         ** inequality.  To avoid this, make sure to also run the full
   112187         ** LIKE on all candidate expressions by clearing the isComplete flag
   112188         */
   112189         if( c=='A'-1 ) isComplete = 0;
   112190         c = sqlite3UpperToLower[c];
   112191       }
   112192       *pC = c + 1;
   112193     }
   112194     sCollSeqName.z = noCase ? "NOCASE" : "BINARY";
   112195     sCollSeqName.n = 6;
   112196     pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
   112197     pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
   112198            sqlite3ExprAddCollateToken(pParse,pNewExpr1,&sCollSeqName),
   112199            pStr1, 0);
   112200     transferJoinMarkings(pNewExpr1, pExpr);
   112201     idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
   112202     testcase( idxNew1==0 );
   112203     exprAnalyze(pSrc, pWC, idxNew1);
   112204     pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
   112205     pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
   112206            sqlite3ExprAddCollateToken(pParse,pNewExpr2,&sCollSeqName),
   112207            pStr2, 0);
   112208     transferJoinMarkings(pNewExpr2, pExpr);
   112209     idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
   112210     testcase( idxNew2==0 );
   112211     exprAnalyze(pSrc, pWC, idxNew2);
   112212     pTerm = &pWC->a[idxTerm];
   112213     if( isComplete ){
   112214       pWC->a[idxNew1].iParent = idxTerm;
   112215       pWC->a[idxNew2].iParent = idxTerm;
   112216       pTerm->nChild = 2;
   112217     }
   112218   }
   112219 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
   112220 
   112221 #ifndef SQLITE_OMIT_VIRTUALTABLE
   112222   /* Add a WO_MATCH auxiliary term to the constraint set if the
   112223   ** current expression is of the form:  column MATCH expr.
   112224   ** This information is used by the xBestIndex methods of
   112225   ** virtual tables.  The native query optimizer does not attempt
   112226   ** to do anything with MATCH functions.
   112227   */
   112228   if( isMatchOfColumn(pExpr) ){
   112229     int idxNew;
   112230     Expr *pRight, *pLeft;
   112231     WhereTerm *pNewTerm;
   112232     Bitmask prereqColumn, prereqExpr;
   112233 
   112234     pRight = pExpr->x.pList->a[0].pExpr;
   112235     pLeft = pExpr->x.pList->a[1].pExpr;
   112236     prereqExpr = exprTableUsage(pMaskSet, pRight);
   112237     prereqColumn = exprTableUsage(pMaskSet, pLeft);
   112238     if( (prereqExpr & prereqColumn)==0 ){
   112239       Expr *pNewExpr;
   112240       pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
   112241                               0, sqlite3ExprDup(db, pRight, 0), 0);
   112242       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
   112243       testcase( idxNew==0 );
   112244       pNewTerm = &pWC->a[idxNew];
   112245       pNewTerm->prereqRight = prereqExpr;
   112246       pNewTerm->leftCursor = pLeft->iTable;
   112247       pNewTerm->u.leftColumn = pLeft->iColumn;
   112248       pNewTerm->eOperator = WO_MATCH;
   112249       pNewTerm->iParent = idxTerm;
   112250       pTerm = &pWC->a[idxTerm];
   112251       pTerm->nChild = 1;
   112252       pTerm->wtFlags |= TERM_COPIED;
   112253       pNewTerm->prereqAll = pTerm->prereqAll;
   112254     }
   112255   }
   112256 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   112257 
   112258 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   112259   /* When sqlite_stat3 histogram data is available an operator of the
   112260   ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
   112261   ** as "x>NULL" if x is not an INTEGER PRIMARY KEY.  So construct a
   112262   ** virtual term of that form.
   112263   **
   112264   ** Note that the virtual term must be tagged with TERM_VNULL.  This
   112265   ** TERM_VNULL tag will suppress the not-null check at the beginning
   112266   ** of the loop.  Without the TERM_VNULL flag, the not-null check at
   112267   ** the start of the loop will prevent any results from being returned.
   112268   */
   112269   if( pExpr->op==TK_NOTNULL
   112270    && pExpr->pLeft->op==TK_COLUMN
   112271    && pExpr->pLeft->iColumn>=0
   112272    && OptimizationEnabled(db, SQLITE_Stat3)
   112273   ){
   112274     Expr *pNewExpr;
   112275     Expr *pLeft = pExpr->pLeft;
   112276     int idxNew;
   112277     WhereTerm *pNewTerm;
   112278 
   112279     pNewExpr = sqlite3PExpr(pParse, TK_GT,
   112280                             sqlite3ExprDup(db, pLeft, 0),
   112281                             sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
   112282 
   112283     idxNew = whereClauseInsert(pWC, pNewExpr,
   112284                               TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
   112285     if( idxNew ){
   112286       pNewTerm = &pWC->a[idxNew];
   112287       pNewTerm->prereqRight = 0;
   112288       pNewTerm->leftCursor = pLeft->iTable;
   112289       pNewTerm->u.leftColumn = pLeft->iColumn;
   112290       pNewTerm->eOperator = WO_GT;
   112291       pNewTerm->iParent = idxTerm;
   112292       pTerm = &pWC->a[idxTerm];
   112293       pTerm->nChild = 1;
   112294       pTerm->wtFlags |= TERM_COPIED;
   112295       pNewTerm->prereqAll = pTerm->prereqAll;
   112296     }
   112297   }
   112298 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
   112299 
   112300   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
   112301   ** an index for tables to the left of the join.
   112302   */
   112303   pTerm->prereqRight |= extraRight;
   112304 }
   112305 
   112306 /*
   112307 ** This function searches pList for a entry that matches the iCol-th column
   112308 ** of index pIdx.
   112309 **
   112310 ** If such an expression is found, its index in pList->a[] is returned. If
   112311 ** no expression is found, -1 is returned.
   112312 */
   112313 static int findIndexCol(
   112314   Parse *pParse,                  /* Parse context */
   112315   ExprList *pList,                /* Expression list to search */
   112316   int iBase,                      /* Cursor for table associated with pIdx */
   112317   Index *pIdx,                    /* Index to match column of */
   112318   int iCol                        /* Column of index to match */
   112319 ){
   112320   int i;
   112321   const char *zColl = pIdx->azColl[iCol];
   112322 
   112323   for(i=0; i<pList->nExpr; i++){
   112324     Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
   112325     if( p->op==TK_COLUMN
   112326      && p->iColumn==pIdx->aiColumn[iCol]
   112327      && p->iTable==iBase
   112328     ){
   112329       CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
   112330       if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
   112331         return i;
   112332       }
   112333     }
   112334   }
   112335 
   112336   return -1;
   112337 }
   112338 
   112339 /*
   112340 ** Return true if the DISTINCT expression-list passed as the third argument
   112341 ** is redundant.
   112342 **
   112343 ** A DISTINCT list is redundant if the database contains some subset of
   112344 ** columns that are unique and non-null.
   112345 */
   112346 static int isDistinctRedundant(
   112347   Parse *pParse,            /* Parsing context */
   112348   SrcList *pTabList,        /* The FROM clause */
   112349   WhereClause *pWC,         /* The WHERE clause */
   112350   ExprList *pDistinct       /* The result set that needs to be DISTINCT */
   112351 ){
   112352   Table *pTab;
   112353   Index *pIdx;
   112354   int i;
   112355   int iBase;
   112356 
   112357   /* If there is more than one table or sub-select in the FROM clause of
   112358   ** this query, then it will not be possible to show that the DISTINCT
   112359   ** clause is redundant. */
   112360   if( pTabList->nSrc!=1 ) return 0;
   112361   iBase = pTabList->a[0].iCursor;
   112362   pTab = pTabList->a[0].pTab;
   112363 
   112364   /* If any of the expressions is an IPK column on table iBase, then return
   112365   ** true. Note: The (p->iTable==iBase) part of this test may be false if the
   112366   ** current SELECT is a correlated sub-query.
   112367   */
   112368   for(i=0; i<pDistinct->nExpr; i++){
   112369     Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
   112370     if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
   112371   }
   112372 
   112373   /* Loop through all indices on the table, checking each to see if it makes
   112374   ** the DISTINCT qualifier redundant. It does so if:
   112375   **
   112376   **   1. The index is itself UNIQUE, and
   112377   **
   112378   **   2. All of the columns in the index are either part of the pDistinct
   112379   **      list, or else the WHERE clause contains a term of the form "col=X",
   112380   **      where X is a constant value. The collation sequences of the
   112381   **      comparison and select-list expressions must match those of the index.
   112382   **
   112383   **   3. All of those index columns for which the WHERE clause does not
   112384   **      contain a "col=X" term are subject to a NOT NULL constraint.
   112385   */
   112386   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   112387     if( !IsUniqueIndex(pIdx) ) continue;
   112388     for(i=0; i<pIdx->nKeyCol; i++){
   112389       i16 iCol = pIdx->aiColumn[i];
   112390       if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
   112391         int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
   112392         if( iIdxCol<0 || pTab->aCol[iCol].notNull==0 ){
   112393           break;
   112394         }
   112395       }
   112396     }
   112397     if( i==pIdx->nKeyCol ){
   112398       /* This index implies that the DISTINCT qualifier is redundant. */
   112399       return 1;
   112400     }
   112401   }
   112402 
   112403   return 0;
   112404 }
   112405 
   112406 
   112407 /*
   112408 ** Estimate the logarithm of the input value to base 2.
   112409 */
   112410 static LogEst estLog(LogEst N){
   112411   return N<=10 ? 0 : sqlite3LogEst(N) - 33;
   112412 }
   112413 
   112414 /*
   112415 ** Two routines for printing the content of an sqlite3_index_info
   112416 ** structure.  Used for testing and debugging only.  If neither
   112417 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
   112418 ** are no-ops.
   112419 */
   112420 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
   112421 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
   112422   int i;
   112423   if( !sqlite3WhereTrace ) return;
   112424   for(i=0; i<p->nConstraint; i++){
   112425     sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
   112426        i,
   112427        p->aConstraint[i].iColumn,
   112428        p->aConstraint[i].iTermOffset,
   112429        p->aConstraint[i].op,
   112430        p->aConstraint[i].usable);
   112431   }
   112432   for(i=0; i<p->nOrderBy; i++){
   112433     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
   112434        i,
   112435        p->aOrderBy[i].iColumn,
   112436        p->aOrderBy[i].desc);
   112437   }
   112438 }
   112439 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
   112440   int i;
   112441   if( !sqlite3WhereTrace ) return;
   112442   for(i=0; i<p->nConstraint; i++){
   112443     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
   112444        i,
   112445        p->aConstraintUsage[i].argvIndex,
   112446        p->aConstraintUsage[i].omit);
   112447   }
   112448   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
   112449   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
   112450   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
   112451   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
   112452   sqlite3DebugPrintf("  estimatedRows=%lld\n", p->estimatedRows);
   112453 }
   112454 #else
   112455 #define TRACE_IDX_INPUTS(A)
   112456 #define TRACE_IDX_OUTPUTS(A)
   112457 #endif
   112458 
   112459 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
   112460 /*
   112461 ** Return TRUE if the WHERE clause term pTerm is of a form where it
   112462 ** could be used with an index to access pSrc, assuming an appropriate
   112463 ** index existed.
   112464 */
   112465 static int termCanDriveIndex(
   112466   WhereTerm *pTerm,              /* WHERE clause term to check */
   112467   struct SrcList_item *pSrc,     /* Table we are trying to access */
   112468   Bitmask notReady               /* Tables in outer loops of the join */
   112469 ){
   112470   char aff;
   112471   if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
   112472   if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
   112473   if( (pTerm->prereqRight & notReady)!=0 ) return 0;
   112474   if( pTerm->u.leftColumn<0 ) return 0;
   112475   aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
   112476   if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
   112477   return 1;
   112478 }
   112479 #endif
   112480 
   112481 
   112482 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
   112483 /*
   112484 ** Generate code to construct the Index object for an automatic index
   112485 ** and to set up the WhereLevel object pLevel so that the code generator
   112486 ** makes use of the automatic index.
   112487 */
   112488 static void constructAutomaticIndex(
   112489   Parse *pParse,              /* The parsing context */
   112490   WhereClause *pWC,           /* The WHERE clause */
   112491   struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
   112492   Bitmask notReady,           /* Mask of cursors that are not available */
   112493   WhereLevel *pLevel          /* Write new index here */
   112494 ){
   112495   int nKeyCol;                /* Number of columns in the constructed index */
   112496   WhereTerm *pTerm;           /* A single term of the WHERE clause */
   112497   WhereTerm *pWCEnd;          /* End of pWC->a[] */
   112498   Index *pIdx;                /* Object describing the transient index */
   112499   Vdbe *v;                    /* Prepared statement under construction */
   112500   int addrInit;               /* Address of the initialization bypass jump */
   112501   Table *pTable;              /* The table being indexed */
   112502   int addrTop;                /* Top of the index fill loop */
   112503   int regRecord;              /* Register holding an index record */
   112504   int n;                      /* Column counter */
   112505   int i;                      /* Loop counter */
   112506   int mxBitCol;               /* Maximum column in pSrc->colUsed */
   112507   CollSeq *pColl;             /* Collating sequence to on a column */
   112508   WhereLoop *pLoop;           /* The Loop object */
   112509   char *zNotUsed;             /* Extra space on the end of pIdx */
   112510   Bitmask idxCols;            /* Bitmap of columns used for indexing */
   112511   Bitmask extraCols;          /* Bitmap of additional columns */
   112512   u8 sentWarning = 0;         /* True if a warnning has been issued */
   112513 
   112514   /* Generate code to skip over the creation and initialization of the
   112515   ** transient index on 2nd and subsequent iterations of the loop. */
   112516   v = pParse->pVdbe;
   112517   assert( v!=0 );
   112518   addrInit = sqlite3CodeOnce(pParse); VdbeCoverage(v);
   112519 
   112520   /* Count the number of columns that will be added to the index
   112521   ** and used to match WHERE clause constraints */
   112522   nKeyCol = 0;
   112523   pTable = pSrc->pTab;
   112524   pWCEnd = &pWC->a[pWC->nTerm];
   112525   pLoop = pLevel->pWLoop;
   112526   idxCols = 0;
   112527   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
   112528     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
   112529       int iCol = pTerm->u.leftColumn;
   112530       Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
   112531       testcase( iCol==BMS );
   112532       testcase( iCol==BMS-1 );
   112533       if( !sentWarning ){
   112534         sqlite3_log(SQLITE_WARNING_AUTOINDEX,
   112535             "automatic index on %s(%s)", pTable->zName,
   112536             pTable->aCol[iCol].zName);
   112537         sentWarning = 1;
   112538       }
   112539       if( (idxCols & cMask)==0 ){
   112540         if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ) return;
   112541         pLoop->aLTerm[nKeyCol++] = pTerm;
   112542         idxCols |= cMask;
   112543       }
   112544     }
   112545   }
   112546   assert( nKeyCol>0 );
   112547   pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
   112548   pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
   112549                      | WHERE_AUTO_INDEX;
   112550 
   112551   /* Count the number of additional columns needed to create a
   112552   ** covering index.  A "covering index" is an index that contains all
   112553   ** columns that are needed by the query.  With a covering index, the
   112554   ** original table never needs to be accessed.  Automatic indices must
   112555   ** be a covering index because the index will not be updated if the
   112556   ** original table changes and the index and table cannot both be used
   112557   ** if they go out of sync.
   112558   */
   112559   extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
   112560   mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
   112561   testcase( pTable->nCol==BMS-1 );
   112562   testcase( pTable->nCol==BMS-2 );
   112563   for(i=0; i<mxBitCol; i++){
   112564     if( extraCols & MASKBIT(i) ) nKeyCol++;
   112565   }
   112566   if( pSrc->colUsed & MASKBIT(BMS-1) ){
   112567     nKeyCol += pTable->nCol - BMS + 1;
   112568   }
   112569   pLoop->wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY;
   112570 
   112571   /* Construct the Index object to describe this index */
   112572   pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
   112573   if( pIdx==0 ) return;
   112574   pLoop->u.btree.pIndex = pIdx;
   112575   pIdx->zName = "auto-index";
   112576   pIdx->pTable = pTable;
   112577   n = 0;
   112578   idxCols = 0;
   112579   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
   112580     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
   112581       int iCol = pTerm->u.leftColumn;
   112582       Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
   112583       testcase( iCol==BMS-1 );
   112584       testcase( iCol==BMS );
   112585       if( (idxCols & cMask)==0 ){
   112586         Expr *pX = pTerm->pExpr;
   112587         idxCols |= cMask;
   112588         pIdx->aiColumn[n] = pTerm->u.leftColumn;
   112589         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
   112590         pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
   112591         n++;
   112592       }
   112593     }
   112594   }
   112595   assert( (u32)n==pLoop->u.btree.nEq );
   112596 
   112597   /* Add additional columns needed to make the automatic index into
   112598   ** a covering index */
   112599   for(i=0; i<mxBitCol; i++){
   112600     if( extraCols & MASKBIT(i) ){
   112601       pIdx->aiColumn[n] = i;
   112602       pIdx->azColl[n] = "BINARY";
   112603       n++;
   112604     }
   112605   }
   112606   if( pSrc->colUsed & MASKBIT(BMS-1) ){
   112607     for(i=BMS-1; i<pTable->nCol; i++){
   112608       pIdx->aiColumn[n] = i;
   112609       pIdx->azColl[n] = "BINARY";
   112610       n++;
   112611     }
   112612   }
   112613   assert( n==nKeyCol );
   112614   pIdx->aiColumn[n] = -1;
   112615   pIdx->azColl[n] = "BINARY";
   112616 
   112617   /* Create the automatic index */
   112618   assert( pLevel->iIdxCur>=0 );
   112619   pLevel->iIdxCur = pParse->nTab++;
   112620   sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
   112621   sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
   112622   VdbeComment((v, "for %s", pTable->zName));
   112623 
   112624   /* Fill the automatic index with content */
   112625   addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
   112626   regRecord = sqlite3GetTempReg(pParse);
   112627   sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0);
   112628   sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
   112629   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
   112630   sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
   112631   sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
   112632   sqlite3VdbeJumpHere(v, addrTop);
   112633   sqlite3ReleaseTempReg(pParse, regRecord);
   112634 
   112635   /* Jump here when skipping the initialization */
   112636   sqlite3VdbeJumpHere(v, addrInit);
   112637 }
   112638 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
   112639 
   112640 #ifndef SQLITE_OMIT_VIRTUALTABLE
   112641 /*
   112642 ** Allocate and populate an sqlite3_index_info structure. It is the
   112643 ** responsibility of the caller to eventually release the structure
   112644 ** by passing the pointer returned by this function to sqlite3_free().
   112645 */
   112646 static sqlite3_index_info *allocateIndexInfo(
   112647   Parse *pParse,
   112648   WhereClause *pWC,
   112649   struct SrcList_item *pSrc,
   112650   ExprList *pOrderBy
   112651 ){
   112652   int i, j;
   112653   int nTerm;
   112654   struct sqlite3_index_constraint *pIdxCons;
   112655   struct sqlite3_index_orderby *pIdxOrderBy;
   112656   struct sqlite3_index_constraint_usage *pUsage;
   112657   WhereTerm *pTerm;
   112658   int nOrderBy;
   112659   sqlite3_index_info *pIdxInfo;
   112660 
   112661   /* Count the number of possible WHERE clause constraints referring
   112662   ** to this virtual table */
   112663   for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
   112664     if( pTerm->leftCursor != pSrc->iCursor ) continue;
   112665     assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
   112666     testcase( pTerm->eOperator & WO_IN );
   112667     testcase( pTerm->eOperator & WO_ISNULL );
   112668     testcase( pTerm->eOperator & WO_ALL );
   112669     if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV))==0 ) continue;
   112670     if( pTerm->wtFlags & TERM_VNULL ) continue;
   112671     nTerm++;
   112672   }
   112673 
   112674   /* If the ORDER BY clause contains only columns in the current
   112675   ** virtual table then allocate space for the aOrderBy part of
   112676   ** the sqlite3_index_info structure.
   112677   */
   112678   nOrderBy = 0;
   112679   if( pOrderBy ){
   112680     int n = pOrderBy->nExpr;
   112681     for(i=0; i<n; i++){
   112682       Expr *pExpr = pOrderBy->a[i].pExpr;
   112683       if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
   112684     }
   112685     if( i==n){
   112686       nOrderBy = n;
   112687     }
   112688   }
   112689 
   112690   /* Allocate the sqlite3_index_info structure
   112691   */
   112692   pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
   112693                            + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
   112694                            + sizeof(*pIdxOrderBy)*nOrderBy );
   112695   if( pIdxInfo==0 ){
   112696     sqlite3ErrorMsg(pParse, "out of memory");
   112697     return 0;
   112698   }
   112699 
   112700   /* Initialize the structure.  The sqlite3_index_info structure contains
   112701   ** many fields that are declared "const" to prevent xBestIndex from
   112702   ** changing them.  We have to do some funky casting in order to
   112703   ** initialize those fields.
   112704   */
   112705   pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
   112706   pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
   112707   pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
   112708   *(int*)&pIdxInfo->nConstraint = nTerm;
   112709   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
   112710   *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
   112711   *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
   112712   *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
   112713                                                                    pUsage;
   112714 
   112715   for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
   112716     u8 op;
   112717     if( pTerm->leftCursor != pSrc->iCursor ) continue;
   112718     assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
   112719     testcase( pTerm->eOperator & WO_IN );
   112720     testcase( pTerm->eOperator & WO_ISNULL );
   112721     testcase( pTerm->eOperator & WO_ALL );
   112722     if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV))==0 ) continue;
   112723     if( pTerm->wtFlags & TERM_VNULL ) continue;
   112724     pIdxCons[j].iColumn = pTerm->u.leftColumn;
   112725     pIdxCons[j].iTermOffset = i;
   112726     op = (u8)pTerm->eOperator & WO_ALL;
   112727     if( op==WO_IN ) op = WO_EQ;
   112728     pIdxCons[j].op = op;
   112729     /* The direct assignment in the previous line is possible only because
   112730     ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
   112731     ** following asserts verify this fact. */
   112732     assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
   112733     assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
   112734     assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
   112735     assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
   112736     assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
   112737     assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
   112738     assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
   112739     j++;
   112740   }
   112741   for(i=0; i<nOrderBy; i++){
   112742     Expr *pExpr = pOrderBy->a[i].pExpr;
   112743     pIdxOrderBy[i].iColumn = pExpr->iColumn;
   112744     pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
   112745   }
   112746 
   112747   return pIdxInfo;
   112748 }
   112749 
   112750 /*
   112751 ** The table object reference passed as the second argument to this function
   112752 ** must represent a virtual table. This function invokes the xBestIndex()
   112753 ** method of the virtual table with the sqlite3_index_info object that
   112754 ** comes in as the 3rd argument to this function.
   112755 **
   112756 ** If an error occurs, pParse is populated with an error message and a
   112757 ** non-zero value is returned. Otherwise, 0 is returned and the output
   112758 ** part of the sqlite3_index_info structure is left populated.
   112759 **
   112760 ** Whether or not an error is returned, it is the responsibility of the
   112761 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
   112762 ** that this is required.
   112763 */
   112764 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
   112765   sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
   112766   int i;
   112767   int rc;
   112768 
   112769   TRACE_IDX_INPUTS(p);
   112770   rc = pVtab->pModule->xBestIndex(pVtab, p);
   112771   TRACE_IDX_OUTPUTS(p);
   112772 
   112773   if( rc!=SQLITE_OK ){
   112774     if( rc==SQLITE_NOMEM ){
   112775       pParse->db->mallocFailed = 1;
   112776     }else if( !pVtab->zErrMsg ){
   112777       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
   112778     }else{
   112779       sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
   112780     }
   112781   }
   112782   sqlite3_free(pVtab->zErrMsg);
   112783   pVtab->zErrMsg = 0;
   112784 
   112785   for(i=0; i<p->nConstraint; i++){
   112786     if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
   112787       sqlite3ErrorMsg(pParse,
   112788           "table %s: xBestIndex returned an invalid plan", pTab->zName);
   112789     }
   112790   }
   112791 
   112792   return pParse->nErr;
   112793 }
   112794 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
   112795 
   112796 
   112797 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   112798 /*
   112799 ** Estimate the location of a particular key among all keys in an
   112800 ** index.  Store the results in aStat as follows:
   112801 **
   112802 **    aStat[0]      Est. number of rows less than pVal
   112803 **    aStat[1]      Est. number of rows equal to pVal
   112804 **
   112805 ** Return SQLITE_OK on success.
   112806 */
   112807 static void whereKeyStats(
   112808   Parse *pParse,              /* Database connection */
   112809   Index *pIdx,                /* Index to consider domain of */
   112810   UnpackedRecord *pRec,       /* Vector of values to consider */
   112811   int roundUp,                /* Round up if true.  Round down if false */
   112812   tRowcnt *aStat              /* OUT: stats written here */
   112813 ){
   112814   IndexSample *aSample = pIdx->aSample;
   112815   int iCol;                   /* Index of required stats in anEq[] etc. */
   112816   int iMin = 0;               /* Smallest sample not yet tested */
   112817   int i = pIdx->nSample;      /* Smallest sample larger than or equal to pRec */
   112818   int iTest;                  /* Next sample to test */
   112819   int res;                    /* Result of comparison operation */
   112820 
   112821 #ifndef SQLITE_DEBUG
   112822   UNUSED_PARAMETER( pParse );
   112823 #endif
   112824   assert( pRec!=0 );
   112825   iCol = pRec->nField - 1;
   112826   assert( pIdx->nSample>0 );
   112827   assert( pRec->nField>0 && iCol<pIdx->nSampleCol );
   112828   do{
   112829     iTest = (iMin+i)/2;
   112830     res = sqlite3VdbeRecordCompare(aSample[iTest].n, aSample[iTest].p, pRec, 0);
   112831     if( res<0 ){
   112832       iMin = iTest+1;
   112833     }else{
   112834       i = iTest;
   112835     }
   112836   }while( res && iMin<i );
   112837 
   112838 #ifdef SQLITE_DEBUG
   112839   /* The following assert statements check that the binary search code
   112840   ** above found the right answer. This block serves no purpose other
   112841   ** than to invoke the asserts.  */
   112842   if( res==0 ){
   112843     /* If (res==0) is true, then sample $i must be equal to pRec */
   112844     assert( i<pIdx->nSample );
   112845     assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec, 0)
   112846          || pParse->db->mallocFailed );
   112847   }else{
   112848     /* Otherwise, pRec must be smaller than sample $i and larger than
   112849     ** sample ($i-1).  */
   112850     assert( i==pIdx->nSample
   112851          || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec, 0)>0
   112852          || pParse->db->mallocFailed );
   112853     assert( i==0
   112854          || sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec, 0)<0
   112855          || pParse->db->mallocFailed );
   112856   }
   112857 #endif /* ifdef SQLITE_DEBUG */
   112858 
   112859   /* At this point, aSample[i] is the first sample that is greater than
   112860   ** or equal to pVal.  Or if i==pIdx->nSample, then all samples are less
   112861   ** than pVal.  If aSample[i]==pVal, then res==0.
   112862   */
   112863   if( res==0 ){
   112864     aStat[0] = aSample[i].anLt[iCol];
   112865     aStat[1] = aSample[i].anEq[iCol];
   112866   }else{
   112867     tRowcnt iLower, iUpper, iGap;
   112868     if( i==0 ){
   112869       iLower = 0;
   112870       iUpper = aSample[0].anLt[iCol];
   112871     }else{
   112872       i64 nRow0 = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
   112873       iUpper = i>=pIdx->nSample ? nRow0 : aSample[i].anLt[iCol];
   112874       iLower = aSample[i-1].anEq[iCol] + aSample[i-1].anLt[iCol];
   112875     }
   112876     aStat[1] = pIdx->aAvgEq[iCol];
   112877     if( iLower>=iUpper ){
   112878       iGap = 0;
   112879     }else{
   112880       iGap = iUpper - iLower;
   112881     }
   112882     if( roundUp ){
   112883       iGap = (iGap*2)/3;
   112884     }else{
   112885       iGap = iGap/3;
   112886     }
   112887     aStat[0] = iLower + iGap;
   112888   }
   112889 }
   112890 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
   112891 
   112892 /*
   112893 ** If it is not NULL, pTerm is a term that provides an upper or lower
   112894 ** bound on a range scan. Without considering pTerm, it is estimated
   112895 ** that the scan will visit nNew rows. This function returns the number
   112896 ** estimated to be visited after taking pTerm into account.
   112897 **
   112898 ** If the user explicitly specified a likelihood() value for this term,
   112899 ** then the return value is the likelihood multiplied by the number of
   112900 ** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
   112901 ** has a likelihood of 0.50, and any other term a likelihood of 0.25.
   112902 */
   112903 static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
   112904   LogEst nRet = nNew;
   112905   if( pTerm ){
   112906     if( pTerm->truthProb<=0 ){
   112907       nRet += pTerm->truthProb;
   112908     }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
   112909       nRet -= 20;        assert( 20==sqlite3LogEst(4) );
   112910     }
   112911   }
   112912   return nRet;
   112913 }
   112914 
   112915 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   112916 /*
   112917 ** This function is called to estimate the number of rows visited by a
   112918 ** range-scan on a skip-scan index. For example:
   112919 **
   112920 **   CREATE INDEX i1 ON t1(a, b, c);
   112921 **   SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
   112922 **
   112923 ** Value pLoop->nOut is currently set to the estimated number of rows
   112924 ** visited for scanning (a=? AND b=?). This function reduces that estimate
   112925 ** by some factor to account for the (c BETWEEN ? AND ?) expression based
   112926 ** on the stat4 data for the index. this scan will be peformed multiple
   112927 ** times (once for each (a,b) combination that matches a=?) is dealt with
   112928 ** by the caller.
   112929 **
   112930 ** It does this by scanning through all stat4 samples, comparing values
   112931 ** extracted from pLower and pUpper with the corresponding column in each
   112932 ** sample. If L and U are the number of samples found to be less than or
   112933 ** equal to the values extracted from pLower and pUpper respectively, and
   112934 ** N is the total number of samples, the pLoop->nOut value is adjusted
   112935 ** as follows:
   112936 **
   112937 **   nOut = nOut * ( min(U - L, 1) / N )
   112938 **
   112939 ** If pLower is NULL, or a value cannot be extracted from the term, L is
   112940 ** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
   112941 ** U is set to N.
   112942 **
   112943 ** Normally, this function sets *pbDone to 1 before returning. However,
   112944 ** if no value can be extracted from either pLower or pUpper (and so the
   112945 ** estimate of the number of rows delivered remains unchanged), *pbDone
   112946 ** is left as is.
   112947 **
   112948 ** If an error occurs, an SQLite error code is returned. Otherwise,
   112949 ** SQLITE_OK.
   112950 */
   112951 static int whereRangeSkipScanEst(
   112952   Parse *pParse,       /* Parsing & code generating context */
   112953   WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
   112954   WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
   112955   WhereLoop *pLoop,    /* Update the .nOut value of this loop */
   112956   int *pbDone          /* Set to true if at least one expr. value extracted */
   112957 ){
   112958   Index *p = pLoop->u.btree.pIndex;
   112959   int nEq = pLoop->u.btree.nEq;
   112960   sqlite3 *db = pParse->db;
   112961   int nLower = -1;
   112962   int nUpper = p->nSample+1;
   112963   int rc = SQLITE_OK;
   112964   int iCol = p->aiColumn[nEq];
   112965   u8 aff = iCol>=0 ? p->pTable->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
   112966   CollSeq *pColl;
   112967 
   112968   sqlite3_value *p1 = 0;          /* Value extracted from pLower */
   112969   sqlite3_value *p2 = 0;          /* Value extracted from pUpper */
   112970   sqlite3_value *pVal = 0;        /* Value extracted from record */
   112971 
   112972   pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
   112973   if( pLower ){
   112974     rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
   112975     nLower = 0;
   112976   }
   112977   if( pUpper && rc==SQLITE_OK ){
   112978     rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
   112979     nUpper = p2 ? 0 : p->nSample;
   112980   }
   112981 
   112982   if( p1 || p2 ){
   112983     int i;
   112984     int nDiff;
   112985     for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
   112986       rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
   112987       if( rc==SQLITE_OK && p1 ){
   112988         int res = sqlite3MemCompare(p1, pVal, pColl);
   112989         if( res>=0 ) nLower++;
   112990       }
   112991       if( rc==SQLITE_OK && p2 ){
   112992         int res = sqlite3MemCompare(p2, pVal, pColl);
   112993         if( res>=0 ) nUpper++;
   112994       }
   112995     }
   112996     nDiff = (nUpper - nLower);
   112997     if( nDiff<=0 ) nDiff = 1;
   112998 
   112999     /* If there is both an upper and lower bound specified, and the
   113000     ** comparisons indicate that they are close together, use the fallback
   113001     ** method (assume that the scan visits 1/64 of the rows) for estimating
   113002     ** the number of rows visited. Otherwise, estimate the number of rows
   113003     ** using the method described in the header comment for this function. */
   113004     if( nDiff!=1 || pUpper==0 || pLower==0 ){
   113005       int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
   113006       pLoop->nOut -= nAdjust;
   113007       *pbDone = 1;
   113008       WHERETRACE(0x10, ("range skip-scan regions: %u..%u  adjust=%d est=%d\n",
   113009                            nLower, nUpper, nAdjust*-1, pLoop->nOut));
   113010     }
   113011 
   113012   }else{
   113013     assert( *pbDone==0 );
   113014   }
   113015 
   113016   sqlite3ValueFree(p1);
   113017   sqlite3ValueFree(p2);
   113018   sqlite3ValueFree(pVal);
   113019 
   113020   return rc;
   113021 }
   113022 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
   113023 
   113024 /*
   113025 ** This function is used to estimate the number of rows that will be visited
   113026 ** by scanning an index for a range of values. The range may have an upper
   113027 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
   113028 ** and lower bounds are represented by pLower and pUpper respectively. For
   113029 ** example, assuming that index p is on t1(a):
   113030 **
   113031 **   ... FROM t1 WHERE a > ? AND a < ? ...
   113032 **                    |_____|   |_____|
   113033 **                       |         |
   113034 **                     pLower    pUpper
   113035 **
   113036 ** If either of the upper or lower bound is not present, then NULL is passed in
   113037 ** place of the corresponding WhereTerm.
   113038 **
   113039 ** The value in (pBuilder->pNew->u.btree.nEq) is the index of the index
   113040 ** column subject to the range constraint. Or, equivalently, the number of
   113041 ** equality constraints optimized by the proposed index scan. For example,
   113042 ** assuming index p is on t1(a, b), and the SQL query is:
   113043 **
   113044 **   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
   113045 **
   113046 ** then nEq is set to 1 (as the range restricted column, b, is the second
   113047 ** left-most column of the index). Or, if the query is:
   113048 **
   113049 **   ... FROM t1 WHERE a > ? AND a < ? ...
   113050 **
   113051 ** then nEq is set to 0.
   113052 **
   113053 ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
   113054 ** number of rows that the index scan is expected to visit without
   113055 ** considering the range constraints. If nEq is 0, this is the number of
   113056 ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
   113057 ** to account for the range contraints pLower and pUpper.
   113058 **
   113059 ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
   113060 ** used, a single range inequality reduces the search space by a factor of 4.
   113061 ** and a pair of constraints (x>? AND x<?) reduces the expected number of
   113062 ** rows visited by a factor of 64.
   113063 */
   113064 static int whereRangeScanEst(
   113065   Parse *pParse,       /* Parsing & code generating context */
   113066   WhereLoopBuilder *pBuilder,
   113067   WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
   113068   WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
   113069   WhereLoop *pLoop     /* Modify the .nOut and maybe .rRun fields */
   113070 ){
   113071   int rc = SQLITE_OK;
   113072   int nOut = pLoop->nOut;
   113073   LogEst nNew;
   113074 
   113075 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   113076   Index *p = pLoop->u.btree.pIndex;
   113077   int nEq = pLoop->u.btree.nEq;
   113078 
   113079   if( p->nSample>0
   113080    && nEq<p->nSampleCol
   113081    && OptimizationEnabled(pParse->db, SQLITE_Stat3)
   113082   ){
   113083     if( nEq==pBuilder->nRecValid ){
   113084       UnpackedRecord *pRec = pBuilder->pRec;
   113085       tRowcnt a[2];
   113086       u8 aff;
   113087 
   113088       /* Variable iLower will be set to the estimate of the number of rows in
   113089       ** the index that are less than the lower bound of the range query. The
   113090       ** lower bound being the concatenation of $P and $L, where $P is the
   113091       ** key-prefix formed by the nEq values matched against the nEq left-most
   113092       ** columns of the index, and $L is the value in pLower.
   113093       **
   113094       ** Or, if pLower is NULL or $L cannot be extracted from it (because it
   113095       ** is not a simple variable or literal value), the lower bound of the
   113096       ** range is $P. Due to a quirk in the way whereKeyStats() works, even
   113097       ** if $L is available, whereKeyStats() is called for both ($P) and
   113098       ** ($P:$L) and the larger of the two returned values used.
   113099       **
   113100       ** Similarly, iUpper is to be set to the estimate of the number of rows
   113101       ** less than the upper bound of the range query. Where the upper bound
   113102       ** is either ($P) or ($P:$U). Again, even if $U is available, both values
   113103       ** of iUpper are requested of whereKeyStats() and the smaller used.
   113104       */
   113105       tRowcnt iLower;
   113106       tRowcnt iUpper;
   113107 
   113108       if( nEq==p->nKeyCol ){
   113109         aff = SQLITE_AFF_INTEGER;
   113110       }else{
   113111         aff = p->pTable->aCol[p->aiColumn[nEq]].affinity;
   113112       }
   113113       /* Determine iLower and iUpper using ($P) only. */
   113114       if( nEq==0 ){
   113115         iLower = 0;
   113116         iUpper = sqlite3LogEstToInt(p->aiRowLogEst[0]);
   113117       }else{
   113118         /* Note: this call could be optimized away - since the same values must
   113119         ** have been requested when testing key $P in whereEqualScanEst().  */
   113120         whereKeyStats(pParse, p, pRec, 0, a);
   113121         iLower = a[0];
   113122         iUpper = a[0] + a[1];
   113123       }
   113124 
   113125       /* If possible, improve on the iLower estimate using ($P:$L). */
   113126       if( pLower ){
   113127         int bOk;                    /* True if value is extracted from pExpr */
   113128         Expr *pExpr = pLower->pExpr->pRight;
   113129         assert( (pLower->eOperator & (WO_GT|WO_GE))!=0 );
   113130         rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
   113131         if( rc==SQLITE_OK && bOk ){
   113132           tRowcnt iNew;
   113133           whereKeyStats(pParse, p, pRec, 0, a);
   113134           iNew = a[0] + ((pLower->eOperator & WO_GT) ? a[1] : 0);
   113135           if( iNew>iLower ) iLower = iNew;
   113136           nOut--;
   113137         }
   113138       }
   113139 
   113140       /* If possible, improve on the iUpper estimate using ($P:$U). */
   113141       if( pUpper ){
   113142         int bOk;                    /* True if value is extracted from pExpr */
   113143         Expr *pExpr = pUpper->pExpr->pRight;
   113144         assert( (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
   113145         rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
   113146         if( rc==SQLITE_OK && bOk ){
   113147           tRowcnt iNew;
   113148           whereKeyStats(pParse, p, pRec, 1, a);
   113149           iNew = a[0] + ((pUpper->eOperator & WO_LE) ? a[1] : 0);
   113150           if( iNew<iUpper ) iUpper = iNew;
   113151           nOut--;
   113152         }
   113153       }
   113154 
   113155       pBuilder->pRec = pRec;
   113156       if( rc==SQLITE_OK ){
   113157         if( iUpper>iLower ){
   113158           nNew = sqlite3LogEst(iUpper - iLower);
   113159         }else{
   113160           nNew = 10;        assert( 10==sqlite3LogEst(2) );
   113161         }
   113162         if( nNew<nOut ){
   113163           nOut = nNew;
   113164         }
   113165         pLoop->nOut = (LogEst)nOut;
   113166         WHERETRACE(0x10, ("range scan regions: %u..%u  est=%d\n",
   113167                            (u32)iLower, (u32)iUpper, nOut));
   113168         return SQLITE_OK;
   113169       }
   113170     }else{
   113171       int bDone = 0;
   113172       rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
   113173       if( bDone ) return rc;
   113174     }
   113175   }
   113176 #else
   113177   UNUSED_PARAMETER(pParse);
   113178   UNUSED_PARAMETER(pBuilder);
   113179 #endif
   113180   assert( pLower || pUpper );
   113181   assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
   113182   nNew = whereRangeAdjust(pLower, nOut);
   113183   nNew = whereRangeAdjust(pUpper, nNew);
   113184 
   113185   /* TUNING: If there is both an upper and lower limit, assume the range is
   113186   ** reduced by an additional 75%. This means that, by default, an open-ended
   113187   ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
   113188   ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
   113189   ** match 1/64 of the index. */
   113190   if( pLower && pUpper ) nNew -= 20;
   113191 
   113192   nOut -= (pLower!=0) + (pUpper!=0);
   113193   if( nNew<10 ) nNew = 10;
   113194   if( nNew<nOut ) nOut = nNew;
   113195   pLoop->nOut = (LogEst)nOut;
   113196   return rc;
   113197 }
   113198 
   113199 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   113200 /*
   113201 ** Estimate the number of rows that will be returned based on
   113202 ** an equality constraint x=VALUE and where that VALUE occurs in
   113203 ** the histogram data.  This only works when x is the left-most
   113204 ** column of an index and sqlite_stat3 histogram data is available
   113205 ** for that index.  When pExpr==NULL that means the constraint is
   113206 ** "x IS NULL" instead of "x=VALUE".
   113207 **
   113208 ** Write the estimated row count into *pnRow and return SQLITE_OK.
   113209 ** If unable to make an estimate, leave *pnRow unchanged and return
   113210 ** non-zero.
   113211 **
   113212 ** This routine can fail if it is unable to load a collating sequence
   113213 ** required for string comparison, or if unable to allocate memory
   113214 ** for a UTF conversion required for comparison.  The error is stored
   113215 ** in the pParse structure.
   113216 */
   113217 static int whereEqualScanEst(
   113218   Parse *pParse,       /* Parsing & code generating context */
   113219   WhereLoopBuilder *pBuilder,
   113220   Expr *pExpr,         /* Expression for VALUE in the x=VALUE constraint */
   113221   tRowcnt *pnRow       /* Write the revised row estimate here */
   113222 ){
   113223   Index *p = pBuilder->pNew->u.btree.pIndex;
   113224   int nEq = pBuilder->pNew->u.btree.nEq;
   113225   UnpackedRecord *pRec = pBuilder->pRec;
   113226   u8 aff;                   /* Column affinity */
   113227   int rc;                   /* Subfunction return code */
   113228   tRowcnt a[2];             /* Statistics */
   113229   int bOk;
   113230 
   113231   assert( nEq>=1 );
   113232   assert( nEq<=p->nColumn );
   113233   assert( p->aSample!=0 );
   113234   assert( p->nSample>0 );
   113235   assert( pBuilder->nRecValid<nEq );
   113236 
   113237   /* If values are not available for all fields of the index to the left
   113238   ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
   113239   if( pBuilder->nRecValid<(nEq-1) ){
   113240     return SQLITE_NOTFOUND;
   113241   }
   113242 
   113243   /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
   113244   ** below would return the same value.  */
   113245   if( nEq>=p->nColumn ){
   113246     *pnRow = 1;
   113247     return SQLITE_OK;
   113248   }
   113249 
   113250   aff = p->pTable->aCol[p->aiColumn[nEq-1]].affinity;
   113251   rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
   113252   pBuilder->pRec = pRec;
   113253   if( rc!=SQLITE_OK ) return rc;
   113254   if( bOk==0 ) return SQLITE_NOTFOUND;
   113255   pBuilder->nRecValid = nEq;
   113256 
   113257   whereKeyStats(pParse, p, pRec, 0, a);
   113258   WHERETRACE(0x10,("equality scan regions: %d\n", (int)a[1]));
   113259   *pnRow = a[1];
   113260 
   113261   return rc;
   113262 }
   113263 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
   113264 
   113265 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   113266 /*
   113267 ** Estimate the number of rows that will be returned based on
   113268 ** an IN constraint where the right-hand side of the IN operator
   113269 ** is a list of values.  Example:
   113270 **
   113271 **        WHERE x IN (1,2,3,4)
   113272 **
   113273 ** Write the estimated row count into *pnRow and return SQLITE_OK.
   113274 ** If unable to make an estimate, leave *pnRow unchanged and return
   113275 ** non-zero.
   113276 **
   113277 ** This routine can fail if it is unable to load a collating sequence
   113278 ** required for string comparison, or if unable to allocate memory
   113279 ** for a UTF conversion required for comparison.  The error is stored
   113280 ** in the pParse structure.
   113281 */
   113282 static int whereInScanEst(
   113283   Parse *pParse,       /* Parsing & code generating context */
   113284   WhereLoopBuilder *pBuilder,
   113285   ExprList *pList,     /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
   113286   tRowcnt *pnRow       /* Write the revised row estimate here */
   113287 ){
   113288   Index *p = pBuilder->pNew->u.btree.pIndex;
   113289   i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
   113290   int nRecValid = pBuilder->nRecValid;
   113291   int rc = SQLITE_OK;     /* Subfunction return code */
   113292   tRowcnt nEst;           /* Number of rows for a single term */
   113293   tRowcnt nRowEst = 0;    /* New estimate of the number of rows */
   113294   int i;                  /* Loop counter */
   113295 
   113296   assert( p->aSample!=0 );
   113297   for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
   113298     nEst = nRow0;
   113299     rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
   113300     nRowEst += nEst;
   113301     pBuilder->nRecValid = nRecValid;
   113302   }
   113303 
   113304   if( rc==SQLITE_OK ){
   113305     if( nRowEst > nRow0 ) nRowEst = nRow0;
   113306     *pnRow = nRowEst;
   113307     WHERETRACE(0x10,("IN row estimate: est=%g\n", nRowEst));
   113308   }
   113309   assert( pBuilder->nRecValid==nRecValid );
   113310   return rc;
   113311 }
   113312 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
   113313 
   113314 /*
   113315 ** Disable a term in the WHERE clause.  Except, do not disable the term
   113316 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
   113317 ** or USING clause of that join.
   113318 **
   113319 ** Consider the term t2.z='ok' in the following queries:
   113320 **
   113321 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
   113322 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
   113323 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
   113324 **
   113325 ** The t2.z='ok' is disabled in the in (2) because it originates
   113326 ** in the ON clause.  The term is disabled in (3) because it is not part
   113327 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
   113328 **
   113329 ** Disabling a term causes that term to not be tested in the inner loop
   113330 ** of the join.  Disabling is an optimization.  When terms are satisfied
   113331 ** by indices, we disable them to prevent redundant tests in the inner
   113332 ** loop.  We would get the correct results if nothing were ever disabled,
   113333 ** but joins might run a little slower.  The trick is to disable as much
   113334 ** as we can without disabling too much.  If we disabled in (1), we'd get
   113335 ** the wrong answer.  See ticket #813.
   113336 */
   113337 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
   113338   if( pTerm
   113339       && (pTerm->wtFlags & TERM_CODED)==0
   113340       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
   113341       && (pLevel->notReady & pTerm->prereqAll)==0
   113342   ){
   113343     pTerm->wtFlags |= TERM_CODED;
   113344     if( pTerm->iParent>=0 ){
   113345       WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
   113346       if( (--pOther->nChild)==0 ){
   113347         disableTerm(pLevel, pOther);
   113348       }
   113349     }
   113350   }
   113351 }
   113352 
   113353 /*
   113354 ** Code an OP_Affinity opcode to apply the column affinity string zAff
   113355 ** to the n registers starting at base.
   113356 **
   113357 ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
   113358 ** beginning and end of zAff are ignored.  If all entries in zAff are
   113359 ** SQLITE_AFF_NONE, then no code gets generated.
   113360 **
   113361 ** This routine makes its own copy of zAff so that the caller is free
   113362 ** to modify zAff after this routine returns.
   113363 */
   113364 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
   113365   Vdbe *v = pParse->pVdbe;
   113366   if( zAff==0 ){
   113367     assert( pParse->db->mallocFailed );
   113368     return;
   113369   }
   113370   assert( v!=0 );
   113371 
   113372   /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
   113373   ** and end of the affinity string.
   113374   */
   113375   while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
   113376     n--;
   113377     base++;
   113378     zAff++;
   113379   }
   113380   while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
   113381     n--;
   113382   }
   113383 
   113384   /* Code the OP_Affinity opcode if there is anything left to do. */
   113385   if( n>0 ){
   113386     sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
   113387     sqlite3VdbeChangeP4(v, -1, zAff, n);
   113388     sqlite3ExprCacheAffinityChange(pParse, base, n);
   113389   }
   113390 }
   113391 
   113392 
   113393 /*
   113394 ** Generate code for a single equality term of the WHERE clause.  An equality
   113395 ** term can be either X=expr or X IN (...).   pTerm is the term to be
   113396 ** coded.
   113397 **
   113398 ** The current value for the constraint is left in register iReg.
   113399 **
   113400 ** For a constraint of the form X=expr, the expression is evaluated and its
   113401 ** result is left on the stack.  For constraints of the form X IN (...)
   113402 ** this routine sets up a loop that will iterate over all values of X.
   113403 */
   113404 static int codeEqualityTerm(
   113405   Parse *pParse,      /* The parsing context */
   113406   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
   113407   WhereLevel *pLevel, /* The level of the FROM clause we are working on */
   113408   int iEq,            /* Index of the equality term within this level */
   113409   int bRev,           /* True for reverse-order IN operations */
   113410   int iTarget         /* Attempt to leave results in this register */
   113411 ){
   113412   Expr *pX = pTerm->pExpr;
   113413   Vdbe *v = pParse->pVdbe;
   113414   int iReg;                  /* Register holding results */
   113415 
   113416   assert( iTarget>0 );
   113417   if( pX->op==TK_EQ ){
   113418     iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
   113419   }else if( pX->op==TK_ISNULL ){
   113420     iReg = iTarget;
   113421     sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
   113422 #ifndef SQLITE_OMIT_SUBQUERY
   113423   }else{
   113424     int eType;
   113425     int iTab;
   113426     struct InLoop *pIn;
   113427     WhereLoop *pLoop = pLevel->pWLoop;
   113428 
   113429     if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
   113430       && pLoop->u.btree.pIndex!=0
   113431       && pLoop->u.btree.pIndex->aSortOrder[iEq]
   113432     ){
   113433       testcase( iEq==0 );
   113434       testcase( bRev );
   113435       bRev = !bRev;
   113436     }
   113437     assert( pX->op==TK_IN );
   113438     iReg = iTarget;
   113439     eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0);
   113440     if( eType==IN_INDEX_INDEX_DESC ){
   113441       testcase( bRev );
   113442       bRev = !bRev;
   113443     }
   113444     iTab = pX->iTable;
   113445     sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
   113446     VdbeCoverageIf(v, bRev);
   113447     VdbeCoverageIf(v, !bRev);
   113448     assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
   113449     pLoop->wsFlags |= WHERE_IN_ABLE;
   113450     if( pLevel->u.in.nIn==0 ){
   113451       pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
   113452     }
   113453     pLevel->u.in.nIn++;
   113454     pLevel->u.in.aInLoop =
   113455        sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
   113456                               sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
   113457     pIn = pLevel->u.in.aInLoop;
   113458     if( pIn ){
   113459       pIn += pLevel->u.in.nIn - 1;
   113460       pIn->iCur = iTab;
   113461       if( eType==IN_INDEX_ROWID ){
   113462         pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
   113463       }else{
   113464         pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
   113465       }
   113466       pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
   113467       sqlite3VdbeAddOp1(v, OP_IsNull, iReg); VdbeCoverage(v);
   113468     }else{
   113469       pLevel->u.in.nIn = 0;
   113470     }
   113471 #endif
   113472   }
   113473   disableTerm(pLevel, pTerm);
   113474   return iReg;
   113475 }
   113476 
   113477 /*
   113478 ** Generate code that will evaluate all == and IN constraints for an
   113479 ** index scan.
   113480 **
   113481 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
   113482 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
   113483 ** The index has as many as three equality constraints, but in this
   113484 ** example, the third "c" value is an inequality.  So only two
   113485 ** constraints are coded.  This routine will generate code to evaluate
   113486 ** a==5 and b IN (1,2,3).  The current values for a and b will be stored
   113487 ** in consecutive registers and the index of the first register is returned.
   113488 **
   113489 ** In the example above nEq==2.  But this subroutine works for any value
   113490 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
   113491 ** The only thing it does is allocate the pLevel->iMem memory cell and
   113492 ** compute the affinity string.
   113493 **
   113494 ** The nExtraReg parameter is 0 or 1.  It is 0 if all WHERE clause constraints
   113495 ** are == or IN and are covered by the nEq.  nExtraReg is 1 if there is
   113496 ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
   113497 ** occurs after the nEq quality constraints.
   113498 **
   113499 ** This routine allocates a range of nEq+nExtraReg memory cells and returns
   113500 ** the index of the first memory cell in that range. The code that
   113501 ** calls this routine will use that memory range to store keys for
   113502 ** start and termination conditions of the loop.
   113503 ** key value of the loop.  If one or more IN operators appear, then
   113504 ** this routine allocates an additional nEq memory cells for internal
   113505 ** use.
   113506 **
   113507 ** Before returning, *pzAff is set to point to a buffer containing a
   113508 ** copy of the column affinity string of the index allocated using
   113509 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
   113510 ** with equality constraints that use NONE affinity are set to
   113511 ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
   113512 **
   113513 **   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
   113514 **   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
   113515 **
   113516 ** In the example above, the index on t1(a) has TEXT affinity. But since
   113517 ** the right hand side of the equality constraint (t2.b) has NONE affinity,
   113518 ** no conversion should be attempted before using a t2.b value as part of
   113519 ** a key to search the index. Hence the first byte in the returned affinity
   113520 ** string in this example would be set to SQLITE_AFF_NONE.
   113521 */
   113522 static int codeAllEqualityTerms(
   113523   Parse *pParse,        /* Parsing context */
   113524   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
   113525   int bRev,             /* Reverse the order of IN operators */
   113526   int nExtraReg,        /* Number of extra registers to allocate */
   113527   char **pzAff          /* OUT: Set to point to affinity string */
   113528 ){
   113529   u16 nEq;                      /* The number of == or IN constraints to code */
   113530   u16 nSkip;                    /* Number of left-most columns to skip */
   113531   Vdbe *v = pParse->pVdbe;      /* The vm under construction */
   113532   Index *pIdx;                  /* The index being used for this loop */
   113533   WhereTerm *pTerm;             /* A single constraint term */
   113534   WhereLoop *pLoop;             /* The WhereLoop object */
   113535   int j;                        /* Loop counter */
   113536   int regBase;                  /* Base register */
   113537   int nReg;                     /* Number of registers to allocate */
   113538   char *zAff;                   /* Affinity string to return */
   113539 
   113540   /* This module is only called on query plans that use an index. */
   113541   pLoop = pLevel->pWLoop;
   113542   assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
   113543   nEq = pLoop->u.btree.nEq;
   113544   nSkip = pLoop->u.btree.nSkip;
   113545   pIdx = pLoop->u.btree.pIndex;
   113546   assert( pIdx!=0 );
   113547 
   113548   /* Figure out how many memory cells we will need then allocate them.
   113549   */
   113550   regBase = pParse->nMem + 1;
   113551   nReg = pLoop->u.btree.nEq + nExtraReg;
   113552   pParse->nMem += nReg;
   113553 
   113554   zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
   113555   if( !zAff ){
   113556     pParse->db->mallocFailed = 1;
   113557   }
   113558 
   113559   if( nSkip ){
   113560     int iIdxCur = pLevel->iIdxCur;
   113561     sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
   113562     VdbeCoverageIf(v, bRev==0);
   113563     VdbeCoverageIf(v, bRev!=0);
   113564     VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
   113565     j = sqlite3VdbeAddOp0(v, OP_Goto);
   113566     pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
   113567                             iIdxCur, 0, regBase, nSkip);
   113568     VdbeCoverageIf(v, bRev==0);
   113569     VdbeCoverageIf(v, bRev!=0);
   113570     sqlite3VdbeJumpHere(v, j);
   113571     for(j=0; j<nSkip; j++){
   113572       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
   113573       assert( pIdx->aiColumn[j]>=0 );
   113574       VdbeComment((v, "%s", pIdx->pTable->aCol[pIdx->aiColumn[j]].zName));
   113575     }
   113576   }
   113577 
   113578   /* Evaluate the equality constraints
   113579   */
   113580   assert( zAff==0 || (int)strlen(zAff)>=nEq );
   113581   for(j=nSkip; j<nEq; j++){
   113582     int r1;
   113583     pTerm = pLoop->aLTerm[j];
   113584     assert( pTerm!=0 );
   113585     /* The following testcase is true for indices with redundant columns.
   113586     ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
   113587     testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
   113588     testcase( pTerm->wtFlags & TERM_VIRTUAL );
   113589     r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
   113590     if( r1!=regBase+j ){
   113591       if( nReg==1 ){
   113592         sqlite3ReleaseTempReg(pParse, regBase);
   113593         regBase = r1;
   113594       }else{
   113595         sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
   113596       }
   113597     }
   113598     testcase( pTerm->eOperator & WO_ISNULL );
   113599     testcase( pTerm->eOperator & WO_IN );
   113600     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
   113601       Expr *pRight = pTerm->pExpr->pRight;
   113602       if( sqlite3ExprCanBeNull(pRight) ){
   113603         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
   113604         VdbeCoverage(v);
   113605       }
   113606       if( zAff ){
   113607         if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
   113608           zAff[j] = SQLITE_AFF_NONE;
   113609         }
   113610         if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
   113611           zAff[j] = SQLITE_AFF_NONE;
   113612         }
   113613       }
   113614     }
   113615   }
   113616   *pzAff = zAff;
   113617   return regBase;
   113618 }
   113619 
   113620 #ifndef SQLITE_OMIT_EXPLAIN
   113621 /*
   113622 ** This routine is a helper for explainIndexRange() below
   113623 **
   113624 ** pStr holds the text of an expression that we are building up one term
   113625 ** at a time.  This routine adds a new term to the end of the expression.
   113626 ** Terms are separated by AND so add the "AND" text for second and subsequent
   113627 ** terms only.
   113628 */
   113629 static void explainAppendTerm(
   113630   StrAccum *pStr,             /* The text expression being built */
   113631   int iTerm,                  /* Index of this term.  First is zero */
   113632   const char *zColumn,        /* Name of the column */
   113633   const char *zOp             /* Name of the operator */
   113634 ){
   113635   if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
   113636   sqlite3StrAccumAppendAll(pStr, zColumn);
   113637   sqlite3StrAccumAppend(pStr, zOp, 1);
   113638   sqlite3StrAccumAppend(pStr, "?", 1);
   113639 }
   113640 
   113641 /*
   113642 ** Argument pLevel describes a strategy for scanning table pTab. This
   113643 ** function returns a pointer to a string buffer containing a description
   113644 ** of the subset of table rows scanned by the strategy in the form of an
   113645 ** SQL expression. Or, if all rows are scanned, NULL is returned.
   113646 **
   113647 ** For example, if the query:
   113648 **
   113649 **   SELECT * FROM t1 WHERE a=1 AND b>2;
   113650 **
   113651 ** is run and there is an index on (a, b), then this function returns a
   113652 ** string similar to:
   113653 **
   113654 **   "a=? AND b>?"
   113655 **
   113656 ** The returned pointer points to memory obtained from sqlite3DbMalloc().
   113657 ** It is the responsibility of the caller to free the buffer when it is
   113658 ** no longer required.
   113659 */
   113660 static char *explainIndexRange(sqlite3 *db, WhereLoop *pLoop, Table *pTab){
   113661   Index *pIndex = pLoop->u.btree.pIndex;
   113662   u16 nEq = pLoop->u.btree.nEq;
   113663   u16 nSkip = pLoop->u.btree.nSkip;
   113664   int i, j;
   113665   Column *aCol = pTab->aCol;
   113666   i16 *aiColumn = pIndex->aiColumn;
   113667   StrAccum txt;
   113668 
   113669   if( nEq==0 && (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
   113670     return 0;
   113671   }
   113672   sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
   113673   txt.db = db;
   113674   sqlite3StrAccumAppend(&txt, " (", 2);
   113675   for(i=0; i<nEq; i++){
   113676     char *z = aiColumn[i] < 0 ? "rowid" : aCol[aiColumn[i]].zName;
   113677     if( i>=nSkip ){
   113678       explainAppendTerm(&txt, i, z, "=");
   113679     }else{
   113680       if( i ) sqlite3StrAccumAppend(&txt, " AND ", 5);
   113681       sqlite3StrAccumAppend(&txt, "ANY(", 4);
   113682       sqlite3StrAccumAppendAll(&txt, z);
   113683       sqlite3StrAccumAppend(&txt, ")", 1);
   113684     }
   113685   }
   113686 
   113687   j = i;
   113688   if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
   113689     char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName;
   113690     explainAppendTerm(&txt, i++, z, ">");
   113691   }
   113692   if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
   113693     char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName;
   113694     explainAppendTerm(&txt, i, z, "<");
   113695   }
   113696   sqlite3StrAccumAppend(&txt, ")", 1);
   113697   return sqlite3StrAccumFinish(&txt);
   113698 }
   113699 
   113700 /*
   113701 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
   113702 ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
   113703 ** record is added to the output to describe the table scan strategy in
   113704 ** pLevel.
   113705 */
   113706 static void explainOneScan(
   113707   Parse *pParse,                  /* Parse context */
   113708   SrcList *pTabList,              /* Table list this loop refers to */
   113709   WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
   113710   int iLevel,                     /* Value for "level" column of output */
   113711   int iFrom,                      /* Value for "from" column of output */
   113712   u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
   113713 ){
   113714 #ifndef SQLITE_DEBUG
   113715   if( pParse->explain==2 )
   113716 #endif
   113717   {
   113718     struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
   113719     Vdbe *v = pParse->pVdbe;      /* VM being constructed */
   113720     sqlite3 *db = pParse->db;     /* Database handle */
   113721     char *zMsg;                   /* Text to add to EQP output */
   113722     int iId = pParse->iSelectId;  /* Select id (left-most output column) */
   113723     int isSearch;                 /* True for a SEARCH. False for SCAN. */
   113724     WhereLoop *pLoop;             /* The controlling WhereLoop object */
   113725     u32 flags;                    /* Flags that describe this loop */
   113726 
   113727     pLoop = pLevel->pWLoop;
   113728     flags = pLoop->wsFlags;
   113729     if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
   113730 
   113731     isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
   113732             || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
   113733             || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
   113734 
   113735     zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
   113736     if( pItem->pSelect ){
   113737       zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
   113738     }else{
   113739       zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
   113740     }
   113741 
   113742     if( pItem->zAlias ){
   113743       zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
   113744     }
   113745     if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0
   113746      && ALWAYS(pLoop->u.btree.pIndex!=0)
   113747     ){
   113748       const char *zFmt;
   113749       Index *pIdx = pLoop->u.btree.pIndex;
   113750       char *zWhere = explainIndexRange(db, pLoop, pItem->pTab);
   113751       assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
   113752       if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
   113753         zFmt = zWhere ? "%s USING PRIMARY KEY%.0s%s" : "%s%.0s%s";
   113754       }else if( flags & WHERE_AUTO_INDEX ){
   113755         zFmt = "%s USING AUTOMATIC COVERING INDEX%.0s%s";
   113756       }else if( flags & WHERE_IDX_ONLY ){
   113757         zFmt = "%s USING COVERING INDEX %s%s";
   113758       }else{
   113759         zFmt = "%s USING INDEX %s%s";
   113760       }
   113761       zMsg = sqlite3MAppendf(db, zMsg, zFmt, zMsg, pIdx->zName, zWhere);
   113762       sqlite3DbFree(db, zWhere);
   113763     }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
   113764       zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
   113765 
   113766       if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
   113767         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
   113768       }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
   113769         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
   113770       }else if( flags&WHERE_BTM_LIMIT ){
   113771         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
   113772       }else if( ALWAYS(flags&WHERE_TOP_LIMIT) ){
   113773         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
   113774       }
   113775     }
   113776 #ifndef SQLITE_OMIT_VIRTUALTABLE
   113777     else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
   113778       zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
   113779                   pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
   113780     }
   113781 #endif
   113782     zMsg = sqlite3MAppendf(db, zMsg, "%s", zMsg);
   113783     sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
   113784   }
   113785 }
   113786 #else
   113787 # define explainOneScan(u,v,w,x,y,z)
   113788 #endif /* SQLITE_OMIT_EXPLAIN */
   113789 
   113790 
   113791 /*
   113792 ** Generate code for the start of the iLevel-th loop in the WHERE clause
   113793 ** implementation described by pWInfo.
   113794 */
   113795 static Bitmask codeOneLoopStart(
   113796   WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
   113797   int iLevel,          /* Which level of pWInfo->a[] should be coded */
   113798   Bitmask notReady     /* Which tables are currently available */
   113799 ){
   113800   int j, k;            /* Loop counters */
   113801   int iCur;            /* The VDBE cursor for the table */
   113802   int addrNxt;         /* Where to jump to continue with the next IN case */
   113803   int omitTable;       /* True if we use the index only */
   113804   int bRev;            /* True if we need to scan in reverse order */
   113805   WhereLevel *pLevel;  /* The where level to be coded */
   113806   WhereLoop *pLoop;    /* The WhereLoop object being coded */
   113807   WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
   113808   WhereTerm *pTerm;               /* A WHERE clause term */
   113809   Parse *pParse;                  /* Parsing context */
   113810   sqlite3 *db;                    /* Database connection */
   113811   Vdbe *v;                        /* The prepared stmt under constructions */
   113812   struct SrcList_item *pTabItem;  /* FROM clause term being coded */
   113813   int addrBrk;                    /* Jump here to break out of the loop */
   113814   int addrCont;                   /* Jump here to continue with next cycle */
   113815   int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
   113816   int iReleaseReg = 0;      /* Temp register to free before returning */
   113817 
   113818   pParse = pWInfo->pParse;
   113819   v = pParse->pVdbe;
   113820   pWC = &pWInfo->sWC;
   113821   db = pParse->db;
   113822   pLevel = &pWInfo->a[iLevel];
   113823   pLoop = pLevel->pWLoop;
   113824   pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
   113825   iCur = pTabItem->iCursor;
   113826   pLevel->notReady = notReady & ~getMask(&pWInfo->sMaskSet, iCur);
   113827   bRev = (pWInfo->revMask>>iLevel)&1;
   113828   omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
   113829            && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
   113830   VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
   113831 
   113832   /* Create labels for the "break" and "continue" instructions
   113833   ** for the current loop.  Jump to addrBrk to break out of a loop.
   113834   ** Jump to cont to go immediately to the next iteration of the
   113835   ** loop.
   113836   **
   113837   ** When there is an IN operator, we also have a "addrNxt" label that
   113838   ** means to continue with the next IN value combination.  When
   113839   ** there are no IN operators in the constraints, the "addrNxt" label
   113840   ** is the same as "addrBrk".
   113841   */
   113842   addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
   113843   addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
   113844 
   113845   /* If this is the right table of a LEFT OUTER JOIN, allocate and
   113846   ** initialize a memory cell that records if this table matches any
   113847   ** row of the left table of the join.
   113848   */
   113849   if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
   113850     pLevel->iLeftJoin = ++pParse->nMem;
   113851     sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
   113852     VdbeComment((v, "init LEFT JOIN no-match flag"));
   113853   }
   113854 
   113855   /* Special case of a FROM clause subquery implemented as a co-routine */
   113856   if( pTabItem->viaCoroutine ){
   113857     int regYield = pTabItem->regReturn;
   113858     sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
   113859     pLevel->p2 =  sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
   113860     VdbeCoverage(v);
   113861     VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
   113862     pLevel->op = OP_Goto;
   113863   }else
   113864 
   113865 #ifndef SQLITE_OMIT_VIRTUALTABLE
   113866   if(  (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
   113867     /* Case 1:  The table is a virtual-table.  Use the VFilter and VNext
   113868     **          to access the data.
   113869     */
   113870     int iReg;   /* P3 Value for OP_VFilter */
   113871     int addrNotFound;
   113872     int nConstraint = pLoop->nLTerm;
   113873 
   113874     sqlite3ExprCachePush(pParse);
   113875     iReg = sqlite3GetTempRange(pParse, nConstraint+2);
   113876     addrNotFound = pLevel->addrBrk;
   113877     for(j=0; j<nConstraint; j++){
   113878       int iTarget = iReg+j+2;
   113879       pTerm = pLoop->aLTerm[j];
   113880       if( pTerm==0 ) continue;
   113881       if( pTerm->eOperator & WO_IN ){
   113882         codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
   113883         addrNotFound = pLevel->addrNxt;
   113884       }else{
   113885         sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
   113886       }
   113887     }
   113888     sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
   113889     sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
   113890     sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
   113891                       pLoop->u.vtab.idxStr,
   113892                       pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
   113893     VdbeCoverage(v);
   113894     pLoop->u.vtab.needFree = 0;
   113895     for(j=0; j<nConstraint && j<16; j++){
   113896       if( (pLoop->u.vtab.omitMask>>j)&1 ){
   113897         disableTerm(pLevel, pLoop->aLTerm[j]);
   113898       }
   113899     }
   113900     pLevel->op = OP_VNext;
   113901     pLevel->p1 = iCur;
   113902     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
   113903     sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
   113904     sqlite3ExprCachePop(pParse);
   113905   }else
   113906 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   113907 
   113908   if( (pLoop->wsFlags & WHERE_IPK)!=0
   113909    && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
   113910   ){
   113911     /* Case 2:  We can directly reference a single row using an
   113912     **          equality comparison against the ROWID field.  Or
   113913     **          we reference multiple rows using a "rowid IN (...)"
   113914     **          construct.
   113915     */
   113916     assert( pLoop->u.btree.nEq==1 );
   113917     pTerm = pLoop->aLTerm[0];
   113918     assert( pTerm!=0 );
   113919     assert( pTerm->pExpr!=0 );
   113920     assert( omitTable==0 );
   113921     testcase( pTerm->wtFlags & TERM_VIRTUAL );
   113922     iReleaseReg = ++pParse->nMem;
   113923     iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
   113924     if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
   113925     addrNxt = pLevel->addrNxt;
   113926     sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt); VdbeCoverage(v);
   113927     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
   113928     VdbeCoverage(v);
   113929     sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
   113930     sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
   113931     VdbeComment((v, "pk"));
   113932     pLevel->op = OP_Noop;
   113933   }else if( (pLoop->wsFlags & WHERE_IPK)!=0
   113934          && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
   113935   ){
   113936     /* Case 3:  We have an inequality comparison against the ROWID field.
   113937     */
   113938     int testOp = OP_Noop;
   113939     int start;
   113940     int memEndValue = 0;
   113941     WhereTerm *pStart, *pEnd;
   113942 
   113943     assert( omitTable==0 );
   113944     j = 0;
   113945     pStart = pEnd = 0;
   113946     if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
   113947     if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
   113948     assert( pStart!=0 || pEnd!=0 );
   113949     if( bRev ){
   113950       pTerm = pStart;
   113951       pStart = pEnd;
   113952       pEnd = pTerm;
   113953     }
   113954     if( pStart ){
   113955       Expr *pX;             /* The expression that defines the start bound */
   113956       int r1, rTemp;        /* Registers for holding the start boundary */
   113957 
   113958       /* The following constant maps TK_xx codes into corresponding
   113959       ** seek opcodes.  It depends on a particular ordering of TK_xx
   113960       */
   113961       const u8 aMoveOp[] = {
   113962            /* TK_GT */  OP_SeekGT,
   113963            /* TK_LE */  OP_SeekLE,
   113964            /* TK_LT */  OP_SeekLT,
   113965            /* TK_GE */  OP_SeekGE
   113966       };
   113967       assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
   113968       assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
   113969       assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
   113970 
   113971       assert( (pStart->wtFlags & TERM_VNULL)==0 );
   113972       testcase( pStart->wtFlags & TERM_VIRTUAL );
   113973       pX = pStart->pExpr;
   113974       assert( pX!=0 );
   113975       testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
   113976       r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
   113977       sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
   113978       VdbeComment((v, "pk"));
   113979       VdbeCoverageIf(v, pX->op==TK_GT);
   113980       VdbeCoverageIf(v, pX->op==TK_LE);
   113981       VdbeCoverageIf(v, pX->op==TK_LT);
   113982       VdbeCoverageIf(v, pX->op==TK_GE);
   113983       sqlite3ExprCacheAffinityChange(pParse, r1, 1);
   113984       sqlite3ReleaseTempReg(pParse, rTemp);
   113985       disableTerm(pLevel, pStart);
   113986     }else{
   113987       sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
   113988       VdbeCoverageIf(v, bRev==0);
   113989       VdbeCoverageIf(v, bRev!=0);
   113990     }
   113991     if( pEnd ){
   113992       Expr *pX;
   113993       pX = pEnd->pExpr;
   113994       assert( pX!=0 );
   113995       assert( (pEnd->wtFlags & TERM_VNULL)==0 );
   113996       testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
   113997       testcase( pEnd->wtFlags & TERM_VIRTUAL );
   113998       memEndValue = ++pParse->nMem;
   113999       sqlite3ExprCode(pParse, pX->pRight, memEndValue);
   114000       if( pX->op==TK_LT || pX->op==TK_GT ){
   114001         testOp = bRev ? OP_Le : OP_Ge;
   114002       }else{
   114003         testOp = bRev ? OP_Lt : OP_Gt;
   114004       }
   114005       disableTerm(pLevel, pEnd);
   114006     }
   114007     start = sqlite3VdbeCurrentAddr(v);
   114008     pLevel->op = bRev ? OP_Prev : OP_Next;
   114009     pLevel->p1 = iCur;
   114010     pLevel->p2 = start;
   114011     assert( pLevel->p5==0 );
   114012     if( testOp!=OP_Noop ){
   114013       iRowidReg = ++pParse->nMem;
   114014       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
   114015       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
   114016       sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
   114017       VdbeCoverageIf(v, testOp==OP_Le);
   114018       VdbeCoverageIf(v, testOp==OP_Lt);
   114019       VdbeCoverageIf(v, testOp==OP_Ge);
   114020       VdbeCoverageIf(v, testOp==OP_Gt);
   114021       sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
   114022     }
   114023   }else if( pLoop->wsFlags & WHERE_INDEXED ){
   114024     /* Case 4: A scan using an index.
   114025     **
   114026     **         The WHERE clause may contain zero or more equality
   114027     **         terms ("==" or "IN" operators) that refer to the N
   114028     **         left-most columns of the index. It may also contain
   114029     **         inequality constraints (>, <, >= or <=) on the indexed
   114030     **         column that immediately follows the N equalities. Only
   114031     **         the right-most column can be an inequality - the rest must
   114032     **         use the "==" and "IN" operators. For example, if the
   114033     **         index is on (x,y,z), then the following clauses are all
   114034     **         optimized:
   114035     **
   114036     **            x=5
   114037     **            x=5 AND y=10
   114038     **            x=5 AND y<10
   114039     **            x=5 AND y>5 AND y<10
   114040     **            x=5 AND y=5 AND z<=10
   114041     **
   114042     **         The z<10 term of the following cannot be used, only
   114043     **         the x=5 term:
   114044     **
   114045     **            x=5 AND z<10
   114046     **
   114047     **         N may be zero if there are inequality constraints.
   114048     **         If there are no inequality constraints, then N is at
   114049     **         least one.
   114050     **
   114051     **         This case is also used when there are no WHERE clause
   114052     **         constraints but an index is selected anyway, in order
   114053     **         to force the output order to conform to an ORDER BY.
   114054     */
   114055     static const u8 aStartOp[] = {
   114056       0,
   114057       0,
   114058       OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
   114059       OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
   114060       OP_SeekGT,           /* 4: (start_constraints  && !startEq && !bRev) */
   114061       OP_SeekLT,           /* 5: (start_constraints  && !startEq &&  bRev) */
   114062       OP_SeekGE,           /* 6: (start_constraints  &&  startEq && !bRev) */
   114063       OP_SeekLE            /* 7: (start_constraints  &&  startEq &&  bRev) */
   114064     };
   114065     static const u8 aEndOp[] = {
   114066       OP_IdxGE,            /* 0: (end_constraints && !bRev && !endEq) */
   114067       OP_IdxGT,            /* 1: (end_constraints && !bRev &&  endEq) */
   114068       OP_IdxLE,            /* 2: (end_constraints &&  bRev && !endEq) */
   114069       OP_IdxLT,            /* 3: (end_constraints &&  bRev &&  endEq) */
   114070     };
   114071     u16 nEq = pLoop->u.btree.nEq;     /* Number of == or IN terms */
   114072     int regBase;                 /* Base register holding constraint values */
   114073     WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
   114074     WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
   114075     int startEq;                 /* True if range start uses ==, >= or <= */
   114076     int endEq;                   /* True if range end uses ==, >= or <= */
   114077     int start_constraints;       /* Start of range is constrained */
   114078     int nConstraint;             /* Number of constraint terms */
   114079     Index *pIdx;                 /* The index we will be using */
   114080     int iIdxCur;                 /* The VDBE cursor for the index */
   114081     int nExtraReg = 0;           /* Number of extra registers needed */
   114082     int op;                      /* Instruction opcode */
   114083     char *zStartAff;             /* Affinity for start of range constraint */
   114084     char cEndAff = 0;            /* Affinity for end of range constraint */
   114085     u8 bSeekPastNull = 0;        /* True to seek past initial nulls */
   114086     u8 bStopAtNull = 0;          /* Add condition to terminate at NULLs */
   114087 
   114088     pIdx = pLoop->u.btree.pIndex;
   114089     iIdxCur = pLevel->iIdxCur;
   114090     assert( nEq>=pLoop->u.btree.nSkip );
   114091 
   114092     /* If this loop satisfies a sort order (pOrderBy) request that
   114093     ** was passed to this function to implement a "SELECT min(x) ..."
   114094     ** query, then the caller will only allow the loop to run for
   114095     ** a single iteration. This means that the first row returned
   114096     ** should not have a NULL value stored in 'x'. If column 'x' is
   114097     ** the first one after the nEq equality constraints in the index,
   114098     ** this requires some special handling.
   114099     */
   114100     assert( pWInfo->pOrderBy==0
   114101          || pWInfo->pOrderBy->nExpr==1
   114102          || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
   114103     if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
   114104      && pWInfo->nOBSat>0
   114105      && (pIdx->nKeyCol>nEq)
   114106     ){
   114107       assert( pLoop->u.btree.nSkip==0 );
   114108       bSeekPastNull = 1;
   114109       nExtraReg = 1;
   114110     }
   114111 
   114112     /* Find any inequality constraint terms for the start and end
   114113     ** of the range.
   114114     */
   114115     j = nEq;
   114116     if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
   114117       pRangeStart = pLoop->aLTerm[j++];
   114118       nExtraReg = 1;
   114119     }
   114120     if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
   114121       pRangeEnd = pLoop->aLTerm[j++];
   114122       nExtraReg = 1;
   114123       if( pRangeStart==0
   114124        && (j = pIdx->aiColumn[nEq])>=0
   114125        && pIdx->pTable->aCol[j].notNull==0
   114126       ){
   114127         bSeekPastNull = 1;
   114128       }
   114129     }
   114130     assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
   114131 
   114132     /* Generate code to evaluate all constraint terms using == or IN
   114133     ** and store the values of those terms in an array of registers
   114134     ** starting at regBase.
   114135     */
   114136     regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
   114137     assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
   114138     if( zStartAff ) cEndAff = zStartAff[nEq];
   114139     addrNxt = pLevel->addrNxt;
   114140 
   114141     /* If we are doing a reverse order scan on an ascending index, or
   114142     ** a forward order scan on a descending index, interchange the
   114143     ** start and end terms (pRangeStart and pRangeEnd).
   114144     */
   114145     if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
   114146      || (bRev && pIdx->nKeyCol==nEq)
   114147     ){
   114148       SWAP(WhereTerm *, pRangeEnd, pRangeStart);
   114149       SWAP(u8, bSeekPastNull, bStopAtNull);
   114150     }
   114151 
   114152     testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
   114153     testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
   114154     testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
   114155     testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
   114156     startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
   114157     endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
   114158     start_constraints = pRangeStart || nEq>0;
   114159 
   114160     /* Seek the index cursor to the start of the range. */
   114161     nConstraint = nEq;
   114162     if( pRangeStart ){
   114163       Expr *pRight = pRangeStart->pExpr->pRight;
   114164       sqlite3ExprCode(pParse, pRight, regBase+nEq);
   114165       if( (pRangeStart->wtFlags & TERM_VNULL)==0
   114166        && sqlite3ExprCanBeNull(pRight)
   114167       ){
   114168         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
   114169         VdbeCoverage(v);
   114170       }
   114171       if( zStartAff ){
   114172         if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
   114173           /* Since the comparison is to be performed with no conversions
   114174           ** applied to the operands, set the affinity to apply to pRight to
   114175           ** SQLITE_AFF_NONE.  */
   114176           zStartAff[nEq] = SQLITE_AFF_NONE;
   114177         }
   114178         if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
   114179           zStartAff[nEq] = SQLITE_AFF_NONE;
   114180         }
   114181       }
   114182       nConstraint++;
   114183       testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
   114184     }else if( bSeekPastNull ){
   114185       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
   114186       nConstraint++;
   114187       startEq = 0;
   114188       start_constraints = 1;
   114189     }
   114190     codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
   114191     op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
   114192     assert( op!=0 );
   114193     sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
   114194     VdbeCoverage(v);
   114195     VdbeCoverageIf(v, op==OP_Rewind);  testcase( op==OP_Rewind );
   114196     VdbeCoverageIf(v, op==OP_Last);    testcase( op==OP_Last );
   114197     VdbeCoverageIf(v, op==OP_SeekGT);  testcase( op==OP_SeekGT );
   114198     VdbeCoverageIf(v, op==OP_SeekGE);  testcase( op==OP_SeekGE );
   114199     VdbeCoverageIf(v, op==OP_SeekLE);  testcase( op==OP_SeekLE );
   114200     VdbeCoverageIf(v, op==OP_SeekLT);  testcase( op==OP_SeekLT );
   114201 
   114202     /* Load the value for the inequality constraint at the end of the
   114203     ** range (if any).
   114204     */
   114205     nConstraint = nEq;
   114206     if( pRangeEnd ){
   114207       Expr *pRight = pRangeEnd->pExpr->pRight;
   114208       sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
   114209       sqlite3ExprCode(pParse, pRight, regBase+nEq);
   114210       if( (pRangeEnd->wtFlags & TERM_VNULL)==0
   114211        && sqlite3ExprCanBeNull(pRight)
   114212       ){
   114213         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
   114214         VdbeCoverage(v);
   114215       }
   114216       if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_NONE
   114217        && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff)
   114218       ){
   114219         codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff);
   114220       }
   114221       nConstraint++;
   114222       testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
   114223     }else if( bStopAtNull ){
   114224       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
   114225       endEq = 0;
   114226       nConstraint++;
   114227     }
   114228     sqlite3DbFree(db, zStartAff);
   114229 
   114230     /* Top of the loop body */
   114231     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
   114232 
   114233     /* Check if the index cursor is past the end of the range. */
   114234     if( nConstraint ){
   114235       op = aEndOp[bRev*2 + endEq];
   114236       sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
   114237       testcase( op==OP_IdxGT );  VdbeCoverageIf(v, op==OP_IdxGT );
   114238       testcase( op==OP_IdxGE );  VdbeCoverageIf(v, op==OP_IdxGE );
   114239       testcase( op==OP_IdxLT );  VdbeCoverageIf(v, op==OP_IdxLT );
   114240       testcase( op==OP_IdxLE );  VdbeCoverageIf(v, op==OP_IdxLE );
   114241     }
   114242 
   114243     /* Seek the table cursor, if required */
   114244     disableTerm(pLevel, pRangeStart);
   114245     disableTerm(pLevel, pRangeEnd);
   114246     if( omitTable ){
   114247       /* pIdx is a covering index.  No need to access the main table. */
   114248     }else if( HasRowid(pIdx->pTable) ){
   114249       iRowidReg = ++pParse->nMem;
   114250       sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
   114251       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
   114252       sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
   114253     }else if( iCur!=iIdxCur ){
   114254       Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
   114255       iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
   114256       for(j=0; j<pPk->nKeyCol; j++){
   114257         k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
   114258         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
   114259       }
   114260       sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
   114261                            iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
   114262     }
   114263 
   114264     /* Record the instruction used to terminate the loop. Disable
   114265     ** WHERE clause terms made redundant by the index range scan.
   114266     */
   114267     if( pLoop->wsFlags & WHERE_ONEROW ){
   114268       pLevel->op = OP_Noop;
   114269     }else if( bRev ){
   114270       pLevel->op = OP_Prev;
   114271     }else{
   114272       pLevel->op = OP_Next;
   114273     }
   114274     pLevel->p1 = iIdxCur;
   114275     pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
   114276     if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
   114277       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
   114278     }else{
   114279       assert( pLevel->p5==0 );
   114280     }
   114281   }else
   114282 
   114283 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
   114284   if( pLoop->wsFlags & WHERE_MULTI_OR ){
   114285     /* Case 5:  Two or more separately indexed terms connected by OR
   114286     **
   114287     ** Example:
   114288     **
   114289     **   CREATE TABLE t1(a,b,c,d);
   114290     **   CREATE INDEX i1 ON t1(a);
   114291     **   CREATE INDEX i2 ON t1(b);
   114292     **   CREATE INDEX i3 ON t1(c);
   114293     **
   114294     **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
   114295     **
   114296     ** In the example, there are three indexed terms connected by OR.
   114297     ** The top of the loop looks like this:
   114298     **
   114299     **          Null       1                # Zero the rowset in reg 1
   114300     **
   114301     ** Then, for each indexed term, the following. The arguments to
   114302     ** RowSetTest are such that the rowid of the current row is inserted
   114303     ** into the RowSet. If it is already present, control skips the
   114304     ** Gosub opcode and jumps straight to the code generated by WhereEnd().
   114305     **
   114306     **        sqlite3WhereBegin(<term>)
   114307     **          RowSetTest                  # Insert rowid into rowset
   114308     **          Gosub      2 A
   114309     **        sqlite3WhereEnd()
   114310     **
   114311     ** Following the above, code to terminate the loop. Label A, the target
   114312     ** of the Gosub above, jumps to the instruction right after the Goto.
   114313     **
   114314     **          Null       1                # Zero the rowset in reg 1
   114315     **          Goto       B                # The loop is finished.
   114316     **
   114317     **       A: <loop body>                 # Return data, whatever.
   114318     **
   114319     **          Return     2                # Jump back to the Gosub
   114320     **
   114321     **       B: <after the loop>
   114322     **
   114323     ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
   114324     ** use an ephermeral index instead of a RowSet to record the primary
   114325     ** keys of the rows we have already seen.
   114326     **
   114327     */
   114328     WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
   114329     SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
   114330     Index *pCov = 0;             /* Potential covering index (or NULL) */
   114331     int iCovCur = pParse->nTab++;  /* Cursor used for index scans (if any) */
   114332 
   114333     int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
   114334     int regRowset = 0;                        /* Register for RowSet object */
   114335     int regRowid = 0;                         /* Register holding rowid */
   114336     int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
   114337     int iRetInit;                             /* Address of regReturn init */
   114338     int untestedTerms = 0;             /* Some terms not completely tested */
   114339     int ii;                            /* Loop counter */
   114340     u16 wctrlFlags;                    /* Flags for sub-WHERE clause */
   114341     Expr *pAndExpr = 0;                /* An ".. AND (...)" expression */
   114342     Table *pTab = pTabItem->pTab;
   114343 
   114344     pTerm = pLoop->aLTerm[0];
   114345     assert( pTerm!=0 );
   114346     assert( pTerm->eOperator & WO_OR );
   114347     assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
   114348     pOrWc = &pTerm->u.pOrInfo->wc;
   114349     pLevel->op = OP_Return;
   114350     pLevel->p1 = regReturn;
   114351 
   114352     /* Set up a new SrcList in pOrTab containing the table being scanned
   114353     ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
   114354     ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
   114355     */
   114356     if( pWInfo->nLevel>1 ){
   114357       int nNotReady;                 /* The number of notReady tables */
   114358       struct SrcList_item *origSrc;     /* Original list of tables */
   114359       nNotReady = pWInfo->nLevel - iLevel - 1;
   114360       pOrTab = sqlite3StackAllocRaw(db,
   114361                             sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
   114362       if( pOrTab==0 ) return notReady;
   114363       pOrTab->nAlloc = (u8)(nNotReady + 1);
   114364       pOrTab->nSrc = pOrTab->nAlloc;
   114365       memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
   114366       origSrc = pWInfo->pTabList->a;
   114367       for(k=1; k<=nNotReady; k++){
   114368         memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
   114369       }
   114370     }else{
   114371       pOrTab = pWInfo->pTabList;
   114372     }
   114373 
   114374     /* Initialize the rowset register to contain NULL. An SQL NULL is
   114375     ** equivalent to an empty rowset.  Or, create an ephermeral index
   114376     ** capable of holding primary keys in the case of a WITHOUT ROWID.
   114377     **
   114378     ** Also initialize regReturn to contain the address of the instruction
   114379     ** immediately following the OP_Return at the bottom of the loop. This
   114380     ** is required in a few obscure LEFT JOIN cases where control jumps
   114381     ** over the top of the loop into the body of it. In this case the
   114382     ** correct response for the end-of-loop code (the OP_Return) is to
   114383     ** fall through to the next instruction, just as an OP_Next does if
   114384     ** called on an uninitialized cursor.
   114385     */
   114386     if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
   114387       if( HasRowid(pTab) ){
   114388         regRowset = ++pParse->nMem;
   114389         sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
   114390       }else{
   114391         Index *pPk = sqlite3PrimaryKeyIndex(pTab);
   114392         regRowset = pParse->nTab++;
   114393         sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
   114394         sqlite3VdbeSetP4KeyInfo(pParse, pPk);
   114395       }
   114396       regRowid = ++pParse->nMem;
   114397     }
   114398     iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
   114399 
   114400     /* If the original WHERE clause is z of the form:  (x1 OR x2 OR ...) AND y
   114401     ** Then for every term xN, evaluate as the subexpression: xN AND z
   114402     ** That way, terms in y that are factored into the disjunction will
   114403     ** be picked up by the recursive calls to sqlite3WhereBegin() below.
   114404     **
   114405     ** Actually, each subexpression is converted to "xN AND w" where w is
   114406     ** the "interesting" terms of z - terms that did not originate in the
   114407     ** ON or USING clause of a LEFT JOIN, and terms that are usable as
   114408     ** indices.
   114409     **
   114410     ** This optimization also only applies if the (x1 OR x2 OR ...) term
   114411     ** is not contained in the ON clause of a LEFT JOIN.
   114412     ** See ticket http://www.sqlite.org/src/info/f2369304e4
   114413     */
   114414     if( pWC->nTerm>1 ){
   114415       int iTerm;
   114416       for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
   114417         Expr *pExpr = pWC->a[iTerm].pExpr;
   114418         if( &pWC->a[iTerm] == pTerm ) continue;
   114419         if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
   114420         testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
   114421         testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
   114422         if( pWC->a[iTerm].wtFlags & (TERM_ORINFO|TERM_VIRTUAL) ) continue;
   114423         if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
   114424         pExpr = sqlite3ExprDup(db, pExpr, 0);
   114425         pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
   114426       }
   114427       if( pAndExpr ){
   114428         pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
   114429       }
   114430     }
   114431 
   114432     /* Run a separate WHERE clause for each term of the OR clause.  After
   114433     ** eliminating duplicates from other WHERE clauses, the action for each
   114434     ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
   114435     */
   114436     wctrlFlags =  WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
   114437                   WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY;
   114438     for(ii=0; ii<pOrWc->nTerm; ii++){
   114439       WhereTerm *pOrTerm = &pOrWc->a[ii];
   114440       if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
   114441         WhereInfo *pSubWInfo;           /* Info for single OR-term scan */
   114442         Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
   114443         int j1 = 0;                     /* Address of jump operation */
   114444         if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
   114445           pAndExpr->pLeft = pOrExpr;
   114446           pOrExpr = pAndExpr;
   114447         }
   114448         /* Loop through table entries that match term pOrTerm. */
   114449         pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
   114450                                       wctrlFlags, iCovCur);
   114451         assert( pSubWInfo || pParse->nErr || db->mallocFailed );
   114452         if( pSubWInfo ){
   114453           WhereLoop *pSubLoop;
   114454           explainOneScan(
   114455               pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
   114456           );
   114457           /* This is the sub-WHERE clause body.  First skip over
   114458           ** duplicate rows from prior sub-WHERE clauses, and record the
   114459           ** rowid (or PRIMARY KEY) for the current row so that the same
   114460           ** row will be skipped in subsequent sub-WHERE clauses.
   114461           */
   114462           if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
   114463             int r;
   114464             int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
   114465             if( HasRowid(pTab) ){
   114466               r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0);
   114467               j1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0, r,iSet);
   114468               VdbeCoverage(v);
   114469             }else{
   114470               Index *pPk = sqlite3PrimaryKeyIndex(pTab);
   114471               int nPk = pPk->nKeyCol;
   114472               int iPk;
   114473 
   114474               /* Read the PK into an array of temp registers. */
   114475               r = sqlite3GetTempRange(pParse, nPk);
   114476               for(iPk=0; iPk<nPk; iPk++){
   114477                 int iCol = pPk->aiColumn[iPk];
   114478                 sqlite3ExprCodeGetColumn(pParse, pTab, iCol, iCur, r+iPk, 0);
   114479               }
   114480 
   114481               /* Check if the temp table already contains this key. If so,
   114482               ** the row has already been included in the result set and
   114483               ** can be ignored (by jumping past the Gosub below). Otherwise,
   114484               ** insert the key into the temp table and proceed with processing
   114485               ** the row.
   114486               **
   114487               ** Use some of the same optimizations as OP_RowSetTest: If iSet
   114488               ** is zero, assume that the key cannot already be present in
   114489               ** the temp table. And if iSet is -1, assume that there is no
   114490               ** need to insert the key into the temp table, as it will never
   114491               ** be tested for.  */
   114492               if( iSet ){
   114493                 j1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
   114494                 VdbeCoverage(v);
   114495               }
   114496               if( iSet>=0 ){
   114497                 sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
   114498                 sqlite3VdbeAddOp3(v, OP_IdxInsert, regRowset, regRowid, 0);
   114499                 if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
   114500               }
   114501 
   114502               /* Release the array of temp registers */
   114503               sqlite3ReleaseTempRange(pParse, r, nPk);
   114504             }
   114505           }
   114506 
   114507           /* Invoke the main loop body as a subroutine */
   114508           sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
   114509 
   114510           /* Jump here (skipping the main loop body subroutine) if the
   114511           ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
   114512           if( j1 ) sqlite3VdbeJumpHere(v, j1);
   114513 
   114514           /* The pSubWInfo->untestedTerms flag means that this OR term
   114515           ** contained one or more AND term from a notReady table.  The
   114516           ** terms from the notReady table could not be tested and will
   114517           ** need to be tested later.
   114518           */
   114519           if( pSubWInfo->untestedTerms ) untestedTerms = 1;
   114520 
   114521           /* If all of the OR-connected terms are optimized using the same
   114522           ** index, and the index is opened using the same cursor number
   114523           ** by each call to sqlite3WhereBegin() made by this loop, it may
   114524           ** be possible to use that index as a covering index.
   114525           **
   114526           ** If the call to sqlite3WhereBegin() above resulted in a scan that
   114527           ** uses an index, and this is either the first OR-connected term
   114528           ** processed or the index is the same as that used by all previous
   114529           ** terms, set pCov to the candidate covering index. Otherwise, set
   114530           ** pCov to NULL to indicate that no candidate covering index will
   114531           ** be available.
   114532           */
   114533           pSubLoop = pSubWInfo->a[0].pWLoop;
   114534           assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
   114535           if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
   114536            && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
   114537            && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
   114538           ){
   114539             assert( pSubWInfo->a[0].iIdxCur==iCovCur );
   114540             pCov = pSubLoop->u.btree.pIndex;
   114541             wctrlFlags |= WHERE_REOPEN_IDX;
   114542           }else{
   114543             pCov = 0;
   114544           }
   114545 
   114546           /* Finish the loop through table entries that match term pOrTerm. */
   114547           sqlite3WhereEnd(pSubWInfo);
   114548         }
   114549       }
   114550     }
   114551     pLevel->u.pCovidx = pCov;
   114552     if( pCov ) pLevel->iIdxCur = iCovCur;
   114553     if( pAndExpr ){
   114554       pAndExpr->pLeft = 0;
   114555       sqlite3ExprDelete(db, pAndExpr);
   114556     }
   114557     sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
   114558     sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
   114559     sqlite3VdbeResolveLabel(v, iLoopBody);
   114560 
   114561     if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
   114562     if( !untestedTerms ) disableTerm(pLevel, pTerm);
   114563   }else
   114564 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
   114565 
   114566   {
   114567     /* Case 6:  There is no usable index.  We must do a complete
   114568     **          scan of the entire table.
   114569     */
   114570     static const u8 aStep[] = { OP_Next, OP_Prev };
   114571     static const u8 aStart[] = { OP_Rewind, OP_Last };
   114572     assert( bRev==0 || bRev==1 );
   114573     if( pTabItem->isRecursive ){
   114574       /* Tables marked isRecursive have only a single row that is stored in
   114575       ** a pseudo-cursor.  No need to Rewind or Next such cursors. */
   114576       pLevel->op = OP_Noop;
   114577     }else{
   114578       pLevel->op = aStep[bRev];
   114579       pLevel->p1 = iCur;
   114580       pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
   114581       VdbeCoverageIf(v, bRev==0);
   114582       VdbeCoverageIf(v, bRev!=0);
   114583       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
   114584     }
   114585   }
   114586 
   114587   /* Insert code to test every subexpression that can be completely
   114588   ** computed using the current set of tables.
   114589   */
   114590   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
   114591     Expr *pE;
   114592     testcase( pTerm->wtFlags & TERM_VIRTUAL );
   114593     testcase( pTerm->wtFlags & TERM_CODED );
   114594     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
   114595     if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
   114596       testcase( pWInfo->untestedTerms==0
   114597                && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
   114598       pWInfo->untestedTerms = 1;
   114599       continue;
   114600     }
   114601     pE = pTerm->pExpr;
   114602     assert( pE!=0 );
   114603     if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
   114604       continue;
   114605     }
   114606     sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
   114607     pTerm->wtFlags |= TERM_CODED;
   114608   }
   114609 
   114610   /* Insert code to test for implied constraints based on transitivity
   114611   ** of the "==" operator.
   114612   **
   114613   ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
   114614   ** and we are coding the t1 loop and the t2 loop has not yet coded,
   114615   ** then we cannot use the "t1.a=t2.b" constraint, but we can code
   114616   ** the implied "t1.a=123" constraint.
   114617   */
   114618   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
   114619     Expr *pE, *pEAlt;
   114620     WhereTerm *pAlt;
   114621     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
   114622     if( pTerm->eOperator!=(WO_EQUIV|WO_EQ) ) continue;
   114623     if( pTerm->leftCursor!=iCur ) continue;
   114624     if( pLevel->iLeftJoin ) continue;
   114625     pE = pTerm->pExpr;
   114626     assert( !ExprHasProperty(pE, EP_FromJoin) );
   114627     assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
   114628     pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0);
   114629     if( pAlt==0 ) continue;
   114630     if( pAlt->wtFlags & (TERM_CODED) ) continue;
   114631     testcase( pAlt->eOperator & WO_EQ );
   114632     testcase( pAlt->eOperator & WO_IN );
   114633     VdbeModuleComment((v, "begin transitive constraint"));
   114634     pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
   114635     if( pEAlt ){
   114636       *pEAlt = *pAlt->pExpr;
   114637       pEAlt->pLeft = pE->pLeft;
   114638       sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
   114639       sqlite3StackFree(db, pEAlt);
   114640     }
   114641   }
   114642 
   114643   /* For a LEFT OUTER JOIN, generate code that will record the fact that
   114644   ** at least one row of the right table has matched the left table.
   114645   */
   114646   if( pLevel->iLeftJoin ){
   114647     pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
   114648     sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
   114649     VdbeComment((v, "record LEFT JOIN hit"));
   114650     sqlite3ExprCacheClear(pParse);
   114651     for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
   114652       testcase( pTerm->wtFlags & TERM_VIRTUAL );
   114653       testcase( pTerm->wtFlags & TERM_CODED );
   114654       if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
   114655       if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
   114656         assert( pWInfo->untestedTerms );
   114657         continue;
   114658       }
   114659       assert( pTerm->pExpr );
   114660       sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
   114661       pTerm->wtFlags |= TERM_CODED;
   114662     }
   114663   }
   114664 
   114665   return pLevel->notReady;
   114666 }
   114667 
   114668 #if defined(WHERETRACE_ENABLED) && defined(SQLITE_ENABLE_TREE_EXPLAIN)
   114669 /*
   114670 ** Generate "Explanation" text for a WhereTerm.
   114671 */
   114672 static void whereExplainTerm(Vdbe *v, WhereTerm *pTerm){
   114673   char zType[4];
   114674   memcpy(zType, "...", 4);
   114675   if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
   114676   if( pTerm->eOperator & WO_EQUIV  ) zType[1] = 'E';
   114677   if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
   114678   sqlite3ExplainPrintf(v, "%s ", zType);
   114679   sqlite3ExplainExpr(v, pTerm->pExpr);
   114680 }
   114681 #endif /* WHERETRACE_ENABLED && SQLITE_ENABLE_TREE_EXPLAIN */
   114682 
   114683 
   114684 #ifdef WHERETRACE_ENABLED
   114685 /*
   114686 ** Print a WhereLoop object for debugging purposes
   114687 */
   114688 static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
   114689   WhereInfo *pWInfo = pWC->pWInfo;
   114690   int nb = 1+(pWInfo->pTabList->nSrc+7)/8;
   114691   struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
   114692   Table *pTab = pItem->pTab;
   114693   sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
   114694                      p->iTab, nb, p->maskSelf, nb, p->prereq);
   114695   sqlite3DebugPrintf(" %12s",
   114696                      pItem->zAlias ? pItem->zAlias : pTab->zName);
   114697   if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
   114698      const char *zName;
   114699      if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
   114700       if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
   114701         int i = sqlite3Strlen30(zName) - 1;
   114702         while( zName[i]!='_' ) i--;
   114703         zName += i;
   114704       }
   114705       sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
   114706     }else{
   114707       sqlite3DebugPrintf("%20s","");
   114708     }
   114709   }else{
   114710     char *z;
   114711     if( p->u.vtab.idxStr ){
   114712       z = sqlite3_mprintf("(%d,\"%s\",%x)",
   114713                 p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
   114714     }else{
   114715       z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
   114716     }
   114717     sqlite3DebugPrintf(" %-19s", z);
   114718     sqlite3_free(z);
   114719   }
   114720   sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
   114721   sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
   114722 #ifdef SQLITE_ENABLE_TREE_EXPLAIN
   114723   /* If the 0x100 bit of wheretracing is set, then show all of the constraint
   114724   ** expressions in the WhereLoop.aLTerm[] array.
   114725   */
   114726   if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){  /* WHERETRACE 0x100 */
   114727     int i;
   114728     Vdbe *v = pWInfo->pParse->pVdbe;
   114729     sqlite3ExplainBegin(v);
   114730     for(i=0; i<p->nLTerm; i++){
   114731       WhereTerm *pTerm = p->aLTerm[i];
   114732       if( pTerm==0 ) continue;
   114733       sqlite3ExplainPrintf(v, "  (%d) #%-2d ", i+1, (int)(pTerm-pWC->a));
   114734       sqlite3ExplainPush(v);
   114735       whereExplainTerm(v, pTerm);
   114736       sqlite3ExplainPop(v);
   114737       sqlite3ExplainNL(v);
   114738     }
   114739     sqlite3ExplainFinish(v);
   114740     sqlite3DebugPrintf("%s", sqlite3VdbeExplanation(v));
   114741   }
   114742 #endif
   114743 }
   114744 #endif
   114745 
   114746 /*
   114747 ** Convert bulk memory into a valid WhereLoop that can be passed
   114748 ** to whereLoopClear harmlessly.
   114749 */
   114750 static void whereLoopInit(WhereLoop *p){
   114751   p->aLTerm = p->aLTermSpace;
   114752   p->nLTerm = 0;
   114753   p->nLSlot = ArraySize(p->aLTermSpace);
   114754   p->wsFlags = 0;
   114755 }
   114756 
   114757 /*
   114758 ** Clear the WhereLoop.u union.  Leave WhereLoop.pLTerm intact.
   114759 */
   114760 static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
   114761   if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
   114762     if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
   114763       sqlite3_free(p->u.vtab.idxStr);
   114764       p->u.vtab.needFree = 0;
   114765       p->u.vtab.idxStr = 0;
   114766     }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
   114767       sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
   114768       sqlite3KeyInfoUnref(p->u.btree.pIndex->pKeyInfo);
   114769       sqlite3DbFree(db, p->u.btree.pIndex);
   114770       p->u.btree.pIndex = 0;
   114771     }
   114772   }
   114773 }
   114774 
   114775 /*
   114776 ** Deallocate internal memory used by a WhereLoop object
   114777 */
   114778 static void whereLoopClear(sqlite3 *db, WhereLoop *p){
   114779   if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
   114780   whereLoopClearUnion(db, p);
   114781   whereLoopInit(p);
   114782 }
   114783 
   114784 /*
   114785 ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
   114786 */
   114787 static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
   114788   WhereTerm **paNew;
   114789   if( p->nLSlot>=n ) return SQLITE_OK;
   114790   n = (n+7)&~7;
   114791   paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
   114792   if( paNew==0 ) return SQLITE_NOMEM;
   114793   memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
   114794   if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
   114795   p->aLTerm = paNew;
   114796   p->nLSlot = n;
   114797   return SQLITE_OK;
   114798 }
   114799 
   114800 /*
   114801 ** Transfer content from the second pLoop into the first.
   114802 */
   114803 static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
   114804   whereLoopClearUnion(db, pTo);
   114805   if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
   114806     memset(&pTo->u, 0, sizeof(pTo->u));
   114807     return SQLITE_NOMEM;
   114808   }
   114809   memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
   114810   memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
   114811   if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
   114812     pFrom->u.vtab.needFree = 0;
   114813   }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
   114814     pFrom->u.btree.pIndex = 0;
   114815   }
   114816   return SQLITE_OK;
   114817 }
   114818 
   114819 /*
   114820 ** Delete a WhereLoop object
   114821 */
   114822 static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
   114823   whereLoopClear(db, p);
   114824   sqlite3DbFree(db, p);
   114825 }
   114826 
   114827 /*
   114828 ** Free a WhereInfo structure
   114829 */
   114830 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
   114831   if( ALWAYS(pWInfo) ){
   114832     whereClauseClear(&pWInfo->sWC);
   114833     while( pWInfo->pLoops ){
   114834       WhereLoop *p = pWInfo->pLoops;
   114835       pWInfo->pLoops = p->pNextLoop;
   114836       whereLoopDelete(db, p);
   114837     }
   114838     sqlite3DbFree(db, pWInfo);
   114839   }
   114840 }
   114841 
   114842 /*
   114843 ** Return TRUE if both of the following are true:
   114844 **
   114845 **   (1)  X has the same or lower cost that Y
   114846 **   (2)  X is a proper subset of Y
   114847 **
   114848 ** By "proper subset" we mean that X uses fewer WHERE clause terms
   114849 ** than Y and that every WHERE clause term used by X is also used
   114850 ** by Y.
   114851 **
   114852 ** If X is a proper subset of Y then Y is a better choice and ought
   114853 ** to have a lower cost.  This routine returns TRUE when that cost
   114854 ** relationship is inverted and needs to be adjusted.
   114855 */
   114856 static int whereLoopCheaperProperSubset(
   114857   const WhereLoop *pX,       /* First WhereLoop to compare */
   114858   const WhereLoop *pY        /* Compare against this WhereLoop */
   114859 ){
   114860   int i, j;
   114861   if( pX->nLTerm >= pY->nLTerm ) return 0; /* X is not a subset of Y */
   114862   if( pX->rRun >= pY->rRun ){
   114863     if( pX->rRun > pY->rRun ) return 0;    /* X costs more than Y */
   114864     if( pX->nOut > pY->nOut ) return 0;    /* X costs more than Y */
   114865   }
   114866   for(i=pX->nLTerm-1; i>=0; i--){
   114867     for(j=pY->nLTerm-1; j>=0; j--){
   114868       if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
   114869     }
   114870     if( j<0 ) return 0;  /* X not a subset of Y since term X[i] not used by Y */
   114871   }
   114872   return 1;  /* All conditions meet */
   114873 }
   114874 
   114875 /*
   114876 ** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
   114877 ** that:
   114878 **
   114879 **   (1) pTemplate costs less than any other WhereLoops that are a proper
   114880 **       subset of pTemplate
   114881 **
   114882 **   (2) pTemplate costs more than any other WhereLoops for which pTemplate
   114883 **       is a proper subset.
   114884 **
   114885 ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
   114886 ** WHERE clause terms than Y and that every WHERE clause term used by X is
   114887 ** also used by Y.
   114888 **
   114889 ** This adjustment is omitted for SKIPSCAN loops.  In a SKIPSCAN loop, the
   114890 ** WhereLoop.nLTerm field is not an accurate measure of the number of WHERE
   114891 ** clause terms covered, since some of the first nLTerm entries in aLTerm[]
   114892 ** will be NULL (because they are skipped).  That makes it more difficult
   114893 ** to compare the loops.  We could add extra code to do the comparison, and
   114894 ** perhaps we will someday.  But SKIPSCAN is sufficiently uncommon, and this
   114895 ** adjustment is sufficient minor, that it is very difficult to construct
   114896 ** a test case where the extra code would improve the query plan.  Better
   114897 ** to avoid the added complexity and just omit cost adjustments to SKIPSCAN
   114898 ** loops.
   114899 */
   114900 static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
   114901   if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
   114902   if( (pTemplate->wsFlags & WHERE_SKIPSCAN)!=0 ) return;
   114903   for(; p; p=p->pNextLoop){
   114904     if( p->iTab!=pTemplate->iTab ) continue;
   114905     if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
   114906     if( (p->wsFlags & WHERE_SKIPSCAN)!=0 ) continue;
   114907     if( whereLoopCheaperProperSubset(p, pTemplate) ){
   114908       /* Adjust pTemplate cost downward so that it is cheaper than its
   114909       ** subset p */
   114910       pTemplate->rRun = p->rRun;
   114911       pTemplate->nOut = p->nOut - 1;
   114912     }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
   114913       /* Adjust pTemplate cost upward so that it is costlier than p since
   114914       ** pTemplate is a proper subset of p */
   114915       pTemplate->rRun = p->rRun;
   114916       pTemplate->nOut = p->nOut + 1;
   114917     }
   114918   }
   114919 }
   114920 
   114921 /*
   114922 ** Search the list of WhereLoops in *ppPrev looking for one that can be
   114923 ** supplanted by pTemplate.
   114924 **
   114925 ** Return NULL if the WhereLoop list contains an entry that can supplant
   114926 ** pTemplate, in other words if pTemplate does not belong on the list.
   114927 **
   114928 ** If pX is a WhereLoop that pTemplate can supplant, then return the
   114929 ** link that points to pX.
   114930 **
   114931 ** If pTemplate cannot supplant any existing element of the list but needs
   114932 ** to be added to the list, then return a pointer to the tail of the list.
   114933 */
   114934 static WhereLoop **whereLoopFindLesser(
   114935   WhereLoop **ppPrev,
   114936   const WhereLoop *pTemplate
   114937 ){
   114938   WhereLoop *p;
   114939   for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
   114940     if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
   114941       /* If either the iTab or iSortIdx values for two WhereLoop are different
   114942       ** then those WhereLoops need to be considered separately.  Neither is
   114943       ** a candidate to replace the other. */
   114944       continue;
   114945     }
   114946     /* In the current implementation, the rSetup value is either zero
   114947     ** or the cost of building an automatic index (NlogN) and the NlogN
   114948     ** is the same for compatible WhereLoops. */
   114949     assert( p->rSetup==0 || pTemplate->rSetup==0
   114950                  || p->rSetup==pTemplate->rSetup );
   114951 
   114952     /* whereLoopAddBtree() always generates and inserts the automatic index
   114953     ** case first.  Hence compatible candidate WhereLoops never have a larger
   114954     ** rSetup. Call this SETUP-INVARIANT */
   114955     assert( p->rSetup>=pTemplate->rSetup );
   114956 
   114957     /* Any loop using an appliation-defined index (or PRIMARY KEY or
   114958     ** UNIQUE constraint) with one or more == constraints is better
   114959     ** than an automatic index. */
   114960     if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
   114961      && (pTemplate->wsFlags & WHERE_INDEXED)!=0
   114962      && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
   114963      && (p->prereq & pTemplate->prereq)==pTemplate->prereq
   114964     ){
   114965       break;
   114966     }
   114967 
   114968     /* If existing WhereLoop p is better than pTemplate, pTemplate can be
   114969     ** discarded.  WhereLoop p is better if:
   114970     **   (1)  p has no more dependencies than pTemplate, and
   114971     **   (2)  p has an equal or lower cost than pTemplate
   114972     */
   114973     if( (p->prereq & pTemplate->prereq)==p->prereq    /* (1)  */
   114974      && p->rSetup<=pTemplate->rSetup                  /* (2a) */
   114975      && p->rRun<=pTemplate->rRun                      /* (2b) */
   114976      && p->nOut<=pTemplate->nOut                      /* (2c) */
   114977     ){
   114978       return 0;  /* Discard pTemplate */
   114979     }
   114980 
   114981     /* If pTemplate is always better than p, then cause p to be overwritten
   114982     ** with pTemplate.  pTemplate is better than p if:
   114983     **   (1)  pTemplate has no more dependences than p, and
   114984     **   (2)  pTemplate has an equal or lower cost than p.
   114985     */
   114986     if( (p->prereq & pTemplate->prereq)==pTemplate->prereq   /* (1)  */
   114987      && p->rRun>=pTemplate->rRun                             /* (2a) */
   114988      && p->nOut>=pTemplate->nOut                             /* (2b) */
   114989     ){
   114990       assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
   114991       break;   /* Cause p to be overwritten by pTemplate */
   114992     }
   114993   }
   114994   return ppPrev;
   114995 }
   114996 
   114997 /*
   114998 ** Insert or replace a WhereLoop entry using the template supplied.
   114999 **
   115000 ** An existing WhereLoop entry might be overwritten if the new template
   115001 ** is better and has fewer dependencies.  Or the template will be ignored
   115002 ** and no insert will occur if an existing WhereLoop is faster and has
   115003 ** fewer dependencies than the template.  Otherwise a new WhereLoop is
   115004 ** added based on the template.
   115005 **
   115006 ** If pBuilder->pOrSet is not NULL then we care about only the
   115007 ** prerequisites and rRun and nOut costs of the N best loops.  That
   115008 ** information is gathered in the pBuilder->pOrSet object.  This special
   115009 ** processing mode is used only for OR clause processing.
   115010 **
   115011 ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
   115012 ** still might overwrite similar loops with the new template if the
   115013 ** new template is better.  Loops may be overwritten if the following
   115014 ** conditions are met:
   115015 **
   115016 **    (1)  They have the same iTab.
   115017 **    (2)  They have the same iSortIdx.
   115018 **    (3)  The template has same or fewer dependencies than the current loop
   115019 **    (4)  The template has the same or lower cost than the current loop
   115020 */
   115021 static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
   115022   WhereLoop **ppPrev, *p;
   115023   WhereInfo *pWInfo = pBuilder->pWInfo;
   115024   sqlite3 *db = pWInfo->pParse->db;
   115025 
   115026   /* If pBuilder->pOrSet is defined, then only keep track of the costs
   115027   ** and prereqs.
   115028   */
   115029   if( pBuilder->pOrSet!=0 ){
   115030 #if WHERETRACE_ENABLED
   115031     u16 n = pBuilder->pOrSet->n;
   115032     int x =
   115033 #endif
   115034     whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
   115035                                     pTemplate->nOut);
   115036 #if WHERETRACE_ENABLED /* 0x8 */
   115037     if( sqlite3WhereTrace & 0x8 ){
   115038       sqlite3DebugPrintf(x?"   or-%d:  ":"   or-X:  ", n);
   115039       whereLoopPrint(pTemplate, pBuilder->pWC);
   115040     }
   115041 #endif
   115042     return SQLITE_OK;
   115043   }
   115044 
   115045   /* Look for an existing WhereLoop to replace with pTemplate
   115046   */
   115047   whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
   115048   ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
   115049 
   115050   if( ppPrev==0 ){
   115051     /* There already exists a WhereLoop on the list that is better
   115052     ** than pTemplate, so just ignore pTemplate */
   115053 #if WHERETRACE_ENABLED /* 0x8 */
   115054     if( sqlite3WhereTrace & 0x8 ){
   115055       sqlite3DebugPrintf("ins-noop: ");
   115056       whereLoopPrint(pTemplate, pBuilder->pWC);
   115057     }
   115058 #endif
   115059     return SQLITE_OK;
   115060   }else{
   115061     p = *ppPrev;
   115062   }
   115063 
   115064   /* If we reach this point it means that either p[] should be overwritten
   115065   ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
   115066   ** WhereLoop and insert it.
   115067   */
   115068 #if WHERETRACE_ENABLED /* 0x8 */
   115069   if( sqlite3WhereTrace & 0x8 ){
   115070     if( p!=0 ){
   115071       sqlite3DebugPrintf("ins-del:  ");
   115072       whereLoopPrint(p, pBuilder->pWC);
   115073     }
   115074     sqlite3DebugPrintf("ins-new:  ");
   115075     whereLoopPrint(pTemplate, pBuilder->pWC);
   115076   }
   115077 #endif
   115078   if( p==0 ){
   115079     /* Allocate a new WhereLoop to add to the end of the list */
   115080     *ppPrev = p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
   115081     if( p==0 ) return SQLITE_NOMEM;
   115082     whereLoopInit(p);
   115083     p->pNextLoop = 0;
   115084   }else{
   115085     /* We will be overwriting WhereLoop p[].  But before we do, first
   115086     ** go through the rest of the list and delete any other entries besides
   115087     ** p[] that are also supplated by pTemplate */
   115088     WhereLoop **ppTail = &p->pNextLoop;
   115089     WhereLoop *pToDel;
   115090     while( *ppTail ){
   115091       ppTail = whereLoopFindLesser(ppTail, pTemplate);
   115092       if( ppTail==0 ) break;
   115093       pToDel = *ppTail;
   115094       if( pToDel==0 ) break;
   115095       *ppTail = pToDel->pNextLoop;
   115096 #if WHERETRACE_ENABLED /* 0x8 */
   115097       if( sqlite3WhereTrace & 0x8 ){
   115098         sqlite3DebugPrintf("ins-del:  ");
   115099         whereLoopPrint(pToDel, pBuilder->pWC);
   115100       }
   115101 #endif
   115102       whereLoopDelete(db, pToDel);
   115103     }
   115104   }
   115105   whereLoopXfer(db, p, pTemplate);
   115106   if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
   115107     Index *pIndex = p->u.btree.pIndex;
   115108     if( pIndex && pIndex->tnum==0 ){
   115109       p->u.btree.pIndex = 0;
   115110     }
   115111   }
   115112   return SQLITE_OK;
   115113 }
   115114 
   115115 /*
   115116 ** Adjust the WhereLoop.nOut value downward to account for terms of the
   115117 ** WHERE clause that reference the loop but which are not used by an
   115118 ** index.
   115119 **
   115120 ** In the current implementation, the first extra WHERE clause term reduces
   115121 ** the number of output rows by a factor of 10 and each additional term
   115122 ** reduces the number of output rows by sqrt(2).
   115123 */
   115124 static void whereLoopOutputAdjust(WhereClause *pWC, WhereLoop *pLoop){
   115125   WhereTerm *pTerm, *pX;
   115126   Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
   115127   int i, j;
   115128 
   115129   if( !OptimizationEnabled(pWC->pWInfo->pParse->db, SQLITE_AdjustOutEst) ){
   115130     return;
   115131   }
   115132   for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
   115133     if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
   115134     if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
   115135     if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
   115136     for(j=pLoop->nLTerm-1; j>=0; j--){
   115137       pX = pLoop->aLTerm[j];
   115138       if( pX==0 ) continue;
   115139       if( pX==pTerm ) break;
   115140       if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
   115141     }
   115142     if( j<0 ){
   115143       pLoop->nOut += (pTerm->truthProb<=0 ? pTerm->truthProb : -1);
   115144     }
   115145   }
   115146 }
   115147 
   115148 /*
   115149 ** Adjust the cost C by the costMult facter T.  This only occurs if
   115150 ** compiled with -DSQLITE_ENABLE_COSTMULT
   115151 */
   115152 #ifdef SQLITE_ENABLE_COSTMULT
   115153 # define ApplyCostMultiplier(C,T)  C += T
   115154 #else
   115155 # define ApplyCostMultiplier(C,T)
   115156 #endif
   115157 
   115158 /*
   115159 ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
   115160 ** index pIndex. Try to match one more.
   115161 **
   115162 ** When this function is called, pBuilder->pNew->nOut contains the
   115163 ** number of rows expected to be visited by filtering using the nEq
   115164 ** terms only. If it is modified, this value is restored before this
   115165 ** function returns.
   115166 **
   115167 ** If pProbe->tnum==0, that means pIndex is a fake index used for the
   115168 ** INTEGER PRIMARY KEY.
   115169 */
   115170 static int whereLoopAddBtreeIndex(
   115171   WhereLoopBuilder *pBuilder,     /* The WhereLoop factory */
   115172   struct SrcList_item *pSrc,      /* FROM clause term being analyzed */
   115173   Index *pProbe,                  /* An index on pSrc */
   115174   LogEst nInMul                   /* log(Number of iterations due to IN) */
   115175 ){
   115176   WhereInfo *pWInfo = pBuilder->pWInfo;  /* WHERE analyse context */
   115177   Parse *pParse = pWInfo->pParse;        /* Parsing context */
   115178   sqlite3 *db = pParse->db;       /* Database connection malloc context */
   115179   WhereLoop *pNew;                /* Template WhereLoop under construction */
   115180   WhereTerm *pTerm;               /* A WhereTerm under consideration */
   115181   int opMask;                     /* Valid operators for constraints */
   115182   WhereScan scan;                 /* Iterator for WHERE terms */
   115183   Bitmask saved_prereq;           /* Original value of pNew->prereq */
   115184   u16 saved_nLTerm;               /* Original value of pNew->nLTerm */
   115185   u16 saved_nEq;                  /* Original value of pNew->u.btree.nEq */
   115186   u16 saved_nSkip;                /* Original value of pNew->u.btree.nSkip */
   115187   u32 saved_wsFlags;              /* Original value of pNew->wsFlags */
   115188   LogEst saved_nOut;              /* Original value of pNew->nOut */
   115189   int iCol;                       /* Index of the column in the table */
   115190   int rc = SQLITE_OK;             /* Return code */
   115191   LogEst rLogSize;                /* Logarithm of table size */
   115192   WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
   115193 
   115194   pNew = pBuilder->pNew;
   115195   if( db->mallocFailed ) return SQLITE_NOMEM;
   115196 
   115197   assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
   115198   assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
   115199   if( pNew->wsFlags & WHERE_BTM_LIMIT ){
   115200     opMask = WO_LT|WO_LE;
   115201   }else if( pProbe->tnum<=0 || (pSrc->jointype & JT_LEFT)!=0 ){
   115202     opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
   115203   }else{
   115204     opMask = WO_EQ|WO_IN|WO_ISNULL|WO_GT|WO_GE|WO_LT|WO_LE;
   115205   }
   115206   if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
   115207 
   115208   assert( pNew->u.btree.nEq<pProbe->nColumn );
   115209   iCol = pProbe->aiColumn[pNew->u.btree.nEq];
   115210 
   115211   pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol,
   115212                         opMask, pProbe);
   115213   saved_nEq = pNew->u.btree.nEq;
   115214   saved_nSkip = pNew->u.btree.nSkip;
   115215   saved_nLTerm = pNew->nLTerm;
   115216   saved_wsFlags = pNew->wsFlags;
   115217   saved_prereq = pNew->prereq;
   115218   saved_nOut = pNew->nOut;
   115219   pNew->rSetup = 0;
   115220   rLogSize = estLog(pProbe->aiRowLogEst[0]);
   115221 
   115222   /* Consider using a skip-scan if there are no WHERE clause constraints
   115223   ** available for the left-most terms of the index, and if the average
   115224   ** number of repeats in the left-most terms is at least 18.
   115225   **
   115226   ** The magic number 18 is selected on the basis that scanning 17 rows
   115227   ** is almost always quicker than an index seek (even though if the index
   115228   ** contains fewer than 2^17 rows we assume otherwise in other parts of
   115229   ** the code). And, even if it is not, it should not be too much slower.
   115230   ** On the other hand, the extra seeks could end up being significantly
   115231   ** more expensive.  */
   115232   assert( 42==sqlite3LogEst(18) );
   115233   if( pTerm==0
   115234    && saved_nEq==saved_nSkip
   115235    && saved_nEq+1<pProbe->nKeyCol
   115236    && pProbe->aiRowLogEst[saved_nEq+1]>=42  /* TUNING: Minimum for skip-scan */
   115237    && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
   115238   ){
   115239     LogEst nIter;
   115240     pNew->u.btree.nEq++;
   115241     pNew->u.btree.nSkip++;
   115242     pNew->aLTerm[pNew->nLTerm++] = 0;
   115243     pNew->wsFlags |= WHERE_SKIPSCAN;
   115244     nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
   115245     pNew->nOut -= nIter;
   115246     whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
   115247     pNew->nOut = saved_nOut;
   115248   }
   115249   for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
   115250     u16 eOp = pTerm->eOperator;   /* Shorthand for pTerm->eOperator */
   115251     LogEst rCostIdx;
   115252     LogEst nOutUnadjusted;        /* nOut before IN() and WHERE adjustments */
   115253     int nIn = 0;
   115254 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   115255     int nRecValid = pBuilder->nRecValid;
   115256 #endif
   115257     if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
   115258      && (iCol<0 || pSrc->pTab->aCol[iCol].notNull)
   115259     ){
   115260       continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
   115261     }
   115262     if( pTerm->prereqRight & pNew->maskSelf ) continue;
   115263 
   115264     pNew->wsFlags = saved_wsFlags;
   115265     pNew->u.btree.nEq = saved_nEq;
   115266     pNew->nLTerm = saved_nLTerm;
   115267     if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
   115268     pNew->aLTerm[pNew->nLTerm++] = pTerm;
   115269     pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
   115270 
   115271     assert( nInMul==0
   115272         || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
   115273         || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
   115274         || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
   115275     );
   115276 
   115277     if( eOp & WO_IN ){
   115278       Expr *pExpr = pTerm->pExpr;
   115279       pNew->wsFlags |= WHERE_COLUMN_IN;
   115280       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   115281         /* "x IN (SELECT ...)":  TUNING: the SELECT returns 25 rows */
   115282         nIn = 46;  assert( 46==sqlite3LogEst(25) );
   115283       }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
   115284         /* "x IN (value, value, ...)" */
   115285         nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
   115286       }
   115287       assert( nIn>0 );  /* RHS always has 2 or more terms...  The parser
   115288                         ** changes "x IN (?)" into "x=?". */
   115289 
   115290     }else if( eOp & (WO_EQ) ){
   115291       pNew->wsFlags |= WHERE_COLUMN_EQ;
   115292       if( iCol<0 || (nInMul==0 && pNew->u.btree.nEq==pProbe->nKeyCol-1) ){
   115293         if( iCol>=0 && !IsUniqueIndex(pProbe) ){
   115294           pNew->wsFlags |= WHERE_UNQ_WANTED;
   115295         }else{
   115296           pNew->wsFlags |= WHERE_ONEROW;
   115297         }
   115298       }
   115299     }else if( eOp & WO_ISNULL ){
   115300       pNew->wsFlags |= WHERE_COLUMN_NULL;
   115301     }else if( eOp & (WO_GT|WO_GE) ){
   115302       testcase( eOp & WO_GT );
   115303       testcase( eOp & WO_GE );
   115304       pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
   115305       pBtm = pTerm;
   115306       pTop = 0;
   115307     }else{
   115308       assert( eOp & (WO_LT|WO_LE) );
   115309       testcase( eOp & WO_LT );
   115310       testcase( eOp & WO_LE );
   115311       pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
   115312       pTop = pTerm;
   115313       pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
   115314                      pNew->aLTerm[pNew->nLTerm-2] : 0;
   115315     }
   115316 
   115317     /* At this point pNew->nOut is set to the number of rows expected to
   115318     ** be visited by the index scan before considering term pTerm, or the
   115319     ** values of nIn and nInMul. In other words, assuming that all
   115320     ** "x IN(...)" terms are replaced with "x = ?". This block updates
   115321     ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul).  */
   115322     assert( pNew->nOut==saved_nOut );
   115323     if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
   115324       /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
   115325       ** data, using some other estimate.  */
   115326       whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
   115327     }else{
   115328       int nEq = ++pNew->u.btree.nEq;
   115329       assert( eOp & (WO_ISNULL|WO_EQ|WO_IN) );
   115330 
   115331       assert( pNew->nOut==saved_nOut );
   115332       if( pTerm->truthProb<=0 && iCol>=0 ){
   115333         assert( (eOp & WO_IN) || nIn==0 );
   115334         testcase( eOp & WO_IN );
   115335         pNew->nOut += pTerm->truthProb;
   115336         pNew->nOut -= nIn;
   115337       }else{
   115338 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   115339         tRowcnt nOut = 0;
   115340         if( nInMul==0
   115341          && pProbe->nSample
   115342          && pNew->u.btree.nEq<=pProbe->nSampleCol
   115343          && OptimizationEnabled(db, SQLITE_Stat3)
   115344          && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
   115345         ){
   115346           Expr *pExpr = pTerm->pExpr;
   115347           if( (eOp & (WO_EQ|WO_ISNULL))!=0 ){
   115348             testcase( eOp & WO_EQ );
   115349             testcase( eOp & WO_ISNULL );
   115350             rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
   115351           }else{
   115352             rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
   115353           }
   115354           if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
   115355           if( rc!=SQLITE_OK ) break;          /* Jump out of the pTerm loop */
   115356           if( nOut ){
   115357             pNew->nOut = sqlite3LogEst(nOut);
   115358             if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
   115359             pNew->nOut -= nIn;
   115360           }
   115361         }
   115362         if( nOut==0 )
   115363 #endif
   115364         {
   115365           pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
   115366           if( eOp & WO_ISNULL ){
   115367             /* TUNING: If there is no likelihood() value, assume that a
   115368             ** "col IS NULL" expression matches twice as many rows
   115369             ** as (col=?). */
   115370             pNew->nOut += 10;
   115371           }
   115372         }
   115373       }
   115374     }
   115375 
   115376     /* Set rCostIdx to the cost of visiting selected rows in index. Add
   115377     ** it to pNew->rRun, which is currently set to the cost of the index
   115378     ** seek only. Then, if this is a non-covering index, add the cost of
   115379     ** visiting the rows in the main table.  */
   115380     rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
   115381     pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
   115382     if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
   115383       pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
   115384     }
   115385     ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
   115386 
   115387     nOutUnadjusted = pNew->nOut;
   115388     pNew->rRun += nInMul + nIn;
   115389     pNew->nOut += nInMul + nIn;
   115390     whereLoopOutputAdjust(pBuilder->pWC, pNew);
   115391     rc = whereLoopInsert(pBuilder, pNew);
   115392 
   115393     if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
   115394       pNew->nOut = saved_nOut;
   115395     }else{
   115396       pNew->nOut = nOutUnadjusted;
   115397     }
   115398 
   115399     if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
   115400      && pNew->u.btree.nEq<pProbe->nColumn
   115401     ){
   115402       whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
   115403     }
   115404     pNew->nOut = saved_nOut;
   115405 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   115406     pBuilder->nRecValid = nRecValid;
   115407 #endif
   115408   }
   115409   pNew->prereq = saved_prereq;
   115410   pNew->u.btree.nEq = saved_nEq;
   115411   pNew->u.btree.nSkip = saved_nSkip;
   115412   pNew->wsFlags = saved_wsFlags;
   115413   pNew->nOut = saved_nOut;
   115414   pNew->nLTerm = saved_nLTerm;
   115415   return rc;
   115416 }
   115417 
   115418 /*
   115419 ** Return True if it is possible that pIndex might be useful in
   115420 ** implementing the ORDER BY clause in pBuilder.
   115421 **
   115422 ** Return False if pBuilder does not contain an ORDER BY clause or
   115423 ** if there is no way for pIndex to be useful in implementing that
   115424 ** ORDER BY clause.
   115425 */
   115426 static int indexMightHelpWithOrderBy(
   115427   WhereLoopBuilder *pBuilder,
   115428   Index *pIndex,
   115429   int iCursor
   115430 ){
   115431   ExprList *pOB;
   115432   int ii, jj;
   115433 
   115434   if( pIndex->bUnordered ) return 0;
   115435   if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
   115436   for(ii=0; ii<pOB->nExpr; ii++){
   115437     Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
   115438     if( pExpr->op!=TK_COLUMN ) return 0;
   115439     if( pExpr->iTable==iCursor ){
   115440       for(jj=0; jj<pIndex->nKeyCol; jj++){
   115441         if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
   115442       }
   115443     }
   115444   }
   115445   return 0;
   115446 }
   115447 
   115448 /*
   115449 ** Return a bitmask where 1s indicate that the corresponding column of
   115450 ** the table is used by an index.  Only the first 63 columns are considered.
   115451 */
   115452 static Bitmask columnsInIndex(Index *pIdx){
   115453   Bitmask m = 0;
   115454   int j;
   115455   for(j=pIdx->nColumn-1; j>=0; j--){
   115456     int x = pIdx->aiColumn[j];
   115457     if( x>=0 ){
   115458       testcase( x==BMS-1 );
   115459       testcase( x==BMS-2 );
   115460       if( x<BMS-1 ) m |= MASKBIT(x);
   115461     }
   115462   }
   115463   return m;
   115464 }
   115465 
   115466 /* Check to see if a partial index with pPartIndexWhere can be used
   115467 ** in the current query.  Return true if it can be and false if not.
   115468 */
   115469 static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
   115470   int i;
   115471   WhereTerm *pTerm;
   115472   for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
   115473     if( sqlite3ExprImpliesExpr(pTerm->pExpr, pWhere, iTab) ) return 1;
   115474   }
   115475   return 0;
   115476 }
   115477 
   115478 /*
   115479 ** Add all WhereLoop objects for a single table of the join where the table
   115480 ** is idenfied by pBuilder->pNew->iTab.  That table is guaranteed to be
   115481 ** a b-tree table, not a virtual table.
   115482 **
   115483 ** The costs (WhereLoop.rRun) of the b-tree loops added by this function
   115484 ** are calculated as follows:
   115485 **
   115486 ** For a full scan, assuming the table (or index) contains nRow rows:
   115487 **
   115488 **     cost = nRow * 3.0                    // full-table scan
   115489 **     cost = nRow * K                      // scan of covering index
   115490 **     cost = nRow * (K+3.0)                // scan of non-covering index
   115491 **
   115492 ** where K is a value between 1.1 and 3.0 set based on the relative
   115493 ** estimated average size of the index and table records.
   115494 **
   115495 ** For an index scan, where nVisit is the number of index rows visited
   115496 ** by the scan, and nSeek is the number of seek operations required on
   115497 ** the index b-tree:
   115498 **
   115499 **     cost = nSeek * (log(nRow) + K * nVisit)          // covering index
   115500 **     cost = nSeek * (log(nRow) + (K+3.0) * nVisit)    // non-covering index
   115501 **
   115502 ** Normally, nSeek is 1. nSeek values greater than 1 come about if the
   115503 ** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
   115504 ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
   115505 **
   115506 ** The estimated values (nRow, nVisit, nSeek) often contain a large amount
   115507 ** of uncertainty.  For this reason, scoring is designed to pick plans that
   115508 ** "do the least harm" if the estimates are inaccurate.  For example, a
   115509 ** log(nRow) factor is omitted from a non-covering index scan in order to
   115510 ** bias the scoring in favor of using an index, since the worst-case
   115511 ** performance of using an index is far better than the worst-case performance
   115512 ** of a full table scan.
   115513 */
   115514 static int whereLoopAddBtree(
   115515   WhereLoopBuilder *pBuilder, /* WHERE clause information */
   115516   Bitmask mExtra              /* Extra prerequesites for using this table */
   115517 ){
   115518   WhereInfo *pWInfo;          /* WHERE analysis context */
   115519   Index *pProbe;              /* An index we are evaluating */
   115520   Index sPk;                  /* A fake index object for the primary key */
   115521   LogEst aiRowEstPk[2];       /* The aiRowLogEst[] value for the sPk index */
   115522   i16 aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
   115523   SrcList *pTabList;          /* The FROM clause */
   115524   struct SrcList_item *pSrc;  /* The FROM clause btree term to add */
   115525   WhereLoop *pNew;            /* Template WhereLoop object */
   115526   int rc = SQLITE_OK;         /* Return code */
   115527   int iSortIdx = 1;           /* Index number */
   115528   int b;                      /* A boolean value */
   115529   LogEst rSize;               /* number of rows in the table */
   115530   LogEst rLogSize;            /* Logarithm of the number of rows in the table */
   115531   WhereClause *pWC;           /* The parsed WHERE clause */
   115532   Table *pTab;                /* Table being queried */
   115533 
   115534   pNew = pBuilder->pNew;
   115535   pWInfo = pBuilder->pWInfo;
   115536   pTabList = pWInfo->pTabList;
   115537   pSrc = pTabList->a + pNew->iTab;
   115538   pTab = pSrc->pTab;
   115539   pWC = pBuilder->pWC;
   115540   assert( !IsVirtual(pSrc->pTab) );
   115541 
   115542   if( pSrc->pIndex ){
   115543     /* An INDEXED BY clause specifies a particular index to use */
   115544     pProbe = pSrc->pIndex;
   115545   }else if( !HasRowid(pTab) ){
   115546     pProbe = pTab->pIndex;
   115547   }else{
   115548     /* There is no INDEXED BY clause.  Create a fake Index object in local
   115549     ** variable sPk to represent the rowid primary key index.  Make this
   115550     ** fake index the first in a chain of Index objects with all of the real
   115551     ** indices to follow */
   115552     Index *pFirst;                  /* First of real indices on the table */
   115553     memset(&sPk, 0, sizeof(Index));
   115554     sPk.nKeyCol = 1;
   115555     sPk.nColumn = 1;
   115556     sPk.aiColumn = &aiColumnPk;
   115557     sPk.aiRowLogEst = aiRowEstPk;
   115558     sPk.onError = OE_Replace;
   115559     sPk.pTable = pTab;
   115560     sPk.szIdxRow = pTab->szTabRow;
   115561     aiRowEstPk[0] = pTab->nRowLogEst;
   115562     aiRowEstPk[1] = 0;
   115563     pFirst = pSrc->pTab->pIndex;
   115564     if( pSrc->notIndexed==0 ){
   115565       /* The real indices of the table are only considered if the
   115566       ** NOT INDEXED qualifier is omitted from the FROM clause */
   115567       sPk.pNext = pFirst;
   115568     }
   115569     pProbe = &sPk;
   115570   }
   115571   rSize = pTab->nRowLogEst;
   115572   rLogSize = estLog(rSize);
   115573 
   115574 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
   115575   /* Automatic indexes */
   115576   if( !pBuilder->pOrSet
   115577    && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
   115578    && pSrc->pIndex==0
   115579    && !pSrc->viaCoroutine
   115580    && !pSrc->notIndexed
   115581    && HasRowid(pTab)
   115582    && !pSrc->isCorrelated
   115583    && !pSrc->isRecursive
   115584   ){
   115585     /* Generate auto-index WhereLoops */
   115586     WhereTerm *pTerm;
   115587     WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
   115588     for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
   115589       if( pTerm->prereqRight & pNew->maskSelf ) continue;
   115590       if( termCanDriveIndex(pTerm, pSrc, 0) ){
   115591         pNew->u.btree.nEq = 1;
   115592         pNew->u.btree.nSkip = 0;
   115593         pNew->u.btree.pIndex = 0;
   115594         pNew->nLTerm = 1;
   115595         pNew->aLTerm[0] = pTerm;
   115596         /* TUNING: One-time cost for computing the automatic index is
   115597         ** approximately 7*N*log2(N) where N is the number of rows in
   115598         ** the table being indexed. */
   115599         pNew->rSetup = rLogSize + rSize + 28;  assert( 28==sqlite3LogEst(7) );
   115600         ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
   115601         /* TUNING: Each index lookup yields 20 rows in the table.  This
   115602         ** is more than the usual guess of 10 rows, since we have no way
   115603         ** of knowning how selective the index will ultimately be.  It would
   115604         ** not be unreasonable to make this value much larger. */
   115605         pNew->nOut = 43;  assert( 43==sqlite3LogEst(20) );
   115606         pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
   115607         pNew->wsFlags = WHERE_AUTO_INDEX;
   115608         pNew->prereq = mExtra | pTerm->prereqRight;
   115609         rc = whereLoopInsert(pBuilder, pNew);
   115610       }
   115611     }
   115612   }
   115613 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
   115614 
   115615   /* Loop over all indices
   115616   */
   115617   for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
   115618     if( pProbe->pPartIdxWhere!=0
   115619      && !whereUsablePartialIndex(pNew->iTab, pWC, pProbe->pPartIdxWhere) ){
   115620       continue;  /* Partial index inappropriate for this query */
   115621     }
   115622     rSize = pProbe->aiRowLogEst[0];
   115623     pNew->u.btree.nEq = 0;
   115624     pNew->u.btree.nSkip = 0;
   115625     pNew->nLTerm = 0;
   115626     pNew->iSortIdx = 0;
   115627     pNew->rSetup = 0;
   115628     pNew->prereq = mExtra;
   115629     pNew->nOut = rSize;
   115630     pNew->u.btree.pIndex = pProbe;
   115631     b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
   115632     /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
   115633     assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
   115634     if( pProbe->tnum<=0 ){
   115635       /* Integer primary key index */
   115636       pNew->wsFlags = WHERE_IPK;
   115637 
   115638       /* Full table scan */
   115639       pNew->iSortIdx = b ? iSortIdx : 0;
   115640       /* TUNING: Cost of full table scan is (N*3.0). */
   115641       pNew->rRun = rSize + 16;
   115642       ApplyCostMultiplier(pNew->rRun, pTab->costMult);
   115643       whereLoopOutputAdjust(pWC, pNew);
   115644       rc = whereLoopInsert(pBuilder, pNew);
   115645       pNew->nOut = rSize;
   115646       if( rc ) break;
   115647     }else{
   115648       Bitmask m;
   115649       if( pProbe->isCovering ){
   115650         pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
   115651         m = 0;
   115652       }else{
   115653         m = pSrc->colUsed & ~columnsInIndex(pProbe);
   115654         pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
   115655       }
   115656 
   115657       /* Full scan via index */
   115658       if( b
   115659        || !HasRowid(pTab)
   115660        || ( m==0
   115661          && pProbe->bUnordered==0
   115662          && (pProbe->szIdxRow<pTab->szTabRow)
   115663          && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
   115664          && sqlite3GlobalConfig.bUseCis
   115665          && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
   115666           )
   115667       ){
   115668         pNew->iSortIdx = b ? iSortIdx : 0;
   115669 
   115670         /* The cost of visiting the index rows is N*K, where K is
   115671         ** between 1.1 and 3.0, depending on the relative sizes of the
   115672         ** index and table rows. If this is a non-covering index scan,
   115673         ** also add the cost of visiting table rows (N*3.0).  */
   115674         pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
   115675         if( m!=0 ){
   115676           pNew->rRun = sqlite3LogEstAdd(pNew->rRun, rSize+16);
   115677         }
   115678         ApplyCostMultiplier(pNew->rRun, pTab->costMult);
   115679         whereLoopOutputAdjust(pWC, pNew);
   115680         rc = whereLoopInsert(pBuilder, pNew);
   115681         pNew->nOut = rSize;
   115682         if( rc ) break;
   115683       }
   115684     }
   115685 
   115686     rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
   115687 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   115688     sqlite3Stat4ProbeFree(pBuilder->pRec);
   115689     pBuilder->nRecValid = 0;
   115690     pBuilder->pRec = 0;
   115691 #endif
   115692 
   115693     /* If there was an INDEXED BY clause, then only that one index is
   115694     ** considered. */
   115695     if( pSrc->pIndex ) break;
   115696   }
   115697   return rc;
   115698 }
   115699 
   115700 #ifndef SQLITE_OMIT_VIRTUALTABLE
   115701 /*
   115702 ** Add all WhereLoop objects for a table of the join identified by
   115703 ** pBuilder->pNew->iTab.  That table is guaranteed to be a virtual table.
   115704 */
   115705 static int whereLoopAddVirtual(
   115706   WhereLoopBuilder *pBuilder,  /* WHERE clause information */
   115707   Bitmask mExtra
   115708 ){
   115709   WhereInfo *pWInfo;           /* WHERE analysis context */
   115710   Parse *pParse;               /* The parsing context */
   115711   WhereClause *pWC;            /* The WHERE clause */
   115712   struct SrcList_item *pSrc;   /* The FROM clause term to search */
   115713   Table *pTab;
   115714   sqlite3 *db;
   115715   sqlite3_index_info *pIdxInfo;
   115716   struct sqlite3_index_constraint *pIdxCons;
   115717   struct sqlite3_index_constraint_usage *pUsage;
   115718   WhereTerm *pTerm;
   115719   int i, j;
   115720   int iTerm, mxTerm;
   115721   int nConstraint;
   115722   int seenIn = 0;              /* True if an IN operator is seen */
   115723   int seenVar = 0;             /* True if a non-constant constraint is seen */
   115724   int iPhase;                  /* 0: const w/o IN, 1: const, 2: no IN,  2: IN */
   115725   WhereLoop *pNew;
   115726   int rc = SQLITE_OK;
   115727 
   115728   pWInfo = pBuilder->pWInfo;
   115729   pParse = pWInfo->pParse;
   115730   db = pParse->db;
   115731   pWC = pBuilder->pWC;
   115732   pNew = pBuilder->pNew;
   115733   pSrc = &pWInfo->pTabList->a[pNew->iTab];
   115734   pTab = pSrc->pTab;
   115735   assert( IsVirtual(pTab) );
   115736   pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pBuilder->pOrderBy);
   115737   if( pIdxInfo==0 ) return SQLITE_NOMEM;
   115738   pNew->prereq = 0;
   115739   pNew->rSetup = 0;
   115740   pNew->wsFlags = WHERE_VIRTUALTABLE;
   115741   pNew->nLTerm = 0;
   115742   pNew->u.vtab.needFree = 0;
   115743   pUsage = pIdxInfo->aConstraintUsage;
   115744   nConstraint = pIdxInfo->nConstraint;
   115745   if( whereLoopResize(db, pNew, nConstraint) ){
   115746     sqlite3DbFree(db, pIdxInfo);
   115747     return SQLITE_NOMEM;
   115748   }
   115749 
   115750   for(iPhase=0; iPhase<=3; iPhase++){
   115751     if( !seenIn && (iPhase&1)!=0 ){
   115752       iPhase++;
   115753       if( iPhase>3 ) break;
   115754     }
   115755     if( !seenVar && iPhase>1 ) break;
   115756     pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
   115757     for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
   115758       j = pIdxCons->iTermOffset;
   115759       pTerm = &pWC->a[j];
   115760       switch( iPhase ){
   115761         case 0:    /* Constants without IN operator */
   115762           pIdxCons->usable = 0;
   115763           if( (pTerm->eOperator & WO_IN)!=0 ){
   115764             seenIn = 1;
   115765           }
   115766           if( pTerm->prereqRight!=0 ){
   115767             seenVar = 1;
   115768           }else if( (pTerm->eOperator & WO_IN)==0 ){
   115769             pIdxCons->usable = 1;
   115770           }
   115771           break;
   115772         case 1:    /* Constants with IN operators */
   115773           assert( seenIn );
   115774           pIdxCons->usable = (pTerm->prereqRight==0);
   115775           break;
   115776         case 2:    /* Variables without IN */
   115777           assert( seenVar );
   115778           pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
   115779           break;
   115780         default:   /* Variables with IN */
   115781           assert( seenVar && seenIn );
   115782           pIdxCons->usable = 1;
   115783           break;
   115784       }
   115785     }
   115786     memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
   115787     if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
   115788     pIdxInfo->idxStr = 0;
   115789     pIdxInfo->idxNum = 0;
   115790     pIdxInfo->needToFreeIdxStr = 0;
   115791     pIdxInfo->orderByConsumed = 0;
   115792     pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
   115793     pIdxInfo->estimatedRows = 25;
   115794     rc = vtabBestIndex(pParse, pTab, pIdxInfo);
   115795     if( rc ) goto whereLoopAddVtab_exit;
   115796     pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
   115797     pNew->prereq = mExtra;
   115798     mxTerm = -1;
   115799     assert( pNew->nLSlot>=nConstraint );
   115800     for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
   115801     pNew->u.vtab.omitMask = 0;
   115802     for(i=0; i<nConstraint; i++, pIdxCons++){
   115803       if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
   115804         j = pIdxCons->iTermOffset;
   115805         if( iTerm>=nConstraint
   115806          || j<0
   115807          || j>=pWC->nTerm
   115808          || pNew->aLTerm[iTerm]!=0
   115809         ){
   115810           rc = SQLITE_ERROR;
   115811           sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
   115812           goto whereLoopAddVtab_exit;
   115813         }
   115814         testcase( iTerm==nConstraint-1 );
   115815         testcase( j==0 );
   115816         testcase( j==pWC->nTerm-1 );
   115817         pTerm = &pWC->a[j];
   115818         pNew->prereq |= pTerm->prereqRight;
   115819         assert( iTerm<pNew->nLSlot );
   115820         pNew->aLTerm[iTerm] = pTerm;
   115821         if( iTerm>mxTerm ) mxTerm = iTerm;
   115822         testcase( iTerm==15 );
   115823         testcase( iTerm==16 );
   115824         if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
   115825         if( (pTerm->eOperator & WO_IN)!=0 ){
   115826           if( pUsage[i].omit==0 ){
   115827             /* Do not attempt to use an IN constraint if the virtual table
   115828             ** says that the equivalent EQ constraint cannot be safely omitted.
   115829             ** If we do attempt to use such a constraint, some rows might be
   115830             ** repeated in the output. */
   115831             break;
   115832           }
   115833           /* A virtual table that is constrained by an IN clause may not
   115834           ** consume the ORDER BY clause because (1) the order of IN terms
   115835           ** is not necessarily related to the order of output terms and
   115836           ** (2) Multiple outputs from a single IN value will not merge
   115837           ** together.  */
   115838           pIdxInfo->orderByConsumed = 0;
   115839         }
   115840       }
   115841     }
   115842     if( i>=nConstraint ){
   115843       pNew->nLTerm = mxTerm+1;
   115844       assert( pNew->nLTerm<=pNew->nLSlot );
   115845       pNew->u.vtab.idxNum = pIdxInfo->idxNum;
   115846       pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
   115847       pIdxInfo->needToFreeIdxStr = 0;
   115848       pNew->u.vtab.idxStr = pIdxInfo->idxStr;
   115849       pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
   115850                                       pIdxInfo->nOrderBy : 0);
   115851       pNew->rSetup = 0;
   115852       pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
   115853       pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
   115854       whereLoopInsert(pBuilder, pNew);
   115855       if( pNew->u.vtab.needFree ){
   115856         sqlite3_free(pNew->u.vtab.idxStr);
   115857         pNew->u.vtab.needFree = 0;
   115858       }
   115859     }
   115860   }
   115861 
   115862 whereLoopAddVtab_exit:
   115863   if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
   115864   sqlite3DbFree(db, pIdxInfo);
   115865   return rc;
   115866 }
   115867 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   115868 
   115869 /*
   115870 ** Add WhereLoop entries to handle OR terms.  This works for either
   115871 ** btrees or virtual tables.
   115872 */
   115873 static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){
   115874   WhereInfo *pWInfo = pBuilder->pWInfo;
   115875   WhereClause *pWC;
   115876   WhereLoop *pNew;
   115877   WhereTerm *pTerm, *pWCEnd;
   115878   int rc = SQLITE_OK;
   115879   int iCur;
   115880   WhereClause tempWC;
   115881   WhereLoopBuilder sSubBuild;
   115882   WhereOrSet sSum, sCur;
   115883   struct SrcList_item *pItem;
   115884 
   115885   pWC = pBuilder->pWC;
   115886   if( pWInfo->wctrlFlags & WHERE_AND_ONLY ) return SQLITE_OK;
   115887   pWCEnd = pWC->a + pWC->nTerm;
   115888   pNew = pBuilder->pNew;
   115889   memset(&sSum, 0, sizeof(sSum));
   115890   pItem = pWInfo->pTabList->a + pNew->iTab;
   115891   iCur = pItem->iCursor;
   115892 
   115893   for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
   115894     if( (pTerm->eOperator & WO_OR)!=0
   115895      && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
   115896     ){
   115897       WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
   115898       WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
   115899       WhereTerm *pOrTerm;
   115900       int once = 1;
   115901       int i, j;
   115902 
   115903       sSubBuild = *pBuilder;
   115904       sSubBuild.pOrderBy = 0;
   115905       sSubBuild.pOrSet = &sCur;
   115906 
   115907       for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
   115908         if( (pOrTerm->eOperator & WO_AND)!=0 ){
   115909           sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
   115910         }else if( pOrTerm->leftCursor==iCur ){
   115911           tempWC.pWInfo = pWC->pWInfo;
   115912           tempWC.pOuter = pWC;
   115913           tempWC.op = TK_AND;
   115914           tempWC.nTerm = 1;
   115915           tempWC.a = pOrTerm;
   115916           sSubBuild.pWC = &tempWC;
   115917         }else{
   115918           continue;
   115919         }
   115920         sCur.n = 0;
   115921 #ifndef SQLITE_OMIT_VIRTUALTABLE
   115922         if( IsVirtual(pItem->pTab) ){
   115923           rc = whereLoopAddVirtual(&sSubBuild, mExtra);
   115924         }else
   115925 #endif
   115926         {
   115927           rc = whereLoopAddBtree(&sSubBuild, mExtra);
   115928         }
   115929         assert( rc==SQLITE_OK || sCur.n==0 );
   115930         if( sCur.n==0 ){
   115931           sSum.n = 0;
   115932           break;
   115933         }else if( once ){
   115934           whereOrMove(&sSum, &sCur);
   115935           once = 0;
   115936         }else{
   115937           WhereOrSet sPrev;
   115938           whereOrMove(&sPrev, &sSum);
   115939           sSum.n = 0;
   115940           for(i=0; i<sPrev.n; i++){
   115941             for(j=0; j<sCur.n; j++){
   115942               whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
   115943                             sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
   115944                             sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
   115945             }
   115946           }
   115947         }
   115948       }
   115949       pNew->nLTerm = 1;
   115950       pNew->aLTerm[0] = pTerm;
   115951       pNew->wsFlags = WHERE_MULTI_OR;
   115952       pNew->rSetup = 0;
   115953       pNew->iSortIdx = 0;
   115954       memset(&pNew->u, 0, sizeof(pNew->u));
   115955       for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
   115956         /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
   115957         ** of all sub-scans required by the OR-scan. However, due to rounding
   115958         ** errors, it may be that the cost of the OR-scan is equal to its
   115959         ** most expensive sub-scan. Add the smallest possible penalty
   115960         ** (equivalent to multiplying the cost by 1.07) to ensure that
   115961         ** this does not happen. Otherwise, for WHERE clauses such as the
   115962         ** following where there is an index on "y":
   115963         **
   115964         **     WHERE likelihood(x=?, 0.99) OR y=?
   115965         **
   115966         ** the planner may elect to "OR" together a full-table scan and an
   115967         ** index lookup. And other similarly odd results.  */
   115968         pNew->rRun = sSum.a[i].rRun + 1;
   115969         pNew->nOut = sSum.a[i].nOut;
   115970         pNew->prereq = sSum.a[i].prereq;
   115971         rc = whereLoopInsert(pBuilder, pNew);
   115972       }
   115973     }
   115974   }
   115975   return rc;
   115976 }
   115977 
   115978 /*
   115979 ** Add all WhereLoop objects for all tables
   115980 */
   115981 static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
   115982   WhereInfo *pWInfo = pBuilder->pWInfo;
   115983   Bitmask mExtra = 0;
   115984   Bitmask mPrior = 0;
   115985   int iTab;
   115986   SrcList *pTabList = pWInfo->pTabList;
   115987   struct SrcList_item *pItem;
   115988   sqlite3 *db = pWInfo->pParse->db;
   115989   int nTabList = pWInfo->nLevel;
   115990   int rc = SQLITE_OK;
   115991   u8 priorJoinType = 0;
   115992   WhereLoop *pNew;
   115993 
   115994   /* Loop over the tables in the join, from left to right */
   115995   pNew = pBuilder->pNew;
   115996   whereLoopInit(pNew);
   115997   for(iTab=0, pItem=pTabList->a; iTab<nTabList; iTab++, pItem++){
   115998     pNew->iTab = iTab;
   115999     pNew->maskSelf = getMask(&pWInfo->sMaskSet, pItem->iCursor);
   116000     if( ((pItem->jointype|priorJoinType) & (JT_LEFT|JT_CROSS))!=0 ){
   116001       mExtra = mPrior;
   116002     }
   116003     priorJoinType = pItem->jointype;
   116004     if( IsVirtual(pItem->pTab) ){
   116005       rc = whereLoopAddVirtual(pBuilder, mExtra);
   116006     }else{
   116007       rc = whereLoopAddBtree(pBuilder, mExtra);
   116008     }
   116009     if( rc==SQLITE_OK ){
   116010       rc = whereLoopAddOr(pBuilder, mExtra);
   116011     }
   116012     mPrior |= pNew->maskSelf;
   116013     if( rc || db->mallocFailed ) break;
   116014   }
   116015   whereLoopClear(db, pNew);
   116016   return rc;
   116017 }
   116018 
   116019 /*
   116020 ** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
   116021 ** parameters) to see if it outputs rows in the requested ORDER BY
   116022 ** (or GROUP BY) without requiring a separate sort operation.  Return N:
   116023 **
   116024 **   N>0:   N terms of the ORDER BY clause are satisfied
   116025 **   N==0:  No terms of the ORDER BY clause are satisfied
   116026 **   N<0:   Unknown yet how many terms of ORDER BY might be satisfied.
   116027 **
   116028 ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
   116029 ** strict.  With GROUP BY and DISTINCT the only requirement is that
   116030 ** equivalent rows appear immediately adjacent to one another.  GROUP BY
   116031 ** and DISTINCT do not require rows to appear in any particular order as long
   116032 ** as equivelent rows are grouped together.  Thus for GROUP BY and DISTINCT
   116033 ** the pOrderBy terms can be matched in any order.  With ORDER BY, the
   116034 ** pOrderBy terms must be matched in strict left-to-right order.
   116035 */
   116036 static i8 wherePathSatisfiesOrderBy(
   116037   WhereInfo *pWInfo,    /* The WHERE clause */
   116038   ExprList *pOrderBy,   /* ORDER BY or GROUP BY or DISTINCT clause to check */
   116039   WherePath *pPath,     /* The WherePath to check */
   116040   u16 wctrlFlags,       /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
   116041   u16 nLoop,            /* Number of entries in pPath->aLoop[] */
   116042   WhereLoop *pLast,     /* Add this WhereLoop to the end of pPath->aLoop[] */
   116043   Bitmask *pRevMask     /* OUT: Mask of WhereLoops to run in reverse order */
   116044 ){
   116045   u8 revSet;            /* True if rev is known */
   116046   u8 rev;               /* Composite sort order */
   116047   u8 revIdx;            /* Index sort order */
   116048   u8 isOrderDistinct;   /* All prior WhereLoops are order-distinct */
   116049   u8 distinctColumns;   /* True if the loop has UNIQUE NOT NULL columns */
   116050   u8 isMatch;           /* iColumn matches a term of the ORDER BY clause */
   116051   u16 nKeyCol;          /* Number of key columns in pIndex */
   116052   u16 nColumn;          /* Total number of ordered columns in the index */
   116053   u16 nOrderBy;         /* Number terms in the ORDER BY clause */
   116054   int iLoop;            /* Index of WhereLoop in pPath being processed */
   116055   int i, j;             /* Loop counters */
   116056   int iCur;             /* Cursor number for current WhereLoop */
   116057   int iColumn;          /* A column number within table iCur */
   116058   WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
   116059   WhereTerm *pTerm;     /* A single term of the WHERE clause */
   116060   Expr *pOBExpr;        /* An expression from the ORDER BY clause */
   116061   CollSeq *pColl;       /* COLLATE function from an ORDER BY clause term */
   116062   Index *pIndex;        /* The index associated with pLoop */
   116063   sqlite3 *db = pWInfo->pParse->db;  /* Database connection */
   116064   Bitmask obSat = 0;    /* Mask of ORDER BY terms satisfied so far */
   116065   Bitmask obDone;       /* Mask of all ORDER BY terms */
   116066   Bitmask orderDistinctMask;  /* Mask of all well-ordered loops */
   116067   Bitmask ready;              /* Mask of inner loops */
   116068 
   116069   /*
   116070   ** We say the WhereLoop is "one-row" if it generates no more than one
   116071   ** row of output.  A WhereLoop is one-row if all of the following are true:
   116072   **  (a) All index columns match with WHERE_COLUMN_EQ.
   116073   **  (b) The index is unique
   116074   ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
   116075   ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
   116076   **
   116077   ** We say the WhereLoop is "order-distinct" if the set of columns from
   116078   ** that WhereLoop that are in the ORDER BY clause are different for every
   116079   ** row of the WhereLoop.  Every one-row WhereLoop is automatically
   116080   ** order-distinct.   A WhereLoop that has no columns in the ORDER BY clause
   116081   ** is not order-distinct. To be order-distinct is not quite the same as being
   116082   ** UNIQUE since a UNIQUE column or index can have multiple rows that
   116083   ** are NULL and NULL values are equivalent for the purpose of order-distinct.
   116084   ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
   116085   **
   116086   ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
   116087   ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
   116088   ** automatically order-distinct.
   116089   */
   116090 
   116091   assert( pOrderBy!=0 );
   116092   if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
   116093 
   116094   nOrderBy = pOrderBy->nExpr;
   116095   testcase( nOrderBy==BMS-1 );
   116096   if( nOrderBy>BMS-1 ) return 0;  /* Cannot optimize overly large ORDER BYs */
   116097   isOrderDistinct = 1;
   116098   obDone = MASKBIT(nOrderBy)-1;
   116099   orderDistinctMask = 0;
   116100   ready = 0;
   116101   for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
   116102     if( iLoop>0 ) ready |= pLoop->maskSelf;
   116103     pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
   116104     if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
   116105       if( pLoop->u.vtab.isOrdered ) obSat = obDone;
   116106       break;
   116107     }
   116108     iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
   116109 
   116110     /* Mark off any ORDER BY term X that is a column in the table of
   116111     ** the current loop for which there is term in the WHERE
   116112     ** clause of the form X IS NULL or X=? that reference only outer
   116113     ** loops.
   116114     */
   116115     for(i=0; i<nOrderBy; i++){
   116116       if( MASKBIT(i) & obSat ) continue;
   116117       pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
   116118       if( pOBExpr->op!=TK_COLUMN ) continue;
   116119       if( pOBExpr->iTable!=iCur ) continue;
   116120       pTerm = findTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
   116121                        ~ready, WO_EQ|WO_ISNULL, 0);
   116122       if( pTerm==0 ) continue;
   116123       if( (pTerm->eOperator&WO_EQ)!=0 && pOBExpr->iColumn>=0 ){
   116124         const char *z1, *z2;
   116125         pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
   116126         if( !pColl ) pColl = db->pDfltColl;
   116127         z1 = pColl->zName;
   116128         pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
   116129         if( !pColl ) pColl = db->pDfltColl;
   116130         z2 = pColl->zName;
   116131         if( sqlite3StrICmp(z1, z2)!=0 ) continue;
   116132       }
   116133       obSat |= MASKBIT(i);
   116134     }
   116135 
   116136     if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
   116137       if( pLoop->wsFlags & WHERE_IPK ){
   116138         pIndex = 0;
   116139         nKeyCol = 0;
   116140         nColumn = 1;
   116141       }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
   116142         return 0;
   116143       }else{
   116144         nKeyCol = pIndex->nKeyCol;
   116145         nColumn = pIndex->nColumn;
   116146         assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
   116147         assert( pIndex->aiColumn[nColumn-1]==(-1) || !HasRowid(pIndex->pTable));
   116148         isOrderDistinct = IsUniqueIndex(pIndex);
   116149       }
   116150 
   116151       /* Loop through all columns of the index and deal with the ones
   116152       ** that are not constrained by == or IN.
   116153       */
   116154       rev = revSet = 0;
   116155       distinctColumns = 0;
   116156       for(j=0; j<nColumn; j++){
   116157         u8 bOnce;   /* True to run the ORDER BY search loop */
   116158 
   116159         /* Skip over == and IS NULL terms */
   116160         if( j<pLoop->u.btree.nEq
   116161          && pLoop->u.btree.nSkip==0
   116162          && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL))!=0
   116163         ){
   116164           if( i & WO_ISNULL ){
   116165             testcase( isOrderDistinct );
   116166             isOrderDistinct = 0;
   116167           }
   116168           continue;
   116169         }
   116170 
   116171         /* Get the column number in the table (iColumn) and sort order
   116172         ** (revIdx) for the j-th column of the index.
   116173         */
   116174         if( pIndex ){
   116175           iColumn = pIndex->aiColumn[j];
   116176           revIdx = pIndex->aSortOrder[j];
   116177           if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
   116178         }else{
   116179           iColumn = -1;
   116180           revIdx = 0;
   116181         }
   116182 
   116183         /* An unconstrained column that might be NULL means that this
   116184         ** WhereLoop is not well-ordered
   116185         */
   116186         if( isOrderDistinct
   116187          && iColumn>=0
   116188          && j>=pLoop->u.btree.nEq
   116189          && pIndex->pTable->aCol[iColumn].notNull==0
   116190         ){
   116191           isOrderDistinct = 0;
   116192         }
   116193 
   116194         /* Find the ORDER BY term that corresponds to the j-th column
   116195         ** of the index and mark that ORDER BY term off
   116196         */
   116197         bOnce = 1;
   116198         isMatch = 0;
   116199         for(i=0; bOnce && i<nOrderBy; i++){
   116200           if( MASKBIT(i) & obSat ) continue;
   116201           pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
   116202           testcase( wctrlFlags & WHERE_GROUPBY );
   116203           testcase( wctrlFlags & WHERE_DISTINCTBY );
   116204           if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
   116205           if( pOBExpr->op!=TK_COLUMN ) continue;
   116206           if( pOBExpr->iTable!=iCur ) continue;
   116207           if( pOBExpr->iColumn!=iColumn ) continue;
   116208           if( iColumn>=0 ){
   116209             pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
   116210             if( !pColl ) pColl = db->pDfltColl;
   116211             if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
   116212           }
   116213           isMatch = 1;
   116214           break;
   116215         }
   116216         if( isMatch && (pWInfo->wctrlFlags & WHERE_GROUPBY)==0 ){
   116217           /* Make sure the sort order is compatible in an ORDER BY clause.
   116218           ** Sort order is irrelevant for a GROUP BY clause. */
   116219           if( revSet ){
   116220             if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
   116221           }else{
   116222             rev = revIdx ^ pOrderBy->a[i].sortOrder;
   116223             if( rev ) *pRevMask |= MASKBIT(iLoop);
   116224             revSet = 1;
   116225           }
   116226         }
   116227         if( isMatch ){
   116228           if( iColumn<0 ){
   116229             testcase( distinctColumns==0 );
   116230             distinctColumns = 1;
   116231           }
   116232           obSat |= MASKBIT(i);
   116233         }else{
   116234           /* No match found */
   116235           if( j==0 || j<nKeyCol ){
   116236             testcase( isOrderDistinct!=0 );
   116237             isOrderDistinct = 0;
   116238           }
   116239           break;
   116240         }
   116241       } /* end Loop over all index columns */
   116242       if( distinctColumns ){
   116243         testcase( isOrderDistinct==0 );
   116244         isOrderDistinct = 1;
   116245       }
   116246     } /* end-if not one-row */
   116247 
   116248     /* Mark off any other ORDER BY terms that reference pLoop */
   116249     if( isOrderDistinct ){
   116250       orderDistinctMask |= pLoop->maskSelf;
   116251       for(i=0; i<nOrderBy; i++){
   116252         Expr *p;
   116253         Bitmask mTerm;
   116254         if( MASKBIT(i) & obSat ) continue;
   116255         p = pOrderBy->a[i].pExpr;
   116256         mTerm = exprTableUsage(&pWInfo->sMaskSet,p);
   116257         if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
   116258         if( (mTerm&~orderDistinctMask)==0 ){
   116259           obSat |= MASKBIT(i);
   116260         }
   116261       }
   116262     }
   116263   } /* End the loop over all WhereLoops from outer-most down to inner-most */
   116264   if( obSat==obDone ) return (i8)nOrderBy;
   116265   if( !isOrderDistinct ){
   116266     for(i=nOrderBy-1; i>0; i--){
   116267       Bitmask m = MASKBIT(i) - 1;
   116268       if( (obSat&m)==m ) return i;
   116269     }
   116270     return 0;
   116271   }
   116272   return -1;
   116273 }
   116274 
   116275 
   116276 /*
   116277 ** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
   116278 ** the planner assumes that the specified pOrderBy list is actually a GROUP
   116279 ** BY clause - and so any order that groups rows as required satisfies the
   116280 ** request.
   116281 **
   116282 ** Normally, in this case it is not possible for the caller to determine
   116283 ** whether or not the rows are really being delivered in sorted order, or
   116284 ** just in some other order that provides the required grouping. However,
   116285 ** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
   116286 ** this function may be called on the returned WhereInfo object. It returns
   116287 ** true if the rows really will be sorted in the specified order, or false
   116288 ** otherwise.
   116289 **
   116290 ** For example, assuming:
   116291 **
   116292 **   CREATE INDEX i1 ON t1(x, Y);
   116293 **
   116294 ** then
   116295 **
   116296 **   SELECT * FROM t1 GROUP BY x,y ORDER BY x,y;   -- IsSorted()==1
   116297 **   SELECT * FROM t1 GROUP BY y,x ORDER BY y,x;   -- IsSorted()==0
   116298 */
   116299 SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){
   116300   assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
   116301   assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
   116302   return pWInfo->sorted;
   116303 }
   116304 
   116305 #ifdef WHERETRACE_ENABLED
   116306 /* For debugging use only: */
   116307 static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
   116308   static char zName[65];
   116309   int i;
   116310   for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
   116311   if( pLast ) zName[i++] = pLast->cId;
   116312   zName[i] = 0;
   116313   return zName;
   116314 }
   116315 #endif
   116316 
   116317 /*
   116318 ** Return the cost of sorting nRow rows, assuming that the keys have
   116319 ** nOrderby columns and that the first nSorted columns are already in
   116320 ** order.
   116321 */
   116322 static LogEst whereSortingCost(
   116323   WhereInfo *pWInfo,
   116324   LogEst nRow,
   116325   int nOrderBy,
   116326   int nSorted
   116327 ){
   116328   /* TUNING: Estimated cost of a full external sort, where N is
   116329   ** the number of rows to sort is:
   116330   **
   116331   **   cost = (3.0 * N * log(N)).
   116332   **
   116333   ** Or, if the order-by clause has X terms but only the last Y
   116334   ** terms are out of order, then block-sorting will reduce the
   116335   ** sorting cost to:
   116336   **
   116337   **   cost = (3.0 * N * log(N)) * (Y/X)
   116338   **
   116339   ** The (Y/X) term is implemented using stack variable rScale
   116340   ** below.  */
   116341   LogEst rScale, rSortCost;
   116342   assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
   116343   rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
   116344   rSortCost = nRow + estLog(nRow) + rScale + 16;
   116345 
   116346   /* TUNING: The cost of implementing DISTINCT using a B-TREE is
   116347   ** similar but with a larger constant of proportionality.
   116348   ** Multiply by an additional factor of 3.0.  */
   116349   if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
   116350     rSortCost += 16;
   116351   }
   116352 
   116353   return rSortCost;
   116354 }
   116355 
   116356 /*
   116357 ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
   116358 ** attempts to find the lowest cost path that visits each WhereLoop
   116359 ** once.  This path is then loaded into the pWInfo->a[].pWLoop fields.
   116360 **
   116361 ** Assume that the total number of output rows that will need to be sorted
   116362 ** will be nRowEst (in the 10*log2 representation).  Or, ignore sorting
   116363 ** costs if nRowEst==0.
   116364 **
   116365 ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
   116366 ** error occurs.
   116367 */
   116368 static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
   116369   int mxChoice;             /* Maximum number of simultaneous paths tracked */
   116370   int nLoop;                /* Number of terms in the join */
   116371   Parse *pParse;            /* Parsing context */
   116372   sqlite3 *db;              /* The database connection */
   116373   int iLoop;                /* Loop counter over the terms of the join */
   116374   int ii, jj;               /* Loop counters */
   116375   int mxI = 0;              /* Index of next entry to replace */
   116376   int nOrderBy;             /* Number of ORDER BY clause terms */
   116377   LogEst mxCost = 0;        /* Maximum cost of a set of paths */
   116378   LogEst mxUnsorted = 0;    /* Maximum unsorted cost of a set of path */
   116379   int nTo, nFrom;           /* Number of valid entries in aTo[] and aFrom[] */
   116380   WherePath *aFrom;         /* All nFrom paths at the previous level */
   116381   WherePath *aTo;           /* The nTo best paths at the current level */
   116382   WherePath *pFrom;         /* An element of aFrom[] that we are working on */
   116383   WherePath *pTo;           /* An element of aTo[] that we are working on */
   116384   WhereLoop *pWLoop;        /* One of the WhereLoop objects */
   116385   WhereLoop **pX;           /* Used to divy up the pSpace memory */
   116386   LogEst *aSortCost = 0;    /* Sorting and partial sorting costs */
   116387   char *pSpace;             /* Temporary memory used by this routine */
   116388   int nSpace;               /* Bytes of space allocated at pSpace */
   116389 
   116390   pParse = pWInfo->pParse;
   116391   db = pParse->db;
   116392   nLoop = pWInfo->nLevel;
   116393   /* TUNING: For simple queries, only the best path is tracked.
   116394   ** For 2-way joins, the 5 best paths are followed.
   116395   ** For joins of 3 or more tables, track the 10 best paths */
   116396   mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
   116397   assert( nLoop<=pWInfo->pTabList->nSrc );
   116398   WHERETRACE(0x002, ("---- begin solver.  (nRowEst=%d)\n", nRowEst));
   116399 
   116400   /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
   116401   ** case the purpose of this call is to estimate the number of rows returned
   116402   ** by the overall query. Once this estimate has been obtained, the caller
   116403   ** will invoke this function a second time, passing the estimate as the
   116404   ** nRowEst parameter.  */
   116405   if( pWInfo->pOrderBy==0 || nRowEst==0 ){
   116406     nOrderBy = 0;
   116407   }else{
   116408     nOrderBy = pWInfo->pOrderBy->nExpr;
   116409   }
   116410 
   116411   /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
   116412   nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
   116413   nSpace += sizeof(LogEst) * nOrderBy;
   116414   pSpace = sqlite3DbMallocRaw(db, nSpace);
   116415   if( pSpace==0 ) return SQLITE_NOMEM;
   116416   aTo = (WherePath*)pSpace;
   116417   aFrom = aTo+mxChoice;
   116418   memset(aFrom, 0, sizeof(aFrom[0]));
   116419   pX = (WhereLoop**)(aFrom+mxChoice);
   116420   for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
   116421     pFrom->aLoop = pX;
   116422   }
   116423   if( nOrderBy ){
   116424     /* If there is an ORDER BY clause and it is not being ignored, set up
   116425     ** space for the aSortCost[] array. Each element of the aSortCost array
   116426     ** is either zero - meaning it has not yet been initialized - or the
   116427     ** cost of sorting nRowEst rows of data where the first X terms of
   116428     ** the ORDER BY clause are already in order, where X is the array
   116429     ** index.  */
   116430     aSortCost = (LogEst*)pX;
   116431     memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
   116432   }
   116433   assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
   116434   assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
   116435 
   116436   /* Seed the search with a single WherePath containing zero WhereLoops.
   116437   **
   116438   ** TUNING: Do not let the number of iterations go above 25.  If the cost
   116439   ** of computing an automatic index is not paid back within the first 25
   116440   ** rows, then do not use the automatic index. */
   116441   aFrom[0].nRow = MIN(pParse->nQueryLoop, 46);  assert( 46==sqlite3LogEst(25) );
   116442   nFrom = 1;
   116443   assert( aFrom[0].isOrdered==0 );
   116444   if( nOrderBy ){
   116445     /* If nLoop is zero, then there are no FROM terms in the query. Since
   116446     ** in this case the query may return a maximum of one row, the results
   116447     ** are already in the requested order. Set isOrdered to nOrderBy to
   116448     ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
   116449     ** -1, indicating that the result set may or may not be ordered,
   116450     ** depending on the loops added to the current plan.  */
   116451     aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
   116452   }
   116453 
   116454   /* Compute successively longer WherePaths using the previous generation
   116455   ** of WherePaths as the basis for the next.  Keep track of the mxChoice
   116456   ** best paths at each generation */
   116457   for(iLoop=0; iLoop<nLoop; iLoop++){
   116458     nTo = 0;
   116459     for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
   116460       for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
   116461         LogEst nOut;                      /* Rows visited by (pFrom+pWLoop) */
   116462         LogEst rCost;                     /* Cost of path (pFrom+pWLoop) */
   116463         LogEst rUnsorted;                 /* Unsorted cost of (pFrom+pWLoop) */
   116464         i8 isOrdered = pFrom->isOrdered;  /* isOrdered for (pFrom+pWLoop) */
   116465         Bitmask maskNew;                  /* Mask of src visited by (..) */
   116466         Bitmask revMask = 0;              /* Mask of rev-order loops for (..) */
   116467 
   116468         if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
   116469         if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
   116470         /* At this point, pWLoop is a candidate to be the next loop.
   116471         ** Compute its cost */
   116472         rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
   116473         rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
   116474         nOut = pFrom->nRow + pWLoop->nOut;
   116475         maskNew = pFrom->maskLoop | pWLoop->maskSelf;
   116476         if( isOrdered<0 ){
   116477           isOrdered = wherePathSatisfiesOrderBy(pWInfo,
   116478                        pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
   116479                        iLoop, pWLoop, &revMask);
   116480         }else{
   116481           revMask = pFrom->revLoop;
   116482         }
   116483         if( isOrdered>=0 && isOrdered<nOrderBy ){
   116484           if( aSortCost[isOrdered]==0 ){
   116485             aSortCost[isOrdered] = whereSortingCost(
   116486                 pWInfo, nRowEst, nOrderBy, isOrdered
   116487             );
   116488           }
   116489           rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]);
   116490 
   116491           WHERETRACE(0x002,
   116492               ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
   116493                aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
   116494                rUnsorted, rCost));
   116495         }else{
   116496           rCost = rUnsorted;
   116497         }
   116498 
   116499         /* Check to see if pWLoop should be added to the set of
   116500         ** mxChoice best-so-far paths.
   116501         **
   116502         ** First look for an existing path among best-so-far paths
   116503         ** that covers the same set of loops and has the same isOrdered
   116504         ** setting as the current path candidate.
   116505         **
   116506         ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
   116507         ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
   116508         ** of legal values for isOrdered, -1..64.
   116509         */
   116510         for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
   116511           if( pTo->maskLoop==maskNew
   116512            && ((pTo->isOrdered^isOrdered)&0x80)==0
   116513           ){
   116514             testcase( jj==nTo-1 );
   116515             break;
   116516           }
   116517         }
   116518         if( jj>=nTo ){
   116519           /* None of the existing best-so-far paths match the candidate. */
   116520           if( nTo>=mxChoice
   116521            && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
   116522           ){
   116523             /* The current candidate is no better than any of the mxChoice
   116524             ** paths currently in the best-so-far buffer.  So discard
   116525             ** this candidate as not viable. */
   116526 #ifdef WHERETRACE_ENABLED /* 0x4 */
   116527             if( sqlite3WhereTrace&0x4 ){
   116528               sqlite3DebugPrintf("Skip   %s cost=%-3d,%3d order=%c\n",
   116529                   wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
   116530                   isOrdered>=0 ? isOrdered+'0' : '?');
   116531             }
   116532 #endif
   116533             continue;
   116534           }
   116535           /* If we reach this points it means that the new candidate path
   116536           ** needs to be added to the set of best-so-far paths. */
   116537           if( nTo<mxChoice ){
   116538             /* Increase the size of the aTo set by one */
   116539             jj = nTo++;
   116540           }else{
   116541             /* New path replaces the prior worst to keep count below mxChoice */
   116542             jj = mxI;
   116543           }
   116544           pTo = &aTo[jj];
   116545 #ifdef WHERETRACE_ENABLED /* 0x4 */
   116546           if( sqlite3WhereTrace&0x4 ){
   116547             sqlite3DebugPrintf("New    %s cost=%-3d,%3d order=%c\n",
   116548                 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
   116549                 isOrdered>=0 ? isOrdered+'0' : '?');
   116550           }
   116551 #endif
   116552         }else{
   116553           /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
   116554           ** same set of loops and has the sam isOrdered setting as the
   116555           ** candidate path.  Check to see if the candidate should replace
   116556           ** pTo or if the candidate should be skipped */
   116557           if( pTo->rCost<rCost || (pTo->rCost==rCost && pTo->nRow<=nOut) ){
   116558 #ifdef WHERETRACE_ENABLED /* 0x4 */
   116559             if( sqlite3WhereTrace&0x4 ){
   116560               sqlite3DebugPrintf(
   116561                   "Skip   %s cost=%-3d,%3d order=%c",
   116562                   wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
   116563                   isOrdered>=0 ? isOrdered+'0' : '?');
   116564               sqlite3DebugPrintf("   vs %s cost=%-3d,%d order=%c\n",
   116565                   wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
   116566                   pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
   116567             }
   116568 #endif
   116569             /* Discard the candidate path from further consideration */
   116570             testcase( pTo->rCost==rCost );
   116571             continue;
   116572           }
   116573           testcase( pTo->rCost==rCost+1 );
   116574           /* Control reaches here if the candidate path is better than the
   116575           ** pTo path.  Replace pTo with the candidate. */
   116576 #ifdef WHERETRACE_ENABLED /* 0x4 */
   116577           if( sqlite3WhereTrace&0x4 ){
   116578             sqlite3DebugPrintf(
   116579                 "Update %s cost=%-3d,%3d order=%c",
   116580                 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
   116581                 isOrdered>=0 ? isOrdered+'0' : '?');
   116582             sqlite3DebugPrintf("  was %s cost=%-3d,%3d order=%c\n",
   116583                 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
   116584                 pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
   116585           }
   116586 #endif
   116587         }
   116588         /* pWLoop is a winner.  Add it to the set of best so far */
   116589         pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
   116590         pTo->revLoop = revMask;
   116591         pTo->nRow = nOut;
   116592         pTo->rCost = rCost;
   116593         pTo->rUnsorted = rUnsorted;
   116594         pTo->isOrdered = isOrdered;
   116595         memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
   116596         pTo->aLoop[iLoop] = pWLoop;
   116597         if( nTo>=mxChoice ){
   116598           mxI = 0;
   116599           mxCost = aTo[0].rCost;
   116600           mxUnsorted = aTo[0].nRow;
   116601           for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
   116602             if( pTo->rCost>mxCost
   116603              || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
   116604             ){
   116605               mxCost = pTo->rCost;
   116606               mxUnsorted = pTo->rUnsorted;
   116607               mxI = jj;
   116608             }
   116609           }
   116610         }
   116611       }
   116612     }
   116613 
   116614 #ifdef WHERETRACE_ENABLED  /* >=2 */
   116615     if( sqlite3WhereTrace>=2 ){
   116616       sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
   116617       for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
   116618         sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
   116619            wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
   116620            pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
   116621         if( pTo->isOrdered>0 ){
   116622           sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
   116623         }else{
   116624           sqlite3DebugPrintf("\n");
   116625         }
   116626       }
   116627     }
   116628 #endif
   116629 
   116630     /* Swap the roles of aFrom and aTo for the next generation */
   116631     pFrom = aTo;
   116632     aTo = aFrom;
   116633     aFrom = pFrom;
   116634     nFrom = nTo;
   116635   }
   116636 
   116637   if( nFrom==0 ){
   116638     sqlite3ErrorMsg(pParse, "no query solution");
   116639     sqlite3DbFree(db, pSpace);
   116640     return SQLITE_ERROR;
   116641   }
   116642 
   116643   /* Find the lowest cost path.  pFrom will be left pointing to that path */
   116644   pFrom = aFrom;
   116645   for(ii=1; ii<nFrom; ii++){
   116646     if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
   116647   }
   116648   assert( pWInfo->nLevel==nLoop );
   116649   /* Load the lowest cost path into pWInfo */
   116650   for(iLoop=0; iLoop<nLoop; iLoop++){
   116651     WhereLevel *pLevel = pWInfo->a + iLoop;
   116652     pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
   116653     pLevel->iFrom = pWLoop->iTab;
   116654     pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
   116655   }
   116656   if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
   116657    && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
   116658    && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
   116659    && nRowEst
   116660   ){
   116661     Bitmask notUsed;
   116662     int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
   116663                  WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
   116664     if( rc==pWInfo->pResultSet->nExpr ){
   116665       pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
   116666     }
   116667   }
   116668   if( pWInfo->pOrderBy ){
   116669     if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
   116670       if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
   116671         pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
   116672       }
   116673     }else{
   116674       pWInfo->nOBSat = pFrom->isOrdered;
   116675       if( pWInfo->nOBSat<0 ) pWInfo->nOBSat = 0;
   116676       pWInfo->revMask = pFrom->revLoop;
   116677     }
   116678     if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
   116679         && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr
   116680     ){
   116681       Bitmask notUsed = 0;
   116682       int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
   116683           pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed
   116684       );
   116685       assert( pWInfo->sorted==0 );
   116686       pWInfo->sorted = (nOrder==pWInfo->pOrderBy->nExpr);
   116687     }
   116688   }
   116689 
   116690 
   116691   pWInfo->nRowOut = pFrom->nRow;
   116692 
   116693   /* Free temporary memory and return success */
   116694   sqlite3DbFree(db, pSpace);
   116695   return SQLITE_OK;
   116696 }
   116697 
   116698 /*
   116699 ** Most queries use only a single table (they are not joins) and have
   116700 ** simple == constraints against indexed fields.  This routine attempts
   116701 ** to plan those simple cases using much less ceremony than the
   116702 ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
   116703 ** times for the common case.
   116704 **
   116705 ** Return non-zero on success, if this query can be handled by this
   116706 ** no-frills query planner.  Return zero if this query needs the
   116707 ** general-purpose query planner.
   116708 */
   116709 static int whereShortCut(WhereLoopBuilder *pBuilder){
   116710   WhereInfo *pWInfo;
   116711   struct SrcList_item *pItem;
   116712   WhereClause *pWC;
   116713   WhereTerm *pTerm;
   116714   WhereLoop *pLoop;
   116715   int iCur;
   116716   int j;
   116717   Table *pTab;
   116718   Index *pIdx;
   116719 
   116720   pWInfo = pBuilder->pWInfo;
   116721   if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
   116722   assert( pWInfo->pTabList->nSrc>=1 );
   116723   pItem = pWInfo->pTabList->a;
   116724   pTab = pItem->pTab;
   116725   if( IsVirtual(pTab) ) return 0;
   116726   if( pItem->zIndex ) return 0;
   116727   iCur = pItem->iCursor;
   116728   pWC = &pWInfo->sWC;
   116729   pLoop = pBuilder->pNew;
   116730   pLoop->wsFlags = 0;
   116731   pLoop->u.btree.nSkip = 0;
   116732   pTerm = findTerm(pWC, iCur, -1, 0, WO_EQ, 0);
   116733   if( pTerm ){
   116734     pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
   116735     pLoop->aLTerm[0] = pTerm;
   116736     pLoop->nLTerm = 1;
   116737     pLoop->u.btree.nEq = 1;
   116738     /* TUNING: Cost of a rowid lookup is 10 */
   116739     pLoop->rRun = 33;  /* 33==sqlite3LogEst(10) */
   116740   }else{
   116741     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   116742       assert( pLoop->aLTermSpace==pLoop->aLTerm );
   116743       assert( ArraySize(pLoop->aLTermSpace)==4 );
   116744       if( !IsUniqueIndex(pIdx)
   116745        || pIdx->pPartIdxWhere!=0
   116746        || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
   116747       ) continue;
   116748       for(j=0; j<pIdx->nKeyCol; j++){
   116749         pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 0, WO_EQ, pIdx);
   116750         if( pTerm==0 ) break;
   116751         pLoop->aLTerm[j] = pTerm;
   116752       }
   116753       if( j!=pIdx->nKeyCol ) continue;
   116754       pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
   116755       if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
   116756         pLoop->wsFlags |= WHERE_IDX_ONLY;
   116757       }
   116758       pLoop->nLTerm = j;
   116759       pLoop->u.btree.nEq = j;
   116760       pLoop->u.btree.pIndex = pIdx;
   116761       /* TUNING: Cost of a unique index lookup is 15 */
   116762       pLoop->rRun = 39;  /* 39==sqlite3LogEst(15) */
   116763       break;
   116764     }
   116765   }
   116766   if( pLoop->wsFlags ){
   116767     pLoop->nOut = (LogEst)1;
   116768     pWInfo->a[0].pWLoop = pLoop;
   116769     pLoop->maskSelf = getMask(&pWInfo->sMaskSet, iCur);
   116770     pWInfo->a[0].iTabCur = iCur;
   116771     pWInfo->nRowOut = 1;
   116772     if( pWInfo->pOrderBy ) pWInfo->nOBSat =  pWInfo->pOrderBy->nExpr;
   116773     if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
   116774       pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
   116775     }
   116776 #ifdef SQLITE_DEBUG
   116777     pLoop->cId = '0';
   116778 #endif
   116779     return 1;
   116780   }
   116781   return 0;
   116782 }
   116783 
   116784 /*
   116785 ** Generate the beginning of the loop used for WHERE clause processing.
   116786 ** The return value is a pointer to an opaque structure that contains
   116787 ** information needed to terminate the loop.  Later, the calling routine
   116788 ** should invoke sqlite3WhereEnd() with the return value of this function
   116789 ** in order to complete the WHERE clause processing.
   116790 **
   116791 ** If an error occurs, this routine returns NULL.
   116792 **
   116793 ** The basic idea is to do a nested loop, one loop for each table in
   116794 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
   116795 ** same as a SELECT with only a single table in the FROM clause.)  For
   116796 ** example, if the SQL is this:
   116797 **
   116798 **       SELECT * FROM t1, t2, t3 WHERE ...;
   116799 **
   116800 ** Then the code generated is conceptually like the following:
   116801 **
   116802 **      foreach row1 in t1 do       \    Code generated
   116803 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
   116804 **          foreach row3 in t3 do   /
   116805 **            ...
   116806 **          end                     \    Code generated
   116807 **        end                        |-- by sqlite3WhereEnd()
   116808 **      end                         /
   116809 **
   116810 ** Note that the loops might not be nested in the order in which they
   116811 ** appear in the FROM clause if a different order is better able to make
   116812 ** use of indices.  Note also that when the IN operator appears in
   116813 ** the WHERE clause, it might result in additional nested loops for
   116814 ** scanning through all values on the right-hand side of the IN.
   116815 **
   116816 ** There are Btree cursors associated with each table.  t1 uses cursor
   116817 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
   116818 ** And so forth.  This routine generates code to open those VDBE cursors
   116819 ** and sqlite3WhereEnd() generates the code to close them.
   116820 **
   116821 ** The code that sqlite3WhereBegin() generates leaves the cursors named
   116822 ** in pTabList pointing at their appropriate entries.  The [...] code
   116823 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
   116824 ** data from the various tables of the loop.
   116825 **
   116826 ** If the WHERE clause is empty, the foreach loops must each scan their
   116827 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
   116828 ** the tables have indices and there are terms in the WHERE clause that
   116829 ** refer to those indices, a complete table scan can be avoided and the
   116830 ** code will run much faster.  Most of the work of this routine is checking
   116831 ** to see if there are indices that can be used to speed up the loop.
   116832 **
   116833 ** Terms of the WHERE clause are also used to limit which rows actually
   116834 ** make it to the "..." in the middle of the loop.  After each "foreach",
   116835 ** terms of the WHERE clause that use only terms in that loop and outer
   116836 ** loops are evaluated and if false a jump is made around all subsequent
   116837 ** inner loops (or around the "..." if the test occurs within the inner-
   116838 ** most loop)
   116839 **
   116840 ** OUTER JOINS
   116841 **
   116842 ** An outer join of tables t1 and t2 is conceptally coded as follows:
   116843 **
   116844 **    foreach row1 in t1 do
   116845 **      flag = 0
   116846 **      foreach row2 in t2 do
   116847 **        start:
   116848 **          ...
   116849 **          flag = 1
   116850 **      end
   116851 **      if flag==0 then
   116852 **        move the row2 cursor to a null row
   116853 **        goto start
   116854 **      fi
   116855 **    end
   116856 **
   116857 ** ORDER BY CLAUSE PROCESSING
   116858 **
   116859 ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
   116860 ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
   116861 ** if there is one.  If there is no ORDER BY clause or if this routine
   116862 ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
   116863 **
   116864 ** The iIdxCur parameter is the cursor number of an index.  If
   116865 ** WHERE_ONETABLE_ONLY is set, iIdxCur is the cursor number of an index
   116866 ** to use for OR clause processing.  The WHERE clause should use this
   116867 ** specific cursor.  If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
   116868 ** the first cursor in an array of cursors for all indices.  iIdxCur should
   116869 ** be used to compute the appropriate cursor depending on which index is
   116870 ** used.
   116871 */
   116872 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
   116873   Parse *pParse,        /* The parser context */
   116874   SrcList *pTabList,    /* FROM clause: A list of all tables to be scanned */
   116875   Expr *pWhere,         /* The WHERE clause */
   116876   ExprList *pOrderBy,   /* An ORDER BY (or GROUP BY) clause, or NULL */
   116877   ExprList *pResultSet, /* Result set of the query */
   116878   u16 wctrlFlags,       /* One of the WHERE_* flags defined in sqliteInt.h */
   116879   int iIdxCur           /* If WHERE_ONETABLE_ONLY is set, index cursor number */
   116880 ){
   116881   int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
   116882   int nTabList;              /* Number of elements in pTabList */
   116883   WhereInfo *pWInfo;         /* Will become the return value of this function */
   116884   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
   116885   Bitmask notReady;          /* Cursors that are not yet positioned */
   116886   WhereLoopBuilder sWLB;     /* The WhereLoop builder */
   116887   WhereMaskSet *pMaskSet;    /* The expression mask set */
   116888   WhereLevel *pLevel;        /* A single level in pWInfo->a[] */
   116889   WhereLoop *pLoop;          /* Pointer to a single WhereLoop object */
   116890   int ii;                    /* Loop counter */
   116891   sqlite3 *db;               /* Database connection */
   116892   int rc;                    /* Return code */
   116893 
   116894 
   116895   /* Variable initialization */
   116896   db = pParse->db;
   116897   memset(&sWLB, 0, sizeof(sWLB));
   116898 
   116899   /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
   116900   testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
   116901   if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
   116902   sWLB.pOrderBy = pOrderBy;
   116903 
   116904   /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
   116905   ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
   116906   if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
   116907     wctrlFlags &= ~WHERE_WANT_DISTINCT;
   116908   }
   116909 
   116910   /* The number of tables in the FROM clause is limited by the number of
   116911   ** bits in a Bitmask
   116912   */
   116913   testcase( pTabList->nSrc==BMS );
   116914   if( pTabList->nSrc>BMS ){
   116915     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
   116916     return 0;
   116917   }
   116918 
   116919   /* This function normally generates a nested loop for all tables in
   116920   ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
   116921   ** only generate code for the first table in pTabList and assume that
   116922   ** any cursors associated with subsequent tables are uninitialized.
   116923   */
   116924   nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
   116925 
   116926   /* Allocate and initialize the WhereInfo structure that will become the
   116927   ** return value. A single allocation is used to store the WhereInfo
   116928   ** struct, the contents of WhereInfo.a[], the WhereClause structure
   116929   ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
   116930   ** field (type Bitmask) it must be aligned on an 8-byte boundary on
   116931   ** some architectures. Hence the ROUND8() below.
   116932   */
   116933   nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
   116934   pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
   116935   if( db->mallocFailed ){
   116936     sqlite3DbFree(db, pWInfo);
   116937     pWInfo = 0;
   116938     goto whereBeginError;
   116939   }
   116940   pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
   116941   pWInfo->nLevel = nTabList;
   116942   pWInfo->pParse = pParse;
   116943   pWInfo->pTabList = pTabList;
   116944   pWInfo->pOrderBy = pOrderBy;
   116945   pWInfo->pResultSet = pResultSet;
   116946   pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
   116947   pWInfo->wctrlFlags = wctrlFlags;
   116948   pWInfo->savedNQueryLoop = pParse->nQueryLoop;
   116949   pMaskSet = &pWInfo->sMaskSet;
   116950   sWLB.pWInfo = pWInfo;
   116951   sWLB.pWC = &pWInfo->sWC;
   116952   sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
   116953   assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
   116954   whereLoopInit(sWLB.pNew);
   116955 #ifdef SQLITE_DEBUG
   116956   sWLB.pNew->cId = '*';
   116957 #endif
   116958 
   116959   /* Split the WHERE clause into separate subexpressions where each
   116960   ** subexpression is separated by an AND operator.
   116961   */
   116962   initMaskSet(pMaskSet);
   116963   whereClauseInit(&pWInfo->sWC, pWInfo);
   116964   whereSplit(&pWInfo->sWC, pWhere, TK_AND);
   116965 
   116966   /* Special case: a WHERE clause that is constant.  Evaluate the
   116967   ** expression and either jump over all of the code or fall thru.
   116968   */
   116969   for(ii=0; ii<sWLB.pWC->nTerm; ii++){
   116970     if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){
   116971       sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak,
   116972                          SQLITE_JUMPIFNULL);
   116973       sWLB.pWC->a[ii].wtFlags |= TERM_CODED;
   116974     }
   116975   }
   116976 
   116977   /* Special case: No FROM clause
   116978   */
   116979   if( nTabList==0 ){
   116980     if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
   116981     if( wctrlFlags & WHERE_WANT_DISTINCT ){
   116982       pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
   116983     }
   116984   }
   116985 
   116986   /* Assign a bit from the bitmask to every term in the FROM clause.
   116987   **
   116988   ** When assigning bitmask values to FROM clause cursors, it must be
   116989   ** the case that if X is the bitmask for the N-th FROM clause term then
   116990   ** the bitmask for all FROM clause terms to the left of the N-th term
   116991   ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
   116992   ** its Expr.iRightJoinTable value to find the bitmask of the right table
   116993   ** of the join.  Subtracting one from the right table bitmask gives a
   116994   ** bitmask for all tables to the left of the join.  Knowing the bitmask
   116995   ** for all tables to the left of a left join is important.  Ticket #3015.
   116996   **
   116997   ** Note that bitmasks are created for all pTabList->nSrc tables in
   116998   ** pTabList, not just the first nTabList tables.  nTabList is normally
   116999   ** equal to pTabList->nSrc but might be shortened to 1 if the
   117000   ** WHERE_ONETABLE_ONLY flag is set.
   117001   */
   117002   for(ii=0; ii<pTabList->nSrc; ii++){
   117003     createMask(pMaskSet, pTabList->a[ii].iCursor);
   117004   }
   117005 #ifndef NDEBUG
   117006   {
   117007     Bitmask toTheLeft = 0;
   117008     for(ii=0; ii<pTabList->nSrc; ii++){
   117009       Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
   117010       assert( (m-1)==toTheLeft );
   117011       toTheLeft |= m;
   117012     }
   117013   }
   117014 #endif
   117015 
   117016   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
   117017   ** add new virtual terms onto the end of the WHERE clause.  We do not
   117018   ** want to analyze these virtual terms, so start analyzing at the end
   117019   ** and work forward so that the added virtual terms are never processed.
   117020   */
   117021   exprAnalyzeAll(pTabList, &pWInfo->sWC);
   117022   if( db->mallocFailed ){
   117023     goto whereBeginError;
   117024   }
   117025 
   117026   if( wctrlFlags & WHERE_WANT_DISTINCT ){
   117027     if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
   117028       /* The DISTINCT marking is pointless.  Ignore it. */
   117029       pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
   117030     }else if( pOrderBy==0 ){
   117031       /* Try to ORDER BY the result set to make distinct processing easier */
   117032       pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
   117033       pWInfo->pOrderBy = pResultSet;
   117034     }
   117035   }
   117036 
   117037   /* Construct the WhereLoop objects */
   117038   WHERETRACE(0xffff,("*** Optimizer Start ***\n"));
   117039   /* Display all terms of the WHERE clause */
   117040 #if defined(WHERETRACE_ENABLED) && defined(SQLITE_ENABLE_TREE_EXPLAIN)
   117041   if( sqlite3WhereTrace & 0x100 ){
   117042     int i;
   117043     Vdbe *v = pParse->pVdbe;
   117044     sqlite3ExplainBegin(v);
   117045     for(i=0; i<sWLB.pWC->nTerm; i++){
   117046       sqlite3ExplainPrintf(v, "#%-2d ", i);
   117047       sqlite3ExplainPush(v);
   117048       whereExplainTerm(v, &sWLB.pWC->a[i]);
   117049       sqlite3ExplainPop(v);
   117050       sqlite3ExplainNL(v);
   117051     }
   117052     sqlite3ExplainFinish(v);
   117053     sqlite3DebugPrintf("%s", sqlite3VdbeExplanation(v));
   117054   }
   117055 #endif
   117056   if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
   117057     rc = whereLoopAddAll(&sWLB);
   117058     if( rc ) goto whereBeginError;
   117059 
   117060     /* Display all of the WhereLoop objects if wheretrace is enabled */
   117061 #ifdef WHERETRACE_ENABLED /* !=0 */
   117062     if( sqlite3WhereTrace ){
   117063       WhereLoop *p;
   117064       int i;
   117065       static char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
   117066                                        "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
   117067       for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
   117068         p->cId = zLabel[i%sizeof(zLabel)];
   117069         whereLoopPrint(p, sWLB.pWC);
   117070       }
   117071     }
   117072 #endif
   117073 
   117074     wherePathSolver(pWInfo, 0);
   117075     if( db->mallocFailed ) goto whereBeginError;
   117076     if( pWInfo->pOrderBy ){
   117077        wherePathSolver(pWInfo, pWInfo->nRowOut+1);
   117078        if( db->mallocFailed ) goto whereBeginError;
   117079     }
   117080   }
   117081   if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
   117082      pWInfo->revMask = (Bitmask)(-1);
   117083   }
   117084   if( pParse->nErr || NEVER(db->mallocFailed) ){
   117085     goto whereBeginError;
   117086   }
   117087 #ifdef WHERETRACE_ENABLED /* !=0 */
   117088   if( sqlite3WhereTrace ){
   117089     int ii;
   117090     sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
   117091     if( pWInfo->nOBSat>0 ){
   117092       sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
   117093     }
   117094     switch( pWInfo->eDistinct ){
   117095       case WHERE_DISTINCT_UNIQUE: {
   117096         sqlite3DebugPrintf("  DISTINCT=unique");
   117097         break;
   117098       }
   117099       case WHERE_DISTINCT_ORDERED: {
   117100         sqlite3DebugPrintf("  DISTINCT=ordered");
   117101         break;
   117102       }
   117103       case WHERE_DISTINCT_UNORDERED: {
   117104         sqlite3DebugPrintf("  DISTINCT=unordered");
   117105         break;
   117106       }
   117107     }
   117108     sqlite3DebugPrintf("\n");
   117109     for(ii=0; ii<pWInfo->nLevel; ii++){
   117110       whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
   117111     }
   117112   }
   117113 #endif
   117114   /* Attempt to omit tables from the join that do not effect the result */
   117115   if( pWInfo->nLevel>=2
   117116    && pResultSet!=0
   117117    && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
   117118   ){
   117119     Bitmask tabUsed = exprListTableUsage(pMaskSet, pResultSet);
   117120     if( sWLB.pOrderBy ) tabUsed |= exprListTableUsage(pMaskSet, sWLB.pOrderBy);
   117121     while( pWInfo->nLevel>=2 ){
   117122       WhereTerm *pTerm, *pEnd;
   117123       pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
   117124       if( (pWInfo->pTabList->a[pLoop->iTab].jointype & JT_LEFT)==0 ) break;
   117125       if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
   117126        && (pLoop->wsFlags & WHERE_ONEROW)==0
   117127       ){
   117128         break;
   117129       }
   117130       if( (tabUsed & pLoop->maskSelf)!=0 ) break;
   117131       pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
   117132       for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
   117133         if( (pTerm->prereqAll & pLoop->maskSelf)!=0
   117134          && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
   117135         ){
   117136           break;
   117137         }
   117138       }
   117139       if( pTerm<pEnd ) break;
   117140       WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
   117141       pWInfo->nLevel--;
   117142       nTabList--;
   117143     }
   117144   }
   117145   WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
   117146   pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
   117147 
   117148   /* If the caller is an UPDATE or DELETE statement that is requesting
   117149   ** to use a one-pass algorithm, determine if this is appropriate.
   117150   ** The one-pass algorithm only works if the WHERE clause constrains
   117151   ** the statement to update a single row.
   117152   */
   117153   assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
   117154   if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
   117155    && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){
   117156     pWInfo->okOnePass = 1;
   117157     if( HasRowid(pTabList->a[0].pTab) ){
   117158       pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
   117159     }
   117160   }
   117161 
   117162   /* Open all tables in the pTabList and any indices selected for
   117163   ** searching those tables.
   117164   */
   117165   notReady = ~(Bitmask)0;
   117166   for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
   117167     Table *pTab;     /* Table to open */
   117168     int iDb;         /* Index of database containing table/index */
   117169     struct SrcList_item *pTabItem;
   117170 
   117171     pTabItem = &pTabList->a[pLevel->iFrom];
   117172     pTab = pTabItem->pTab;
   117173     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   117174     pLoop = pLevel->pWLoop;
   117175     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
   117176       /* Do nothing */
   117177     }else
   117178 #ifndef SQLITE_OMIT_VIRTUALTABLE
   117179     if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
   117180       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
   117181       int iCur = pTabItem->iCursor;
   117182       sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
   117183     }else if( IsVirtual(pTab) ){
   117184       /* noop */
   117185     }else
   117186 #endif
   117187     if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
   117188          && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
   117189       int op = OP_OpenRead;
   117190       if( pWInfo->okOnePass ){
   117191         op = OP_OpenWrite;
   117192         pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
   117193       };
   117194       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
   117195       assert( pTabItem->iCursor==pLevel->iTabCur );
   117196       testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 );
   117197       testcase( !pWInfo->okOnePass && pTab->nCol==BMS );
   117198       if( !pWInfo->okOnePass && pTab->nCol<BMS && HasRowid(pTab) ){
   117199         Bitmask b = pTabItem->colUsed;
   117200         int n = 0;
   117201         for(; b; b=b>>1, n++){}
   117202         sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
   117203                             SQLITE_INT_TO_PTR(n), P4_INT32);
   117204         assert( n<=pTab->nCol );
   117205       }
   117206     }else{
   117207       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
   117208     }
   117209     if( pLoop->wsFlags & WHERE_INDEXED ){
   117210       Index *pIx = pLoop->u.btree.pIndex;
   117211       int iIndexCur;
   117212       int op = OP_OpenRead;
   117213       /* iIdxCur is always set if to a positive value if ONEPASS is possible */
   117214       assert( iIdxCur!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
   117215       if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
   117216        && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0
   117217       ){
   117218         /* This is one term of an OR-optimization using the PRIMARY KEY of a
   117219         ** WITHOUT ROWID table.  No need for a separate index */
   117220         iIndexCur = pLevel->iTabCur;
   117221         op = 0;
   117222       }else if( pWInfo->okOnePass ){
   117223         Index *pJ = pTabItem->pTab->pIndex;
   117224         iIndexCur = iIdxCur;
   117225         assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
   117226         while( ALWAYS(pJ) && pJ!=pIx ){
   117227           iIndexCur++;
   117228           pJ = pJ->pNext;
   117229         }
   117230         op = OP_OpenWrite;
   117231         pWInfo->aiCurOnePass[1] = iIndexCur;
   117232       }else if( iIdxCur && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0 ){
   117233         iIndexCur = iIdxCur;
   117234         if( wctrlFlags & WHERE_REOPEN_IDX ) op = OP_ReopenIdx;
   117235       }else{
   117236         iIndexCur = pParse->nTab++;
   117237       }
   117238       pLevel->iIdxCur = iIndexCur;
   117239       assert( pIx->pSchema==pTab->pSchema );
   117240       assert( iIndexCur>=0 );
   117241       if( op ){
   117242         sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
   117243         sqlite3VdbeSetP4KeyInfo(pParse, pIx);
   117244         VdbeComment((v, "%s", pIx->zName));
   117245       }
   117246     }
   117247     if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
   117248     notReady &= ~getMask(&pWInfo->sMaskSet, pTabItem->iCursor);
   117249   }
   117250   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
   117251   if( db->mallocFailed ) goto whereBeginError;
   117252 
   117253   /* Generate the code to do the search.  Each iteration of the for
   117254   ** loop below generates code for a single nested loop of the VM
   117255   ** program.
   117256   */
   117257   notReady = ~(Bitmask)0;
   117258   for(ii=0; ii<nTabList; ii++){
   117259     pLevel = &pWInfo->a[ii];
   117260 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
   117261     if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
   117262       constructAutomaticIndex(pParse, &pWInfo->sWC,
   117263                 &pTabList->a[pLevel->iFrom], notReady, pLevel);
   117264       if( db->mallocFailed ) goto whereBeginError;
   117265     }
   117266 #endif
   117267     explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags);
   117268     pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
   117269     notReady = codeOneLoopStart(pWInfo, ii, notReady);
   117270     pWInfo->iContinue = pLevel->addrCont;
   117271   }
   117272 
   117273   /* Done. */
   117274   VdbeModuleComment((v, "Begin WHERE-core"));
   117275   return pWInfo;
   117276 
   117277   /* Jump here if malloc fails */
   117278 whereBeginError:
   117279   if( pWInfo ){
   117280     pParse->nQueryLoop = pWInfo->savedNQueryLoop;
   117281     whereInfoFree(db, pWInfo);
   117282   }
   117283   return 0;
   117284 }
   117285 
   117286 /*
   117287 ** Generate the end of the WHERE loop.  See comments on
   117288 ** sqlite3WhereBegin() for additional information.
   117289 */
   117290 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
   117291   Parse *pParse = pWInfo->pParse;
   117292   Vdbe *v = pParse->pVdbe;
   117293   int i;
   117294   WhereLevel *pLevel;
   117295   WhereLoop *pLoop;
   117296   SrcList *pTabList = pWInfo->pTabList;
   117297   sqlite3 *db = pParse->db;
   117298 
   117299   /* Generate loop termination code.
   117300   */
   117301   VdbeModuleComment((v, "End WHERE-core"));
   117302   sqlite3ExprCacheClear(pParse);
   117303   for(i=pWInfo->nLevel-1; i>=0; i--){
   117304     int addr;
   117305     pLevel = &pWInfo->a[i];
   117306     pLoop = pLevel->pWLoop;
   117307     sqlite3VdbeResolveLabel(v, pLevel->addrCont);
   117308     if( pLevel->op!=OP_Noop ){
   117309       sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
   117310       sqlite3VdbeChangeP5(v, pLevel->p5);
   117311       VdbeCoverage(v);
   117312       VdbeCoverageIf(v, pLevel->op==OP_Next);
   117313       VdbeCoverageIf(v, pLevel->op==OP_Prev);
   117314       VdbeCoverageIf(v, pLevel->op==OP_VNext);
   117315     }
   117316     if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
   117317       struct InLoop *pIn;
   117318       int j;
   117319       sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
   117320       for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
   117321         sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
   117322         sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
   117323         VdbeCoverage(v);
   117324         VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen);
   117325         VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
   117326         sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
   117327       }
   117328       sqlite3DbFree(db, pLevel->u.in.aInLoop);
   117329     }
   117330     sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
   117331     if( pLevel->addrSkip ){
   117332       sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrSkip);
   117333       VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
   117334       sqlite3VdbeJumpHere(v, pLevel->addrSkip);
   117335       sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
   117336     }
   117337     if( pLevel->iLeftJoin ){
   117338       addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
   117339       assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
   117340            || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
   117341       if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
   117342         sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
   117343       }
   117344       if( pLoop->wsFlags & WHERE_INDEXED ){
   117345         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
   117346       }
   117347       if( pLevel->op==OP_Return ){
   117348         sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
   117349       }else{
   117350         sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
   117351       }
   117352       sqlite3VdbeJumpHere(v, addr);
   117353     }
   117354     VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
   117355                      pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
   117356   }
   117357 
   117358   /* The "break" point is here, just past the end of the outer loop.
   117359   ** Set it.
   117360   */
   117361   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
   117362 
   117363   assert( pWInfo->nLevel<=pTabList->nSrc );
   117364   for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
   117365     int k, last;
   117366     VdbeOp *pOp;
   117367     Index *pIdx = 0;
   117368     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
   117369     Table *pTab = pTabItem->pTab;
   117370     assert( pTab!=0 );
   117371     pLoop = pLevel->pWLoop;
   117372 
   117373     /* For a co-routine, change all OP_Column references to the table of
   117374     ** the co-routine into OP_SCopy of result contained in a register.
   117375     ** OP_Rowid becomes OP_Null.
   117376     */
   117377     if( pTabItem->viaCoroutine && !db->mallocFailed ){
   117378       last = sqlite3VdbeCurrentAddr(v);
   117379       k = pLevel->addrBody;
   117380       pOp = sqlite3VdbeGetOp(v, k);
   117381       for(; k<last; k++, pOp++){
   117382         if( pOp->p1!=pLevel->iTabCur ) continue;
   117383         if( pOp->opcode==OP_Column ){
   117384           pOp->opcode = OP_Copy;
   117385           pOp->p1 = pOp->p2 + pTabItem->regResult;
   117386           pOp->p2 = pOp->p3;
   117387           pOp->p3 = 0;
   117388         }else if( pOp->opcode==OP_Rowid ){
   117389           pOp->opcode = OP_Null;
   117390           pOp->p1 = 0;
   117391           pOp->p3 = 0;
   117392         }
   117393       }
   117394       continue;
   117395     }
   117396 
   117397     /* Close all of the cursors that were opened by sqlite3WhereBegin.
   117398     ** Except, do not close cursors that will be reused by the OR optimization
   117399     ** (WHERE_OMIT_OPEN_CLOSE).  And do not close the OP_OpenWrite cursors
   117400     ** created for the ONEPASS optimization.
   117401     */
   117402     if( (pTab->tabFlags & TF_Ephemeral)==0
   117403      && pTab->pSelect==0
   117404      && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
   117405     ){
   117406       int ws = pLoop->wsFlags;
   117407       if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
   117408         sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
   117409       }
   117410       if( (ws & WHERE_INDEXED)!=0
   117411        && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0
   117412        && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1]
   117413       ){
   117414         sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
   117415       }
   117416     }
   117417 
   117418     /* If this scan uses an index, make VDBE code substitutions to read data
   117419     ** from the index instead of from the table where possible.  In some cases
   117420     ** this optimization prevents the table from ever being read, which can
   117421     ** yield a significant performance boost.
   117422     **
   117423     ** Calls to the code generator in between sqlite3WhereBegin and
   117424     ** sqlite3WhereEnd will have created code that references the table
   117425     ** directly.  This loop scans all that code looking for opcodes
   117426     ** that reference the table and converts them into opcodes that
   117427     ** reference the index.
   117428     */
   117429     if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
   117430       pIdx = pLoop->u.btree.pIndex;
   117431     }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
   117432       pIdx = pLevel->u.pCovidx;
   117433     }
   117434     if( pIdx && !db->mallocFailed ){
   117435       last = sqlite3VdbeCurrentAddr(v);
   117436       k = pLevel->addrBody;
   117437       pOp = sqlite3VdbeGetOp(v, k);
   117438       for(; k<last; k++, pOp++){
   117439         if( pOp->p1!=pLevel->iTabCur ) continue;
   117440         if( pOp->opcode==OP_Column ){
   117441           int x = pOp->p2;
   117442           assert( pIdx->pTable==pTab );
   117443           if( !HasRowid(pTab) ){
   117444             Index *pPk = sqlite3PrimaryKeyIndex(pTab);
   117445             x = pPk->aiColumn[x];
   117446           }
   117447           x = sqlite3ColumnOfIndex(pIdx, x);
   117448           if( x>=0 ){
   117449             pOp->p2 = x;
   117450             pOp->p1 = pLevel->iIdxCur;
   117451           }
   117452           assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 );
   117453         }else if( pOp->opcode==OP_Rowid ){
   117454           pOp->p1 = pLevel->iIdxCur;
   117455           pOp->opcode = OP_IdxRowid;
   117456         }
   117457       }
   117458     }
   117459   }
   117460 
   117461   /* Final cleanup
   117462   */
   117463   pParse->nQueryLoop = pWInfo->savedNQueryLoop;
   117464   whereInfoFree(db, pWInfo);
   117465   return;
   117466 }
   117467 
   117468 /************** End of where.c ***********************************************/
   117469 /************** Begin file parse.c *******************************************/
   117470 /* Driver template for the LEMON parser generator.
   117471 ** The author disclaims copyright to this source code.
   117472 **
   117473 ** This version of "lempar.c" is modified, slightly, for use by SQLite.
   117474 ** The only modifications are the addition of a couple of NEVER()
   117475 ** macros to disable tests that are needed in the case of a general
   117476 ** LALR(1) grammar but which are always false in the
   117477 ** specific grammar used by SQLite.
   117478 */
   117479 /* First off, code is included that follows the "include" declaration
   117480 ** in the input grammar file. */
   117481 /* #include <stdio.h> */
   117482 
   117483 
   117484 /*
   117485 ** Disable all error recovery processing in the parser push-down
   117486 ** automaton.
   117487 */
   117488 #define YYNOERRORRECOVERY 1
   117489 
   117490 /*
   117491 ** Make yytestcase() the same as testcase()
   117492 */
   117493 #define yytestcase(X) testcase(X)
   117494 
   117495 /*
   117496 ** An instance of this structure holds information about the
   117497 ** LIMIT clause of a SELECT statement.
   117498 */
   117499 struct LimitVal {
   117500   Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
   117501   Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
   117502 };
   117503 
   117504 /*
   117505 ** An instance of this structure is used to store the LIKE,
   117506 ** GLOB, NOT LIKE, and NOT GLOB operators.
   117507 */
   117508 struct LikeOp {
   117509   Token eOperator;  /* "like" or "glob" or "regexp" */
   117510   int bNot;         /* True if the NOT keyword is present */
   117511 };
   117512 
   117513 /*
   117514 ** An instance of the following structure describes the event of a
   117515 ** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
   117516 ** TK_DELETE, or TK_INSTEAD.  If the event is of the form
   117517 **
   117518 **      UPDATE ON (a,b,c)
   117519 **
   117520 ** Then the "b" IdList records the list "a,b,c".
   117521 */
   117522 struct TrigEvent { int a; IdList * b; };
   117523 
   117524 /*
   117525 ** An instance of this structure holds the ATTACH key and the key type.
   117526 */
   117527 struct AttachKey { int type;  Token key; };
   117528 
   117529 
   117530   /* This is a utility routine used to set the ExprSpan.zStart and
   117531   ** ExprSpan.zEnd values of pOut so that the span covers the complete
   117532   ** range of text beginning with pStart and going to the end of pEnd.
   117533   */
   117534   static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
   117535     pOut->zStart = pStart->z;
   117536     pOut->zEnd = &pEnd->z[pEnd->n];
   117537   }
   117538 
   117539   /* Construct a new Expr object from a single identifier.  Use the
   117540   ** new Expr to populate pOut.  Set the span of pOut to be the identifier
   117541   ** that created the expression.
   117542   */
   117543   static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
   117544     pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
   117545     pOut->zStart = pValue->z;
   117546     pOut->zEnd = &pValue->z[pValue->n];
   117547   }
   117548 
   117549   /* This routine constructs a binary expression node out of two ExprSpan
   117550   ** objects and uses the result to populate a new ExprSpan object.
   117551   */
   117552   static void spanBinaryExpr(
   117553     ExprSpan *pOut,     /* Write the result here */
   117554     Parse *pParse,      /* The parsing context.  Errors accumulate here */
   117555     int op,             /* The binary operation */
   117556     ExprSpan *pLeft,    /* The left operand */
   117557     ExprSpan *pRight    /* The right operand */
   117558   ){
   117559     pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
   117560     pOut->zStart = pLeft->zStart;
   117561     pOut->zEnd = pRight->zEnd;
   117562   }
   117563 
   117564   /* Construct an expression node for a unary postfix operator
   117565   */
   117566   static void spanUnaryPostfix(
   117567     ExprSpan *pOut,        /* Write the new expression node here */
   117568     Parse *pParse,         /* Parsing context to record errors */
   117569     int op,                /* The operator */
   117570     ExprSpan *pOperand,    /* The operand */
   117571     Token *pPostOp         /* The operand token for setting the span */
   117572   ){
   117573     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
   117574     pOut->zStart = pOperand->zStart;
   117575     pOut->zEnd = &pPostOp->z[pPostOp->n];
   117576   }
   117577 
   117578   /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
   117579   ** unary TK_ISNULL or TK_NOTNULL expression. */
   117580   static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
   117581     sqlite3 *db = pParse->db;
   117582     if( db->mallocFailed==0 && pY->op==TK_NULL ){
   117583       pA->op = (u8)op;
   117584       sqlite3ExprDelete(db, pA->pRight);
   117585       pA->pRight = 0;
   117586     }
   117587   }
   117588 
   117589   /* Construct an expression node for a unary prefix operator
   117590   */
   117591   static void spanUnaryPrefix(
   117592     ExprSpan *pOut,        /* Write the new expression node here */
   117593     Parse *pParse,         /* Parsing context to record errors */
   117594     int op,                /* The operator */
   117595     ExprSpan *pOperand,    /* The operand */
   117596     Token *pPreOp         /* The operand token for setting the span */
   117597   ){
   117598     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
   117599     pOut->zStart = pPreOp->z;
   117600     pOut->zEnd = pOperand->zEnd;
   117601   }
   117602 /* Next is all token values, in a form suitable for use by makeheaders.
   117603 ** This section will be null unless lemon is run with the -m switch.
   117604 */
   117605 /*
   117606 ** These constants (all generated automatically by the parser generator)
   117607 ** specify the various kinds of tokens (terminals) that the parser
   117608 ** understands.
   117609 **
   117610 ** Each symbol here is a terminal symbol in the grammar.
   117611 */
   117612 /* Make sure the INTERFACE macro is defined.
   117613 */
   117614 #ifndef INTERFACE
   117615 # define INTERFACE 1
   117616 #endif
   117617 /* The next thing included is series of defines which control
   117618 ** various aspects of the generated parser.
   117619 **    YYCODETYPE         is the data type used for storing terminal
   117620 **                       and nonterminal numbers.  "unsigned char" is
   117621 **                       used if there are fewer than 250 terminals
   117622 **                       and nonterminals.  "int" is used otherwise.
   117623 **    YYNOCODE           is a number of type YYCODETYPE which corresponds
   117624 **                       to no legal terminal or nonterminal number.  This
   117625 **                       number is used to fill in empty slots of the hash
   117626 **                       table.
   117627 **    YYFALLBACK         If defined, this indicates that one or more tokens
   117628 **                       have fall-back values which should be used if the
   117629 **                       original value of the token will not parse.
   117630 **    YYACTIONTYPE       is the data type used for storing terminal
   117631 **                       and nonterminal numbers.  "unsigned char" is
   117632 **                       used if there are fewer than 250 rules and
   117633 **                       states combined.  "int" is used otherwise.
   117634 **    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given
   117635 **                       directly to the parser from the tokenizer.
   117636 **    YYMINORTYPE        is the data type used for all minor tokens.
   117637 **                       This is typically a union of many types, one of
   117638 **                       which is sqlite3ParserTOKENTYPE.  The entry in the union
   117639 **                       for base tokens is called "yy0".
   117640 **    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
   117641 **                       zero the stack is dynamically sized using realloc()
   117642 **    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
   117643 **    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
   117644 **    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
   117645 **    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
   117646 **    YYNSTATE           the combined number of states.
   117647 **    YYNRULE            the number of rules in the grammar
   117648 **    YYERRORSYMBOL      is the code number of the error symbol.  If not
   117649 **                       defined, then do no error processing.
   117650 */
   117651 #define YYCODETYPE unsigned char
   117652 #define YYNOCODE 254
   117653 #define YYACTIONTYPE unsigned short int
   117654 #define YYWILDCARD 70
   117655 #define sqlite3ParserTOKENTYPE Token
   117656 typedef union {
   117657   int yyinit;
   117658   sqlite3ParserTOKENTYPE yy0;
   117659   Select* yy3;
   117660   ExprList* yy14;
   117661   With* yy59;
   117662   SrcList* yy65;
   117663   struct LikeOp yy96;
   117664   Expr* yy132;
   117665   u8 yy186;
   117666   int yy328;
   117667   ExprSpan yy346;
   117668   struct TrigEvent yy378;
   117669   u16 yy381;
   117670   IdList* yy408;
   117671   struct {int value; int mask;} yy429;
   117672   TriggerStep* yy473;
   117673   struct LimitVal yy476;
   117674 } YYMINORTYPE;
   117675 #ifndef YYSTACKDEPTH
   117676 #define YYSTACKDEPTH 100
   117677 #endif
   117678 #define sqlite3ParserARG_SDECL Parse *pParse;
   117679 #define sqlite3ParserARG_PDECL ,Parse *pParse
   117680 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
   117681 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
   117682 #define YYNSTATE 642
   117683 #define YYNRULE 327
   117684 #define YYFALLBACK 1
   117685 #define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
   117686 #define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
   117687 #define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
   117688 
   117689 /* The yyzerominor constant is used to initialize instances of
   117690 ** YYMINORTYPE objects to zero. */
   117691 static const YYMINORTYPE yyzerominor = { 0 };
   117692 
   117693 /* Define the yytestcase() macro to be a no-op if is not already defined
   117694 ** otherwise.
   117695 **
   117696 ** Applications can choose to define yytestcase() in the %include section
   117697 ** to a macro that can assist in verifying code coverage.  For production
   117698 ** code the yytestcase() macro should be turned off.  But it is useful
   117699 ** for testing.
   117700 */
   117701 #ifndef yytestcase
   117702 # define yytestcase(X)
   117703 #endif
   117704 
   117705 
   117706 /* Next are the tables used to determine what action to take based on the
   117707 ** current state and lookahead token.  These tables are used to implement
   117708 ** functions that take a state number and lookahead value and return an
   117709 ** action integer.
   117710 **
   117711 ** Suppose the action integer is N.  Then the action is determined as
   117712 ** follows
   117713 **
   117714 **   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
   117715 **                                      token onto the stack and goto state N.
   117716 **
   117717 **   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
   117718 **
   117719 **   N == YYNSTATE+YYNRULE              A syntax error has occurred.
   117720 **
   117721 **   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
   117722 **
   117723 **   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
   117724 **                                      slots in the yy_action[] table.
   117725 **
   117726 ** The action table is constructed as a single large table named yy_action[].
   117727 ** Given state S and lookahead X, the action is computed as
   117728 **
   117729 **      yy_action[ yy_shift_ofst[S] + X ]
   117730 **
   117731 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
   117732 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
   117733 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
   117734 ** and that yy_default[S] should be used instead.
   117735 **
   117736 ** The formula above is for computing the action when the lookahead is
   117737 ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
   117738 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
   117739 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
   117740 ** YY_SHIFT_USE_DFLT.
   117741 **
   117742 ** The following are the tables generated in this section:
   117743 **
   117744 **  yy_action[]        A single table containing all actions.
   117745 **  yy_lookahead[]     A table containing the lookahead for each entry in
   117746 **                     yy_action.  Used to detect hash collisions.
   117747 **  yy_shift_ofst[]    For each state, the offset into yy_action for
   117748 **                     shifting terminals.
   117749 **  yy_reduce_ofst[]   For each state, the offset into yy_action for
   117750 **                     shifting non-terminals after a reduce.
   117751 **  yy_default[]       Default action for each state.
   117752 */
   117753 #define YY_ACTTAB_COUNT (1497)
   117754 static const YYACTIONTYPE yy_action[] = {
   117755  /*     0 */   306,  212,  432,  955,  639,  191,  955,  295,  559,   88,
   117756  /*    10 */    88,   88,   88,   81,   86,   86,   86,   86,   85,   85,
   117757  /*    20 */    84,   84,   84,   83,  330,  185,  184,  183,  635,  635,
   117758  /*    30 */   292,  606,  606,   88,   88,   88,   88,  683,   86,   86,
   117759  /*    40 */    86,   86,   85,   85,   84,   84,   84,   83,  330,   16,
   117760  /*    50 */   436,  597,   89,   90,   80,  600,  599,  601,  601,   87,
   117761  /*    60 */    87,   88,   88,   88,   88,  684,   86,   86,   86,   86,
   117762  /*    70 */    85,   85,   84,   84,   84,   83,  330,  306,  559,   84,
   117763  /*    80 */    84,   84,   83,  330,   65,   86,   86,   86,   86,   85,
   117764  /*    90 */    85,   84,   84,   84,   83,  330,  635,  635,  634,  633,
   117765  /*   100 */   182,  682,  550,  379,  376,  375,   17,  322,  606,  606,
   117766  /*   110 */   371,  198,  479,   91,  374,   82,   79,  165,   85,   85,
   117767  /*   120 */    84,   84,   84,   83,  330,  598,  635,  635,  107,   89,
   117768  /*   130 */    90,   80,  600,  599,  601,  601,   87,   87,   88,   88,
   117769  /*   140 */    88,   88,  186,   86,   86,   86,   86,   85,   85,   84,
   117770  /*   150 */    84,   84,   83,  330,  306,  594,  594,  142,  328,  327,
   117771  /*   160 */   484,  249,  344,  238,  635,  635,  634,  633,  585,  448,
   117772  /*   170 */   526,  525,  229,  388,    1,  394,  450,  584,  449,  635,
   117773  /*   180 */   635,  635,  635,  319,  395,  606,  606,  199,  157,  273,
   117774  /*   190 */   382,  268,  381,  187,  635,  635,  634,  633,  311,  555,
   117775  /*   200 */   266,  593,  593,  266,  347,  588,   89,   90,   80,  600,
   117776  /*   210 */   599,  601,  601,   87,   87,   88,   88,   88,   88,  478,
   117777  /*   220 */    86,   86,   86,   86,   85,   85,   84,   84,   84,   83,
   117778  /*   230 */   330,  306,  272,  536,  634,  633,  146,  610,  197,  310,
   117779  /*   240 */   575,  182,  482,  271,  379,  376,  375,  506,   21,  634,
   117780  /*   250 */   633,  634,  633,  635,  635,  374,  611,  574,  548,  440,
   117781  /*   260 */   111,  563,  606,  606,  634,  633,  324,  479,  608,  608,
   117782  /*   270 */   608,  300,  435,  573,  119,  407,  210,  162,  562,  883,
   117783  /*   280 */   592,  592,  306,   89,   90,   80,  600,  599,  601,  601,
   117784  /*   290 */    87,   87,   88,   88,   88,   88,  506,   86,   86,   86,
   117785  /*   300 */    86,   85,   85,   84,   84,   84,   83,  330,  620,  111,
   117786  /*   310 */   635,  635,  361,  606,  606,  358,  249,  349,  248,  433,
   117787  /*   320 */   243,  479,  586,  634,  633,  195,  611,   93,  119,  221,
   117788  /*   330 */   575,  497,  534,  534,   89,   90,   80,  600,  599,  601,
   117789  /*   340 */   601,   87,   87,   88,   88,   88,   88,  574,   86,   86,
   117790  /*   350 */    86,   86,   85,   85,   84,   84,   84,   83,  330,  306,
   117791  /*   360 */    77,  429,  638,  573,  589,  530,  240,  230,  242,  105,
   117792  /*   370 */   249,  349,  248,  515,  588,  208,  460,  529,  564,  173,
   117793  /*   380 */   634,  633,  970,  144,  430,    2,  424,  228,  380,  557,
   117794  /*   390 */   606,  606,  190,  153,  159,  158,  514,   51,  632,  631,
   117795  /*   400 */   630,   71,  536,  432,  954,  196,  610,  954,  614,   45,
   117796  /*   410 */    18,   89,   90,   80,  600,  599,  601,  601,   87,   87,
   117797  /*   420 */    88,   88,   88,   88,  261,   86,   86,   86,   86,   85,
   117798  /*   430 */    85,   84,   84,   84,   83,  330,  306,  608,  608,  608,
   117799  /*   440 */   542,  424,  402,  385,  241,  506,  451,  320,  211,  543,
   117800  /*   450 */   164,  436,  386,  293,  451,  587,  108,  496,  111,  334,
   117801  /*   460 */   391,  591,  424,  614,   27,  452,  453,  606,  606,   72,
   117802  /*   470 */   257,   70,  259,  452,  339,  342,  564,  582,   68,  415,
   117803  /*   480 */   469,  328,  327,   62,  614,   45,  110,  393,   89,   90,
   117804  /*   490 */    80,  600,  599,  601,  601,   87,   87,   88,   88,   88,
   117805  /*   500 */    88,  152,   86,   86,   86,   86,   85,   85,   84,   84,
   117806  /*   510 */    84,   83,  330,  306,  110,  499,  520,  538,  402,  389,
   117807  /*   520 */   424,  110,  566,  500,  593,  593,  454,   82,   79,  165,
   117808  /*   530 */   424,  591,  384,  564,  340,  615,  188,  162,  424,  350,
   117809  /*   540 */   616,  424,  614,   44,  606,  606,  445,  582,  300,  434,
   117810  /*   550 */   151,   19,  614,    9,  568,  580,  348,  615,  469,  567,
   117811  /*   560 */   614,   26,  616,  614,   45,   89,   90,   80,  600,  599,
   117812  /*   570 */   601,  601,   87,   87,   88,   88,   88,   88,  411,   86,
   117813  /*   580 */    86,   86,   86,   85,   85,   84,   84,   84,   83,  330,
   117814  /*   590 */   306,  579,  110,  578,  521,  282,  433,  398,  400,  255,
   117815  /*   600 */   486,   82,   79,  165,  487,  164,   82,   79,  165,  488,
   117816  /*   610 */   488,  364,  387,  424,  544,  544,  509,  350,  362,  155,
   117817  /*   620 */   191,  606,  606,  559,  642,  640,  333,   82,   79,  165,
   117818  /*   630 */   305,  564,  507,  312,  357,  614,   45,  329,  596,  595,
   117819  /*   640 */   194,  337,   89,   90,   80,  600,  599,  601,  601,   87,
   117820  /*   650 */    87,   88,   88,   88,   88,  424,   86,   86,   86,   86,
   117821  /*   660 */    85,   85,   84,   84,   84,   83,  330,  306,   20,  323,
   117822  /*   670 */   150,  263,  211,  543,  421,  596,  595,  614,   22,  424,
   117823  /*   680 */   193,  424,  284,  424,  391,  424,  509,  424,  577,  424,
   117824  /*   690 */   186,  335,  424,  559,  424,  313,  120,  546,  606,  606,
   117825  /*   700 */    67,  614,   47,  614,   50,  614,   48,  614,  100,  614,
   117826  /*   710 */    99,  614,  101,  576,  614,  102,  614,  109,  326,   89,
   117827  /*   720 */    90,   80,  600,  599,  601,  601,   87,   87,   88,   88,
   117828  /*   730 */    88,   88,  424,   86,   86,   86,   86,   85,   85,   84,
   117829  /*   740 */    84,   84,   83,  330,  306,  424,  311,  424,  585,   54,
   117830  /*   750 */   424,  516,  517,  590,  614,  112,  424,  584,  424,  572,
   117831  /*   760 */   424,  195,  424,  571,  424,   67,  424,  614,   94,  614,
   117832  /*   770 */    98,  424,  614,   97,  264,  606,  606,  195,  614,   46,
   117833  /*   780 */   614,   96,  614,   30,  614,   49,  614,  115,  614,  114,
   117834  /*   790 */   418,  229,  388,  614,  113,  306,   89,   90,   80,  600,
   117835  /*   800 */   599,  601,  601,   87,   87,   88,   88,   88,   88,  424,
   117836  /*   810 */    86,   86,   86,   86,   85,   85,   84,   84,   84,   83,
   117837  /*   820 */   330,  119,  424,  590,  110,  372,  606,  606,  195,   53,
   117838  /*   830 */   250,  614,   29,  195,  472,  438,  729,  190,  302,  498,
   117839  /*   840 */    14,  523,  641,    2,  614,   43,  306,   89,   90,   80,
   117840  /*   850 */   600,  599,  601,  601,   87,   87,   88,   88,   88,   88,
   117841  /*   860 */   424,   86,   86,   86,   86,   85,   85,   84,   84,   84,
   117842  /*   870 */    83,  330,  424,  613,  964,  964,  354,  606,  606,  420,
   117843  /*   880 */   312,   64,  614,   42,  391,  355,  283,  437,  301,  255,
   117844  /*   890 */   414,  410,  495,  492,  614,   28,  471,  306,   89,   90,
   117845  /*   900 */    80,  600,  599,  601,  601,   87,   87,   88,   88,   88,
   117846  /*   910 */    88,  424,   86,   86,   86,   86,   85,   85,   84,   84,
   117847  /*   920 */    84,   83,  330,  424,  110,  110,  110,  110,  606,  606,
   117848  /*   930 */   110,  254,   13,  614,   41,  532,  531,  283,  481,  531,
   117849  /*   940 */   457,  284,  119,  561,  356,  614,   40,  284,  306,   89,
   117850  /*   950 */    78,   80,  600,  599,  601,  601,   87,   87,   88,   88,
   117851  /*   960 */    88,   88,  424,   86,   86,   86,   86,   85,   85,   84,
   117852  /*   970 */    84,   84,   83,  330,  110,  424,  341,  220,  555,  606,
   117853  /*   980 */   606,  351,  555,  318,  614,   95,  413,  255,   83,  330,
   117854  /*   990 */   284,  284,  255,  640,  333,  356,  255,  614,   39,  306,
   117855  /*  1000 */   356,   90,   80,  600,  599,  601,  601,   87,   87,   88,
   117856  /*  1010 */    88,   88,   88,  424,   86,   86,   86,   86,   85,   85,
   117857  /*  1020 */    84,   84,   84,   83,  330,  424,  317,  316,  141,  465,
   117858  /*  1030 */   606,  606,  219,  619,  463,  614,   10,  417,  462,  255,
   117859  /*  1040 */   189,  510,  553,  351,  207,  363,  161,  614,   38,  315,
   117860  /*  1050 */   218,  255,  255,   80,  600,  599,  601,  601,   87,   87,
   117861  /*  1060 */    88,   88,   88,   88,  424,   86,   86,   86,   86,   85,
   117862  /*  1070 */    85,   84,   84,   84,   83,  330,   76,  419,  255,    3,
   117863  /*  1080 */   878,  461,  424,  247,  331,  331,  614,   37,  217,   76,
   117864  /*  1090 */   419,  390,    3,  216,  215,  422,    4,  331,  331,  424,
   117865  /*  1100 */   547,   12,  424,  545,  614,   36,  424,  541,  422,  424,
   117866  /*  1110 */   540,  424,  214,  424,  408,  424,  539,  403,  605,  605,
   117867  /*  1120 */   237,  614,   25,  119,  614,   24,  588,  408,  614,   45,
   117868  /*  1130 */   118,  614,   35,  614,   34,  614,   33,  614,   23,  588,
   117869  /*  1140 */    60,  223,  603,  602,  513,  378,   73,   74,  140,  139,
   117870  /*  1150 */   424,  110,  265,   75,  426,  425,   59,  424,  610,   73,
   117871  /*  1160 */    74,  549,  402,  404,  424,  373,   75,  426,  425,  604,
   117872  /*  1170 */   138,  610,  614,   11,  392,   76,  419,  181,    3,  614,
   117873  /*  1180 */    32,  271,  369,  331,  331,  493,  614,   31,  149,  608,
   117874  /*  1190 */   608,  608,  607,   15,  422,  365,  614,    8,  137,  489,
   117875  /*  1200 */   136,  190,  608,  608,  608,  607,   15,  485,  176,  135,
   117876  /*  1210 */     7,  252,  477,  408,  174,  133,  175,  474,   57,   56,
   117877  /*  1220 */   132,  130,  119,   76,  419,  588,    3,  468,  245,  464,
   117878  /*  1230 */   171,  331,  331,  125,  123,  456,  447,  122,  446,  104,
   117879  /*  1240 */   336,  231,  422,  166,  154,   73,   74,  332,  116,  431,
   117880  /*  1250 */   121,  309,   75,  426,  425,  222,  106,  610,  308,  637,
   117881  /*  1260 */   204,  408,  629,  627,  628,    6,  200,  428,  427,  290,
   117882  /*  1270 */   203,  622,  201,  588,   62,   63,  289,   66,  419,  399,
   117883  /*  1280 */     3,  401,  288,   92,  143,  331,  331,  287,  608,  608,
   117884  /*  1290 */   608,  607,   15,   73,   74,  227,  422,  325,   69,  416,
   117885  /*  1300 */    75,  426,  425,  612,  412,  610,  192,   61,  569,  209,
   117886  /*  1310 */   396,  226,  278,  225,  383,  408,  527,  558,  276,  533,
   117887  /*  1320 */   552,  528,  321,  523,  370,  508,  180,  588,  494,  179,
   117888  /*  1330 */   366,  117,  253,  269,  522,  503,  608,  608,  608,  607,
   117889  /*  1340 */    15,  551,  502,   58,  274,  524,  178,   73,   74,  304,
   117890  /*  1350 */   501,  368,  303,  206,   75,  426,  425,  491,  360,  610,
   117891  /*  1360 */   213,  177,  483,  131,  345,  298,  297,  296,  202,  294,
   117892  /*  1370 */   480,  490,  466,  134,  172,  129,  444,  346,  470,  128,
   117893  /*  1380 */   314,  459,  103,  127,  126,  148,  124,  167,  443,  235,
   117894  /*  1390 */   608,  608,  608,  607,   15,  442,  439,  623,  234,  299,
   117895  /*  1400 */   145,  583,  291,  377,  581,  160,  119,  156,  270,  636,
   117896  /*  1410 */   971,  169,  279,  626,  520,  625,  473,  624,  170,  621,
   117897  /*  1420 */   618,  119,  168,   55,  409,  423,  537,  609,  286,  285,
   117898  /*  1430 */   405,  570,  560,  556,    5,   52,  458,  554,  147,  267,
   117899  /*  1440 */   519,  504,  518,  406,  262,  239,  260,  512,  343,  511,
   117900  /*  1450 */   258,  353,  565,  256,  224,  251,  359,  277,  275,  476,
   117901  /*  1460 */   475,  246,  352,  244,  467,  455,  236,  233,  232,  307,
   117902  /*  1470 */   441,  281,  205,  163,  397,  280,  535,  505,  330,  617,
   117903  /*  1480 */   971,  971,  971,  971,  367,  971,  971,  971,  971,  971,
   117904  /*  1490 */   971,  971,  971,  971,  971,  971,  338,
   117905 };
   117906 static const YYCODETYPE yy_lookahead[] = {
   117907  /*     0 */    19,   22,   22,   23,    1,   24,   26,   15,   27,   80,
   117908  /*    10 */    81,   82,   83,   84,   85,   86,   87,   88,   89,   90,
   117909  /*    20 */    91,   92,   93,   94,   95,  108,  109,  110,   27,   28,
   117910  /*    30 */    23,   50,   51,   80,   81,   82,   83,  122,   85,   86,
   117911  /*    40 */    87,   88,   89,   90,   91,   92,   93,   94,   95,   22,
   117912  /*    50 */    70,   23,   71,   72,   73,   74,   75,   76,   77,   78,
   117913  /*    60 */    79,   80,   81,   82,   83,  122,   85,   86,   87,   88,
   117914  /*    70 */    89,   90,   91,   92,   93,   94,   95,   19,   97,   91,
   117915  /*    80 */    92,   93,   94,   95,   26,   85,   86,   87,   88,   89,
   117916  /*    90 */    90,   91,   92,   93,   94,   95,   27,   28,   97,   98,
   117917  /*   100 */    99,  122,  211,  102,  103,  104,   79,   19,   50,   51,
   117918  /*   110 */    19,  122,   59,   55,  113,  224,  225,  226,   89,   90,
   117919  /*   120 */    91,   92,   93,   94,   95,   23,   27,   28,   26,   71,
   117920  /*   130 */    72,   73,   74,   75,   76,   77,   78,   79,   80,   81,
   117921  /*   140 */    82,   83,   51,   85,   86,   87,   88,   89,   90,   91,
   117922  /*   150 */    92,   93,   94,   95,   19,  132,  133,   58,   89,   90,
   117923  /*   160 */    21,  108,  109,  110,   27,   28,   97,   98,   33,  100,
   117924  /*   170 */     7,    8,  119,  120,   22,   19,  107,   42,  109,   27,
   117925  /*   180 */    28,   27,   28,   95,   28,   50,   51,   99,  100,  101,
   117926  /*   190 */   102,  103,  104,  105,   27,   28,   97,   98,  107,  152,
   117927  /*   200 */   112,  132,  133,  112,   65,   69,   71,   72,   73,   74,
   117928  /*   210 */    75,   76,   77,   78,   79,   80,   81,   82,   83,   11,
   117929  /*   220 */    85,   86,   87,   88,   89,   90,   91,   92,   93,   94,
   117930  /*   230 */    95,   19,  101,   97,   97,   98,   24,  101,  122,  157,
   117931  /*   240 */    12,   99,  103,  112,  102,  103,  104,  152,   22,   97,
   117932  /*   250 */    98,   97,   98,   27,   28,  113,   27,   29,   91,  164,
   117933  /*   260 */   165,  124,   50,   51,   97,   98,  219,   59,  132,  133,
   117934  /*   270 */   134,   22,   23,   45,   66,   47,  212,  213,  124,  140,
   117935  /*   280 */   132,  133,   19,   71,   72,   73,   74,   75,   76,   77,
   117936  /*   290 */    78,   79,   80,   81,   82,   83,  152,   85,   86,   87,
   117937  /*   300 */    88,   89,   90,   91,   92,   93,   94,   95,  164,  165,
   117938  /*   310 */    27,   28,  230,   50,   51,  233,  108,  109,  110,   70,
   117939  /*   320 */    16,   59,   23,   97,   98,   26,   97,   22,   66,  185,
   117940  /*   330 */    12,  187,   27,   28,   71,   72,   73,   74,   75,   76,
   117941  /*   340 */    77,   78,   79,   80,   81,   82,   83,   29,   85,   86,
   117942  /*   350 */    87,   88,   89,   90,   91,   92,   93,   94,   95,   19,
   117943  /*   360 */    22,  148,  149,   45,   23,   47,   62,  154,   64,  156,
   117944  /*   370 */   108,  109,  110,   37,   69,   23,  163,   59,   26,   26,
   117945  /*   380 */    97,   98,  144,  145,  146,  147,  152,  200,   52,   23,
   117946  /*   390 */    50,   51,   26,   22,   89,   90,   60,  210,    7,    8,
   117947  /*   400 */     9,  138,   97,   22,   23,   26,  101,   26,  174,  175,
   117948  /*   410 */   197,   71,   72,   73,   74,   75,   76,   77,   78,   79,
   117949  /*   420 */    80,   81,   82,   83,   16,   85,   86,   87,   88,   89,
   117950  /*   430 */    90,   91,   92,   93,   94,   95,   19,  132,  133,  134,
   117951  /*   440 */    23,  152,  208,  209,  140,  152,  152,  111,  195,  196,
   117952  /*   450 */    98,   70,  163,  160,  152,   23,   22,  164,  165,  246,
   117953  /*   460 */   207,   27,  152,  174,  175,  171,  172,   50,   51,  137,
   117954  /*   470 */    62,  139,   64,  171,  172,  222,  124,   27,  138,   24,
   117955  /*   480 */   163,   89,   90,  130,  174,  175,  197,  163,   71,   72,
   117956  /*   490 */    73,   74,   75,   76,   77,   78,   79,   80,   81,   82,
   117957  /*   500 */    83,   22,   85,   86,   87,   88,   89,   90,   91,   92,
   117958  /*   510 */    93,   94,   95,   19,  197,  181,  182,   23,  208,  209,
   117959  /*   520 */   152,  197,   26,  189,  132,  133,  232,  224,  225,  226,
   117960  /*   530 */   152,   97,   91,   26,  232,  116,  212,  213,  152,  222,
   117961  /*   540 */   121,  152,  174,  175,   50,   51,  243,   97,   22,   23,
   117962  /*   550 */    22,  234,  174,  175,  177,   23,  239,  116,  163,  177,
   117963  /*   560 */   174,  175,  121,  174,  175,   71,   72,   73,   74,   75,
   117964  /*   570 */    76,   77,   78,   79,   80,   81,   82,   83,   24,   85,
   117965  /*   580 */    86,   87,   88,   89,   90,   91,   92,   93,   94,   95,
   117966  /*   590 */    19,   23,  197,   11,   23,  227,   70,  208,  220,  152,
   117967  /*   600 */    31,  224,  225,  226,   35,   98,  224,  225,  226,  108,
   117968  /*   610 */   109,  110,  115,  152,  117,  118,   27,  222,   49,  123,
   117969  /*   620 */    24,   50,   51,   27,    0,    1,    2,  224,  225,  226,
   117970  /*   630 */   166,  124,  168,  169,  239,  174,  175,  170,  171,  172,
   117971  /*   640 */    22,  194,   71,   72,   73,   74,   75,   76,   77,   78,
   117972  /*   650 */    79,   80,   81,   82,   83,  152,   85,   86,   87,   88,
   117973  /*   660 */    89,   90,   91,   92,   93,   94,   95,   19,   22,  208,
   117974  /*   670 */    24,   23,  195,  196,  170,  171,  172,  174,  175,  152,
   117975  /*   680 */    26,  152,  152,  152,  207,  152,   97,  152,   23,  152,
   117976  /*   690 */    51,  244,  152,   97,  152,  247,  248,   23,   50,   51,
   117977  /*   700 */    26,  174,  175,  174,  175,  174,  175,  174,  175,  174,
   117978  /*   710 */   175,  174,  175,   23,  174,  175,  174,  175,  188,   71,
   117979  /*   720 */    72,   73,   74,   75,   76,   77,   78,   79,   80,   81,
   117980  /*   730 */    82,   83,  152,   85,   86,   87,   88,   89,   90,   91,
   117981  /*   740 */    92,   93,   94,   95,   19,  152,  107,  152,   33,   24,
   117982  /*   750 */   152,  100,  101,   27,  174,  175,  152,   42,  152,   23,
   117983  /*   760 */   152,   26,  152,   23,  152,   26,  152,  174,  175,  174,
   117984  /*   770 */   175,  152,  174,  175,   23,   50,   51,   26,  174,  175,
   117985  /*   780 */   174,  175,  174,  175,  174,  175,  174,  175,  174,  175,
   117986  /*   790 */   163,  119,  120,  174,  175,   19,   71,   72,   73,   74,
   117987  /*   800 */    75,   76,   77,   78,   79,   80,   81,   82,   83,  152,
   117988  /*   810 */    85,   86,   87,   88,   89,   90,   91,   92,   93,   94,
   117989  /*   820 */    95,   66,  152,   97,  197,   23,   50,   51,   26,   53,
   117990  /*   830 */    23,  174,  175,   26,   23,   23,   23,   26,   26,   26,
   117991  /*   840 */    36,  106,  146,  147,  174,  175,   19,   71,   72,   73,
   117992  /*   850 */    74,   75,   76,   77,   78,   79,   80,   81,   82,   83,
   117993  /*   860 */   152,   85,   86,   87,   88,   89,   90,   91,   92,   93,
   117994  /*   870 */    94,   95,  152,  196,  119,  120,   19,   50,   51,  168,
   117995  /*   880 */   169,   26,  174,  175,  207,   28,  152,  249,  250,  152,
   117996  /*   890 */   163,  163,  163,  163,  174,  175,  163,   19,   71,   72,
   117997  /*   900 */    73,   74,   75,   76,   77,   78,   79,   80,   81,   82,
   117998  /*   910 */    83,  152,   85,   86,   87,   88,   89,   90,   91,   92,
   117999  /*   920 */    93,   94,   95,  152,  197,  197,  197,  197,   50,   51,
   118000  /*   930 */   197,  194,   36,  174,  175,  191,  192,  152,  191,  192,
   118001  /*   940 */   163,  152,   66,  124,  152,  174,  175,  152,   19,   71,
   118002  /*   950 */    72,   73,   74,   75,   76,   77,   78,   79,   80,   81,
   118003  /*   960 */    82,   83,  152,   85,   86,   87,   88,   89,   90,   91,
   118004  /*   970 */    92,   93,   94,   95,  197,  152,  100,  188,  152,   50,
   118005  /*   980 */    51,  152,  152,  188,  174,  175,  252,  152,   94,   95,
   118006  /*   990 */   152,  152,  152,    1,    2,  152,  152,  174,  175,   19,
   118007  /*  1000 */   152,   72,   73,   74,   75,   76,   77,   78,   79,   80,
   118008  /*  1010 */    81,   82,   83,  152,   85,   86,   87,   88,   89,   90,
   118009  /*  1020 */    91,   92,   93,   94,   95,  152,  188,  188,   22,  194,
   118010  /*  1030 */    50,   51,  240,  173,  194,  174,  175,  252,  194,  152,
   118011  /*  1040 */    36,  181,   28,  152,   23,  219,  122,  174,  175,  219,
   118012  /*  1050 */   221,  152,  152,   73,   74,   75,   76,   77,   78,   79,
   118013  /*  1060 */    80,   81,   82,   83,  152,   85,   86,   87,   88,   89,
   118014  /*  1070 */    90,   91,   92,   93,   94,   95,   19,   20,  152,   22,
   118015  /*  1080 */    23,  194,  152,  240,   27,   28,  174,  175,  240,   19,
   118016  /*  1090 */    20,   26,   22,  194,  194,   38,   22,   27,   28,  152,
   118017  /*  1100 */    23,   22,  152,  116,  174,  175,  152,   23,   38,  152,
   118018  /*  1110 */    23,  152,  221,  152,   57,  152,   23,  163,   50,   51,
   118019  /*  1120 */   194,  174,  175,   66,  174,  175,   69,   57,  174,  175,
   118020  /*  1130 */    40,  174,  175,  174,  175,  174,  175,  174,  175,   69,
   118021  /*  1140 */    22,   53,   74,   75,   30,   53,   89,   90,   22,   22,
   118022  /*  1150 */   152,  197,   23,   96,   97,   98,   22,  152,  101,   89,
   118023  /*  1160 */    90,   91,  208,  209,  152,   53,   96,   97,   98,  101,
   118024  /*  1170 */    22,  101,  174,  175,  152,   19,   20,  105,   22,  174,
   118025  /*  1180 */   175,  112,   19,   27,   28,   20,  174,  175,   24,  132,
   118026  /*  1190 */   133,  134,  135,  136,   38,   44,  174,  175,  107,   61,
   118027  /*  1200 */    54,   26,  132,  133,  134,  135,  136,   54,  107,   22,
   118028  /*  1210 */     5,  140,    1,   57,   36,  111,  122,   28,   79,   79,
   118029  /*  1220 */   131,  123,   66,   19,   20,   69,   22,    1,   16,   20,
   118030  /*  1230 */   125,   27,   28,  123,  111,  120,   23,  131,   23,   16,
   118031  /*  1240 */    68,  142,   38,   15,   22,   89,   90,    3,  167,    4,
   118032  /*  1250 */   248,  251,   96,   97,   98,  180,  180,  101,  251,  151,
   118033  /*  1260 */     6,   57,  151,   13,  151,   26,   25,  151,  161,  202,
   118034  /*  1270 */   153,  162,  153,   69,  130,  128,  203,   19,   20,  127,
   118035  /*  1280 */    22,  126,  204,  129,   22,   27,   28,  205,  132,  133,
   118036  /*  1290 */   134,  135,  136,   89,   90,  231,   38,   95,  137,  179,
   118037  /*  1300 */    96,   97,   98,  206,  179,  101,  122,  107,  159,  159,
   118038  /*  1310 */   125,  231,  216,  228,  107,   57,  184,  217,  216,  176,
   118039  /*  1320 */   217,  176,   48,  106,   18,  184,  158,   69,  159,  158,
   118040  /*  1330 */    46,   71,  237,  176,  176,  176,  132,  133,  134,  135,
   118041  /*  1340 */   136,  217,  176,  137,  216,  178,  158,   89,   90,  179,
   118042  /*  1350 */   176,  159,  179,  159,   96,   97,   98,  159,  159,  101,
   118043  /*  1360 */     5,  158,  202,   22,   18,   10,   11,   12,   13,   14,
   118044  /*  1370 */   190,  238,   17,  190,  158,  193,   41,  159,  202,  193,
   118045  /*  1380 */   159,  202,  245,  193,  193,  223,  190,   32,  159,   34,
   118046  /*  1390 */   132,  133,  134,  135,  136,  159,   39,  155,   43,  150,
   118047  /*  1400 */   223,  177,  201,  178,  177,  186,   66,  199,  177,  152,
   118048  /*  1410 */   253,   56,  215,  152,  182,  152,  202,  152,   63,  152,
   118049  /*  1420 */   152,   66,   67,  242,  229,  152,  174,  152,  152,  152,
   118050  /*  1430 */   152,  152,  152,  152,  199,  242,  202,  152,  198,  152,
   118051  /*  1440 */   152,  152,  183,  192,  152,  215,  152,  183,  215,  183,
   118052  /*  1450 */   152,  241,  214,  152,  211,  152,  152,  211,  211,  152,
   118053  /*  1460 */   152,  241,  152,  152,  152,  152,  152,  152,  152,  114,
   118054  /*  1470 */   152,  152,  235,  152,  152,  152,  174,  187,   95,  174,
   118055  /*  1480 */   253,  253,  253,  253,  236,  253,  253,  253,  253,  253,
   118056  /*  1490 */   253,  253,  253,  253,  253,  253,  141,
   118057 };
   118058 #define YY_SHIFT_USE_DFLT (-86)
   118059 #define YY_SHIFT_COUNT (429)
   118060 #define YY_SHIFT_MIN   (-85)
   118061 #define YY_SHIFT_MAX   (1383)
   118062 static const short yy_shift_ofst[] = {
   118063  /*     0 */   992, 1057, 1355, 1156, 1204, 1204,    1,  262,  -19,  135,
   118064  /*    10 */   135,  776, 1204, 1204, 1204, 1204,   69,   69,   53,  208,
   118065  /*    20 */   283,  755,   58,  725,  648,  571,  494,  417,  340,  263,
   118066  /*    30 */   212,  827,  827,  827,  827,  827,  827,  827,  827,  827,
   118067  /*    40 */   827,  827,  827,  827,  827,  827,  878,  827,  929,  980,
   118068  /*    50 */   980, 1070, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
   118069  /*    60 */  1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
   118070  /*    70 */  1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
   118071  /*    80 */  1258, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
   118072  /*    90 */  1204, 1204, 1204, 1204,  -71,  -47,  -47,  -47,  -47,  -47,
   118073  /*   100 */     0,   29,  -12,  283,  283,  139,   91,  392,  392,  894,
   118074  /*   110 */   672,  726, 1383,  -86,  -86,  -86,   88,  318,  318,   99,
   118075  /*   120 */   381,  -20,  283,  283,  283,  283,  283,  283,  283,  283,
   118076  /*   130 */   283,  283,  283,  283,  283,  283,  283,  283,  283,  283,
   118077  /*   140 */   283,  283,  283,  283,  624,  876,  726,  672, 1340, 1340,
   118078  /*   150 */  1340, 1340, 1340, 1340,  -86,  -86,  -86,  305,  136,  136,
   118079  /*   160 */   142,  167,  226,  154,  137,  152,  283,  283,  283,  283,
   118080  /*   170 */   283,  283,  283,  283,  283,  283,  283,  283,  283,  283,
   118081  /*   180 */   283,  283,  283,  336,  336,  336,  283,  283,  352,  283,
   118082  /*   190 */   283,  283,  283,  283,  228,  283,  283,  283,  283,  283,
   118083  /*   200 */   283,  283,  283,  283,  283,  501,  569,  596,  596,  596,
   118084  /*   210 */   507,  497,  441,  391,  353,  156,  156,  857,  353,  857,
   118085  /*   220 */   735,  813,  639,  715,  156,  332,  715,  715,  496,  419,
   118086  /*   230 */   646, 1357, 1184, 1184, 1335, 1335, 1184, 1341, 1260, 1144,
   118087  /*   240 */  1346, 1346, 1346, 1346, 1184, 1306, 1144, 1341, 1260, 1260,
   118088  /*   250 */  1144, 1184, 1306, 1206, 1284, 1184, 1184, 1306, 1184, 1306,
   118089  /*   260 */  1184, 1306, 1262, 1207, 1207, 1207, 1274, 1262, 1207, 1217,
   118090  /*   270 */  1207, 1274, 1207, 1207, 1185, 1200, 1185, 1200, 1185, 1200,
   118091  /*   280 */  1184, 1184, 1161, 1262, 1202, 1202, 1262, 1154, 1155, 1147,
   118092  /*   290 */  1152, 1144, 1241, 1239, 1250, 1250, 1254, 1254, 1254, 1254,
   118093  /*   300 */   -86,  -86,  -86,  -86,  -86,  -86, 1068,  304,  526,  249,
   118094  /*   310 */   408,  -83,  434,  812,   27,  811,  807,  802,  751,  589,
   118095  /*   320 */   651,  163,  131,  674,  366,  450,  299,  148,   23,  102,
   118096  /*   330 */   229,  -21, 1245, 1244, 1222, 1099, 1228, 1172, 1223, 1215,
   118097  /*   340 */  1213, 1115, 1106, 1123, 1110, 1209, 1105, 1212, 1226, 1098,
   118098  /*   350 */  1089, 1140, 1139, 1104, 1189, 1178, 1094, 1211, 1205, 1187,
   118099  /*   360 */  1101, 1071, 1153, 1175, 1146, 1138, 1151, 1091, 1164, 1165,
   118100  /*   370 */  1163, 1069, 1072, 1148, 1112, 1134, 1127, 1129, 1126, 1092,
   118101  /*   380 */  1114, 1118, 1088, 1090, 1093, 1087, 1084,  987, 1079, 1077,
   118102  /*   390 */  1074, 1065,  924, 1021, 1014, 1004, 1006,  819,  739,  896,
   118103  /*   400 */   855,  804,  739,  740,  736,  690,  654,  665,  618,  582,
   118104  /*   410 */   568,  528,  554,  379,  532,  479,  455,  379,  432,  371,
   118105  /*   420 */   341,   28,  338,  116,  -11,  -57,  -85,    7,   -8,    3,
   118106 };
   118107 #define YY_REDUCE_USE_DFLT (-110)
   118108 #define YY_REDUCE_COUNT (305)
   118109 #define YY_REDUCE_MIN   (-109)
   118110 #define YY_REDUCE_MAX   (1323)
   118111 static const short yy_reduce_ofst[] = {
   118112  /*     0 */   238,  954,  213,  289,  310,  234,  144,  317, -109,  382,
   118113  /*    10 */   377,  303,  461,  389,  378,  368,  302,  294,  253,  395,
   118114  /*    20 */   293,  324,  403,  403,  403,  403,  403,  403,  403,  403,
   118115  /*    30 */   403,  403,  403,  403,  403,  403,  403,  403,  403,  403,
   118116  /*    40 */   403,  403,  403,  403,  403,  403,  403,  403,  403,  403,
   118117  /*    50 */   403, 1022, 1012, 1005,  998,  963,  961,  959,  957,  950,
   118118  /*    60 */   947,  930,  912,  873,  861,  823,  810,  771,  759,  720,
   118119  /*    70 */   708,  670,  657,  619,  614,  612,  610,  608,  606,  604,
   118120  /*    80 */   598,  595,  593,  580,  542,  540,  537,  535,  533,  531,
   118121  /*    90 */   529,  527,  503,  386,  403,  403,  403,  403,  403,  403,
   118122  /*   100 */   403,  403,  403,   95,  447,   82,  334,  504,  467,  403,
   118123  /*   110 */   477,  464,  403,  403,  403,  403,  860,  747,  744,  785,
   118124  /*   120 */   638,  638,  926,  891,  900,  899,  887,  844,  840,  835,
   118125  /*   130 */   848,  830,  843,  829,  792,  839,  826,  737,  838,  795,
   118126  /*   140 */   789,   47,  734,  530,  696,  777,  711,  677,  733,  730,
   118127  /*   150 */   729,  728,  727,  627,  448,   64,  187, 1305, 1302, 1252,
   118128  /*   160 */  1290, 1273, 1323, 1322, 1321, 1319, 1318, 1316, 1315, 1314,
   118129  /*   170 */  1313, 1312, 1311, 1310, 1308, 1307, 1304, 1303, 1301, 1298,
   118130  /*   180 */  1294, 1292, 1289, 1266, 1264, 1259, 1288, 1287, 1238, 1285,
   118131  /*   190 */  1281, 1280, 1279, 1278, 1251, 1277, 1276, 1275, 1273, 1268,
   118132  /*   200 */  1267, 1265, 1263, 1261, 1257, 1248, 1237, 1247, 1246, 1243,
   118133  /*   210 */  1238, 1240, 1235, 1249, 1234, 1233, 1230, 1220, 1214, 1210,
   118134  /*   220 */  1225, 1219, 1232, 1231, 1197, 1195, 1227, 1224, 1201, 1208,
   118135  /*   230 */  1242, 1137, 1236, 1229, 1193, 1181, 1221, 1177, 1196, 1179,
   118136  /*   240 */  1191, 1190, 1186, 1182, 1218, 1216, 1176, 1162, 1183, 1180,
   118137  /*   250 */  1160, 1199, 1203, 1133, 1095, 1198, 1194, 1188, 1192, 1171,
   118138  /*   260 */  1169, 1168, 1173, 1174, 1166, 1159, 1141, 1170, 1158, 1167,
   118139  /*   270 */  1157, 1132, 1145, 1143, 1124, 1128, 1103, 1102, 1100, 1096,
   118140  /*   280 */  1150, 1149, 1085, 1125, 1080, 1064, 1120, 1097, 1082, 1078,
   118141  /*   290 */  1073, 1067, 1109, 1107, 1119, 1117, 1116, 1113, 1111, 1108,
   118142  /*   300 */  1007, 1000, 1002, 1076, 1075, 1081,
   118143 };
   118144 static const YYACTIONTYPE yy_default[] = {
   118145  /*     0 */   647,  964,  964,  964,  878,  878,  969,  964,  774,  802,
   118146  /*    10 */   802,  938,  969,  969,  969,  876,  969,  969,  969,  964,
   118147  /*    20 */   969,  778,  808,  969,  969,  969,  969,  969,  969,  969,
   118148  /*    30 */   969,  937,  939,  816,  815,  918,  789,  813,  806,  810,
   118149  /*    40 */   879,  872,  873,  871,  875,  880,  969,  809,  841,  856,
   118150  /*    50 */   840,  969,  969,  969,  969,  969,  969,  969,  969,  969,
   118151  /*    60 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
   118152  /*    70 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
   118153  /*    80 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
   118154  /*    90 */   969,  969,  969,  969,  850,  855,  862,  854,  851,  843,
   118155  /*   100 */   842,  844,  845,  969,  969,  673,  739,  969,  969,  846,
   118156  /*   110 */   969,  685,  847,  859,  858,  857,  680,  969,  969,  969,
   118157  /*   120 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
   118158  /*   130 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
   118159  /*   140 */   969,  969,  969,  969,  647,  964,  969,  969,  964,  964,
   118160  /*   150 */   964,  964,  964,  964,  956,  778,  768,  969,  969,  969,
   118161  /*   160 */   969,  969,  969,  969,  969,  969,  969,  944,  942,  969,
   118162  /*   170 */   891,  969,  969,  969,  969,  969,  969,  969,  969,  969,
   118163  /*   180 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
   118164  /*   190 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
   118165  /*   200 */   969,  969,  969,  969,  653,  969,  911,  774,  774,  774,
   118166  /*   210 */   776,  754,  766,  655,  812,  791,  791,  923,  812,  923,
   118167  /*   220 */   710,  733,  707,  802,  791,  874,  802,  802,  775,  766,
   118168  /*   230 */   969,  949,  782,  782,  941,  941,  782,  821,  743,  812,
   118169  /*   240 */   750,  750,  750,  750,  782,  670,  812,  821,  743,  743,
   118170  /*   250 */   812,  782,  670,  917,  915,  782,  782,  670,  782,  670,
   118171  /*   260 */   782,  670,  884,  741,  741,  741,  725,  884,  741,  710,
   118172  /*   270 */   741,  725,  741,  741,  795,  790,  795,  790,  795,  790,
   118173  /*   280 */   782,  782,  969,  884,  888,  888,  884,  807,  796,  805,
   118174  /*   290 */   803,  812,  676,  728,  663,  663,  652,  652,  652,  652,
   118175  /*   300 */   961,  961,  956,  712,  712,  695,  969,  969,  969,  969,
   118176  /*   310 */   969,  969,  687,  969,  893,  969,  969,  969,  969,  969,
   118177  /*   320 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
   118178  /*   330 */   969,  828,  969,  648,  951,  969,  969,  948,  969,  969,
   118179  /*   340 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
   118180  /*   350 */   969,  969,  969,  969,  969,  969,  921,  969,  969,  969,
   118181  /*   360 */   969,  969,  969,  914,  913,  969,  969,  969,  969,  969,
   118182  /*   370 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
   118183  /*   380 */   969,  969,  969,  969,  969,  969,  969,  757,  969,  969,
   118184  /*   390 */   969,  761,  969,  969,  969,  969,  969,  969,  804,  969,
   118185  /*   400 */   797,  969,  877,  969,  969,  969,  969,  969,  969,  969,
   118186  /*   410 */   969,  969,  969,  966,  969,  969,  969,  965,  969,  969,
   118187  /*   420 */   969,  969,  969,  830,  969,  829,  833,  969,  661,  969,
   118188  /*   430 */   644,  649,  960,  963,  962,  959,  958,  957,  952,  950,
   118189  /*   440 */   947,  946,  945,  943,  940,  936,  897,  895,  902,  901,
   118190  /*   450 */   900,  899,  898,  896,  894,  892,  818,  817,  814,  811,
   118191  /*   460 */   753,  935,  890,  752,  749,  748,  669,  953,  920,  929,
   118192  /*   470 */   928,  927,  822,  926,  925,  924,  922,  919,  906,  820,
   118193  /*   480 */   819,  744,  882,  881,  672,  910,  909,  908,  912,  916,
   118194  /*   490 */   907,  784,  751,  671,  668,  675,  679,  731,  732,  740,
   118195  /*   500 */   738,  737,  736,  735,  734,  730,  681,  686,  724,  709,
   118196  /*   510 */   708,  717,  716,  722,  721,  720,  719,  718,  715,  714,
   118197  /*   520 */   713,  706,  705,  711,  704,  727,  726,  723,  703,  747,
   118198  /*   530 */   746,  745,  742,  702,  701,  700,  833,  699,  698,  838,
   118199  /*   540 */   837,  866,  826,  755,  759,  758,  762,  763,  771,  770,
   118200  /*   550 */   769,  780,  781,  793,  792,  824,  823,  794,  779,  773,
   118201  /*   560 */   772,  788,  787,  786,  785,  777,  767,  799,  798,  868,
   118202  /*   570 */   783,  867,  865,  934,  933,  932,  931,  930,  870,  967,
   118203  /*   580 */   968,  887,  889,  886,  801,  800,  885,  869,  839,  836,
   118204  /*   590 */   690,  691,  905,  904,  903,  693,  692,  689,  688,  863,
   118205  /*   600 */   860,  852,  864,  861,  853,  849,  848,  834,  832,  831,
   118206  /*   610 */   827,  835,  760,  756,  825,  765,  764,  697,  696,  694,
   118207  /*   620 */   678,  677,  674,  667,  665,  664,  666,  662,  660,  659,
   118208  /*   630 */   658,  657,  656,  684,  683,  682,  654,  651,  650,  646,
   118209  /*   640 */   645,  643,
   118210 };
   118211 
   118212 /* The next table maps tokens into fallback tokens.  If a construct
   118213 ** like the following:
   118214 **
   118215 **      %fallback ID X Y Z.
   118216 **
   118217 ** appears in the grammar, then ID becomes a fallback token for X, Y,
   118218 ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
   118219 ** but it does not parse, the type of the token is changed to ID and
   118220 ** the parse is retried before an error is thrown.
   118221 */
   118222 #ifdef YYFALLBACK
   118223 static const YYCODETYPE yyFallback[] = {
   118224     0,  /*          $ => nothing */
   118225     0,  /*       SEMI => nothing */
   118226    27,  /*    EXPLAIN => ID */
   118227    27,  /*      QUERY => ID */
   118228    27,  /*       PLAN => ID */
   118229    27,  /*      BEGIN => ID */
   118230     0,  /* TRANSACTION => nothing */
   118231    27,  /*   DEFERRED => ID */
   118232    27,  /*  IMMEDIATE => ID */
   118233    27,  /*  EXCLUSIVE => ID */
   118234     0,  /*     COMMIT => nothing */
   118235    27,  /*        END => ID */
   118236    27,  /*   ROLLBACK => ID */
   118237    27,  /*  SAVEPOINT => ID */
   118238    27,  /*    RELEASE => ID */
   118239     0,  /*         TO => nothing */
   118240     0,  /*      TABLE => nothing */
   118241     0,  /*     CREATE => nothing */
   118242    27,  /*         IF => ID */
   118243     0,  /*        NOT => nothing */
   118244     0,  /*     EXISTS => nothing */
   118245    27,  /*       TEMP => ID */
   118246     0,  /*         LP => nothing */
   118247     0,  /*         RP => nothing */
   118248     0,  /*         AS => nothing */
   118249    27,  /*    WITHOUT => ID */
   118250     0,  /*      COMMA => nothing */
   118251     0,  /*         ID => nothing */
   118252     0,  /*    INDEXED => nothing */
   118253    27,  /*      ABORT => ID */
   118254    27,  /*     ACTION => ID */
   118255    27,  /*      AFTER => ID */
   118256    27,  /*    ANALYZE => ID */
   118257    27,  /*        ASC => ID */
   118258    27,  /*     ATTACH => ID */
   118259    27,  /*     BEFORE => ID */
   118260    27,  /*         BY => ID */
   118261    27,  /*    CASCADE => ID */
   118262    27,  /*       CAST => ID */
   118263    27,  /*   COLUMNKW => ID */
   118264    27,  /*   CONFLICT => ID */
   118265    27,  /*   DATABASE => ID */
   118266    27,  /*       DESC => ID */
   118267    27,  /*     DETACH => ID */
   118268    27,  /*       EACH => ID */
   118269    27,  /*       FAIL => ID */
   118270    27,  /*        FOR => ID */
   118271    27,  /*     IGNORE => ID */
   118272    27,  /*  INITIALLY => ID */
   118273    27,  /*    INSTEAD => ID */
   118274    27,  /*    LIKE_KW => ID */
   118275    27,  /*      MATCH => ID */
   118276    27,  /*         NO => ID */
   118277    27,  /*        KEY => ID */
   118278    27,  /*         OF => ID */
   118279    27,  /*     OFFSET => ID */
   118280    27,  /*     PRAGMA => ID */
   118281    27,  /*      RAISE => ID */
   118282    27,  /*  RECURSIVE => ID */
   118283    27,  /*    REPLACE => ID */
   118284    27,  /*   RESTRICT => ID */
   118285    27,  /*        ROW => ID */
   118286    27,  /*    TRIGGER => ID */
   118287    27,  /*     VACUUM => ID */
   118288    27,  /*       VIEW => ID */
   118289    27,  /*    VIRTUAL => ID */
   118290    27,  /*       WITH => ID */
   118291    27,  /*    REINDEX => ID */
   118292    27,  /*     RENAME => ID */
   118293    27,  /*   CTIME_KW => ID */
   118294 };
   118295 #endif /* YYFALLBACK */
   118296 
   118297 /* The following structure represents a single element of the
   118298 ** parser's stack.  Information stored includes:
   118299 **
   118300 **   +  The state number for the parser at this level of the stack.
   118301 **
   118302 **   +  The value of the token stored at this level of the stack.
   118303 **      (In other words, the "major" token.)
   118304 **
   118305 **   +  The semantic value stored at this level of the stack.  This is
   118306 **      the information used by the action routines in the grammar.
   118307 **      It is sometimes called the "minor" token.
   118308 */
   118309 struct yyStackEntry {
   118310   YYACTIONTYPE stateno;  /* The state-number */
   118311   YYCODETYPE major;      /* The major token value.  This is the code
   118312                          ** number for the token at this stack level */
   118313   YYMINORTYPE minor;     /* The user-supplied minor token value.  This
   118314                          ** is the value of the token  */
   118315 };
   118316 typedef struct yyStackEntry yyStackEntry;
   118317 
   118318 /* The state of the parser is completely contained in an instance of
   118319 ** the following structure */
   118320 struct yyParser {
   118321   int yyidx;                    /* Index of top element in stack */
   118322 #ifdef YYTRACKMAXSTACKDEPTH
   118323   int yyidxMax;                 /* Maximum value of yyidx */
   118324 #endif
   118325   int yyerrcnt;                 /* Shifts left before out of the error */
   118326   sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
   118327 #if YYSTACKDEPTH<=0
   118328   int yystksz;                  /* Current side of the stack */
   118329   yyStackEntry *yystack;        /* The parser's stack */
   118330 #else
   118331   yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
   118332 #endif
   118333 };
   118334 typedef struct yyParser yyParser;
   118335 
   118336 #ifndef NDEBUG
   118337 /* #include <stdio.h> */
   118338 static FILE *yyTraceFILE = 0;
   118339 static char *yyTracePrompt = 0;
   118340 #endif /* NDEBUG */
   118341 
   118342 #ifndef NDEBUG
   118343 /*
   118344 ** Turn parser tracing on by giving a stream to which to write the trace
   118345 ** and a prompt to preface each trace message.  Tracing is turned off
   118346 ** by making either argument NULL
   118347 **
   118348 ** Inputs:
   118349 ** <ul>
   118350 ** <li> A FILE* to which trace output should be written.
   118351 **      If NULL, then tracing is turned off.
   118352 ** <li> A prefix string written at the beginning of every
   118353 **      line of trace output.  If NULL, then tracing is
   118354 **      turned off.
   118355 ** </ul>
   118356 **
   118357 ** Outputs:
   118358 ** None.
   118359 */
   118360 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
   118361   yyTraceFILE = TraceFILE;
   118362   yyTracePrompt = zTracePrompt;
   118363   if( yyTraceFILE==0 ) yyTracePrompt = 0;
   118364   else if( yyTracePrompt==0 ) yyTraceFILE = 0;
   118365 }
   118366 #endif /* NDEBUG */
   118367 
   118368 #ifndef NDEBUG
   118369 /* For tracing shifts, the names of all terminals and nonterminals
   118370 ** are required.  The following table supplies these names */
   118371 static const char *const yyTokenName[] = {
   118372   "$",             "SEMI",          "EXPLAIN",       "QUERY",
   118373   "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",
   118374   "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",
   118375   "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",
   118376   "TABLE",         "CREATE",        "IF",            "NOT",
   118377   "EXISTS",        "TEMP",          "LP",            "RP",
   118378   "AS",            "WITHOUT",       "COMMA",         "ID",
   118379   "INDEXED",       "ABORT",         "ACTION",        "AFTER",
   118380   "ANALYZE",       "ASC",           "ATTACH",        "BEFORE",
   118381   "BY",            "CASCADE",       "CAST",          "COLUMNKW",
   118382   "CONFLICT",      "DATABASE",      "DESC",          "DETACH",
   118383   "EACH",          "FAIL",          "FOR",           "IGNORE",
   118384   "INITIALLY",     "INSTEAD",       "LIKE_KW",       "MATCH",
   118385   "NO",            "KEY",           "OF",            "OFFSET",
   118386   "PRAGMA",        "RAISE",         "RECURSIVE",     "REPLACE",
   118387   "RESTRICT",      "ROW",           "TRIGGER",       "VACUUM",
   118388   "VIEW",          "VIRTUAL",       "WITH",          "REINDEX",
   118389   "RENAME",        "CTIME_KW",      "ANY",           "OR",
   118390   "AND",           "IS",            "BETWEEN",       "IN",
   118391   "ISNULL",        "NOTNULL",       "NE",            "EQ",
   118392   "GT",            "LE",            "LT",            "GE",
   118393   "ESCAPE",        "BITAND",        "BITOR",         "LSHIFT",
   118394   "RSHIFT",        "PLUS",          "MINUS",         "STAR",
   118395   "SLASH",         "REM",           "CONCAT",        "COLLATE",
   118396   "BITNOT",        "STRING",        "JOIN_KW",       "CONSTRAINT",
   118397   "DEFAULT",       "NULL",          "PRIMARY",       "UNIQUE",
   118398   "CHECK",         "REFERENCES",    "AUTOINCR",      "ON",
   118399   "INSERT",        "DELETE",        "UPDATE",        "SET",
   118400   "DEFERRABLE",    "FOREIGN",       "DROP",          "UNION",
   118401   "ALL",           "EXCEPT",        "INTERSECT",     "SELECT",
   118402   "VALUES",        "DISTINCT",      "DOT",           "FROM",
   118403   "JOIN",          "USING",         "ORDER",         "GROUP",
   118404   "HAVING",        "LIMIT",         "WHERE",         "INTO",
   118405   "INTEGER",       "FLOAT",         "BLOB",          "VARIABLE",
   118406   "CASE",          "WHEN",          "THEN",          "ELSE",
   118407   "INDEX",         "ALTER",         "ADD",           "error",
   118408   "input",         "cmdlist",       "ecmd",          "explain",
   118409   "cmdx",          "cmd",           "transtype",     "trans_opt",
   118410   "nm",            "savepoint_opt",  "create_table",  "create_table_args",
   118411   "createkw",      "temp",          "ifnotexists",   "dbnm",
   118412   "columnlist",    "conslist_opt",  "table_options",  "select",
   118413   "column",        "columnid",      "type",          "carglist",
   118414   "typetoken",     "typename",      "signed",        "plus_num",
   118415   "minus_num",     "ccons",         "term",          "expr",
   118416   "onconf",        "sortorder",     "autoinc",       "idxlist_opt",
   118417   "refargs",       "defer_subclause",  "refarg",        "refact",
   118418   "init_deferred_pred_opt",  "conslist",      "tconscomma",    "tcons",
   118419   "idxlist",       "defer_subclause_opt",  "orconf",        "resolvetype",
   118420   "raisetype",     "ifexists",      "fullname",      "selectnowith",
   118421   "oneselect",     "with",          "multiselect_op",  "distinct",
   118422   "selcollist",    "from",          "where_opt",     "groupby_opt",
   118423   "having_opt",    "orderby_opt",   "limit_opt",     "values",
   118424   "nexprlist",     "exprlist",      "sclp",          "as",
   118425   "seltablist",    "stl_prefix",    "joinop",        "indexed_opt",
   118426   "on_opt",        "using_opt",     "joinop2",       "idlist",
   118427   "sortlist",      "setlist",       "insert_cmd",    "inscollist_opt",
   118428   "likeop",        "between_op",    "in_op",         "case_operand",
   118429   "case_exprlist",  "case_else",     "uniqueflag",    "collate",
   118430   "nmnum",         "trigger_decl",  "trigger_cmd_list",  "trigger_time",
   118431   "trigger_event",  "foreach_clause",  "when_clause",   "trigger_cmd",
   118432   "trnm",          "tridxby",       "database_kw_opt",  "key_opt",
   118433   "add_column_fullname",  "kwcolumn_opt",  "create_vtab",   "vtabarglist",
   118434   "vtabarg",       "vtabargtoken",  "lp",            "anylist",
   118435   "wqlist",
   118436 };
   118437 #endif /* NDEBUG */
   118438 
   118439 #ifndef NDEBUG
   118440 /* For tracing reduce actions, the names of all rules are required.
   118441 */
   118442 static const char *const yyRuleName[] = {
   118443  /*   0 */ "input ::= cmdlist",
   118444  /*   1 */ "cmdlist ::= cmdlist ecmd",
   118445  /*   2 */ "cmdlist ::= ecmd",
   118446  /*   3 */ "ecmd ::= SEMI",
   118447  /*   4 */ "ecmd ::= explain cmdx SEMI",
   118448  /*   5 */ "explain ::=",
   118449  /*   6 */ "explain ::= EXPLAIN",
   118450  /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
   118451  /*   8 */ "cmdx ::= cmd",
   118452  /*   9 */ "cmd ::= BEGIN transtype trans_opt",
   118453  /*  10 */ "trans_opt ::=",
   118454  /*  11 */ "trans_opt ::= TRANSACTION",
   118455  /*  12 */ "trans_opt ::= TRANSACTION nm",
   118456  /*  13 */ "transtype ::=",
   118457  /*  14 */ "transtype ::= DEFERRED",
   118458  /*  15 */ "transtype ::= IMMEDIATE",
   118459  /*  16 */ "transtype ::= EXCLUSIVE",
   118460  /*  17 */ "cmd ::= COMMIT trans_opt",
   118461  /*  18 */ "cmd ::= END trans_opt",
   118462  /*  19 */ "cmd ::= ROLLBACK trans_opt",
   118463  /*  20 */ "savepoint_opt ::= SAVEPOINT",
   118464  /*  21 */ "savepoint_opt ::=",
   118465  /*  22 */ "cmd ::= SAVEPOINT nm",
   118466  /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
   118467  /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
   118468  /*  25 */ "cmd ::= create_table create_table_args",
   118469  /*  26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
   118470  /*  27 */ "createkw ::= CREATE",
   118471  /*  28 */ "ifnotexists ::=",
   118472  /*  29 */ "ifnotexists ::= IF NOT EXISTS",
   118473  /*  30 */ "temp ::= TEMP",
   118474  /*  31 */ "temp ::=",
   118475  /*  32 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
   118476  /*  33 */ "create_table_args ::= AS select",
   118477  /*  34 */ "table_options ::=",
   118478  /*  35 */ "table_options ::= WITHOUT nm",
   118479  /*  36 */ "columnlist ::= columnlist COMMA column",
   118480  /*  37 */ "columnlist ::= column",
   118481  /*  38 */ "column ::= columnid type carglist",
   118482  /*  39 */ "columnid ::= nm",
   118483  /*  40 */ "nm ::= ID|INDEXED",
   118484  /*  41 */ "nm ::= STRING",
   118485  /*  42 */ "nm ::= JOIN_KW",
   118486  /*  43 */ "type ::=",
   118487  /*  44 */ "type ::= typetoken",
   118488  /*  45 */ "typetoken ::= typename",
   118489  /*  46 */ "typetoken ::= typename LP signed RP",
   118490  /*  47 */ "typetoken ::= typename LP signed COMMA signed RP",
   118491  /*  48 */ "typename ::= ID|STRING",
   118492  /*  49 */ "typename ::= typename ID|STRING",
   118493  /*  50 */ "signed ::= plus_num",
   118494  /*  51 */ "signed ::= minus_num",
   118495  /*  52 */ "carglist ::= carglist ccons",
   118496  /*  53 */ "carglist ::=",
   118497  /*  54 */ "ccons ::= CONSTRAINT nm",
   118498  /*  55 */ "ccons ::= DEFAULT term",
   118499  /*  56 */ "ccons ::= DEFAULT LP expr RP",
   118500  /*  57 */ "ccons ::= DEFAULT PLUS term",
   118501  /*  58 */ "ccons ::= DEFAULT MINUS term",
   118502  /*  59 */ "ccons ::= DEFAULT ID|INDEXED",
   118503  /*  60 */ "ccons ::= NULL onconf",
   118504  /*  61 */ "ccons ::= NOT NULL onconf",
   118505  /*  62 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
   118506  /*  63 */ "ccons ::= UNIQUE onconf",
   118507  /*  64 */ "ccons ::= CHECK LP expr RP",
   118508  /*  65 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
   118509  /*  66 */ "ccons ::= defer_subclause",
   118510  /*  67 */ "ccons ::= COLLATE ID|STRING",
   118511  /*  68 */ "autoinc ::=",
   118512  /*  69 */ "autoinc ::= AUTOINCR",
   118513  /*  70 */ "refargs ::=",
   118514  /*  71 */ "refargs ::= refargs refarg",
   118515  /*  72 */ "refarg ::= MATCH nm",
   118516  /*  73 */ "refarg ::= ON INSERT refact",
   118517  /*  74 */ "refarg ::= ON DELETE refact",
   118518  /*  75 */ "refarg ::= ON UPDATE refact",
   118519  /*  76 */ "refact ::= SET NULL",
   118520  /*  77 */ "refact ::= SET DEFAULT",
   118521  /*  78 */ "refact ::= CASCADE",
   118522  /*  79 */ "refact ::= RESTRICT",
   118523  /*  80 */ "refact ::= NO ACTION",
   118524  /*  81 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
   118525  /*  82 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
   118526  /*  83 */ "init_deferred_pred_opt ::=",
   118527  /*  84 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
   118528  /*  85 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
   118529  /*  86 */ "conslist_opt ::=",
   118530  /*  87 */ "conslist_opt ::= COMMA conslist",
   118531  /*  88 */ "conslist ::= conslist tconscomma tcons",
   118532  /*  89 */ "conslist ::= tcons",
   118533  /*  90 */ "tconscomma ::= COMMA",
   118534  /*  91 */ "tconscomma ::=",
   118535  /*  92 */ "tcons ::= CONSTRAINT nm",
   118536  /*  93 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
   118537  /*  94 */ "tcons ::= UNIQUE LP idxlist RP onconf",
   118538  /*  95 */ "tcons ::= CHECK LP expr RP onconf",
   118539  /*  96 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
   118540  /*  97 */ "defer_subclause_opt ::=",
   118541  /*  98 */ "defer_subclause_opt ::= defer_subclause",
   118542  /*  99 */ "onconf ::=",
   118543  /* 100 */ "onconf ::= ON CONFLICT resolvetype",
   118544  /* 101 */ "orconf ::=",
   118545  /* 102 */ "orconf ::= OR resolvetype",
   118546  /* 103 */ "resolvetype ::= raisetype",
   118547  /* 104 */ "resolvetype ::= IGNORE",
   118548  /* 105 */ "resolvetype ::= REPLACE",
   118549  /* 106 */ "cmd ::= DROP TABLE ifexists fullname",
   118550  /* 107 */ "ifexists ::= IF EXISTS",
   118551  /* 108 */ "ifexists ::=",
   118552  /* 109 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
   118553  /* 110 */ "cmd ::= DROP VIEW ifexists fullname",
   118554  /* 111 */ "cmd ::= select",
   118555  /* 112 */ "select ::= with selectnowith",
   118556  /* 113 */ "selectnowith ::= oneselect",
   118557  /* 114 */ "selectnowith ::= selectnowith multiselect_op oneselect",
   118558  /* 115 */ "multiselect_op ::= UNION",
   118559  /* 116 */ "multiselect_op ::= UNION ALL",
   118560  /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
   118561  /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
   118562  /* 119 */ "oneselect ::= values",
   118563  /* 120 */ "values ::= VALUES LP nexprlist RP",
   118564  /* 121 */ "values ::= values COMMA LP exprlist RP",
   118565  /* 122 */ "distinct ::= DISTINCT",
   118566  /* 123 */ "distinct ::= ALL",
   118567  /* 124 */ "distinct ::=",
   118568  /* 125 */ "sclp ::= selcollist COMMA",
   118569  /* 126 */ "sclp ::=",
   118570  /* 127 */ "selcollist ::= sclp expr as",
   118571  /* 128 */ "selcollist ::= sclp STAR",
   118572  /* 129 */ "selcollist ::= sclp nm DOT STAR",
   118573  /* 130 */ "as ::= AS nm",
   118574  /* 131 */ "as ::= ID|STRING",
   118575  /* 132 */ "as ::=",
   118576  /* 133 */ "from ::=",
   118577  /* 134 */ "from ::= FROM seltablist",
   118578  /* 135 */ "stl_prefix ::= seltablist joinop",
   118579  /* 136 */ "stl_prefix ::=",
   118580  /* 137 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
   118581  /* 138 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
   118582  /* 139 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
   118583  /* 140 */ "dbnm ::=",
   118584  /* 141 */ "dbnm ::= DOT nm",
   118585  /* 142 */ "fullname ::= nm dbnm",
   118586  /* 143 */ "joinop ::= COMMA|JOIN",
   118587  /* 144 */ "joinop ::= JOIN_KW JOIN",
   118588  /* 145 */ "joinop ::= JOIN_KW nm JOIN",
   118589  /* 146 */ "joinop ::= JOIN_KW nm nm JOIN",
   118590  /* 147 */ "on_opt ::= ON expr",
   118591  /* 148 */ "on_opt ::=",
   118592  /* 149 */ "indexed_opt ::=",
   118593  /* 150 */ "indexed_opt ::= INDEXED BY nm",
   118594  /* 151 */ "indexed_opt ::= NOT INDEXED",
   118595  /* 152 */ "using_opt ::= USING LP idlist RP",
   118596  /* 153 */ "using_opt ::=",
   118597  /* 154 */ "orderby_opt ::=",
   118598  /* 155 */ "orderby_opt ::= ORDER BY sortlist",
   118599  /* 156 */ "sortlist ::= sortlist COMMA expr sortorder",
   118600  /* 157 */ "sortlist ::= expr sortorder",
   118601  /* 158 */ "sortorder ::= ASC",
   118602  /* 159 */ "sortorder ::= DESC",
   118603  /* 160 */ "sortorder ::=",
   118604  /* 161 */ "groupby_opt ::=",
   118605  /* 162 */ "groupby_opt ::= GROUP BY nexprlist",
   118606  /* 163 */ "having_opt ::=",
   118607  /* 164 */ "having_opt ::= HAVING expr",
   118608  /* 165 */ "limit_opt ::=",
   118609  /* 166 */ "limit_opt ::= LIMIT expr",
   118610  /* 167 */ "limit_opt ::= LIMIT expr OFFSET expr",
   118611  /* 168 */ "limit_opt ::= LIMIT expr COMMA expr",
   118612  /* 169 */ "cmd ::= with DELETE FROM fullname indexed_opt where_opt",
   118613  /* 170 */ "where_opt ::=",
   118614  /* 171 */ "where_opt ::= WHERE expr",
   118615  /* 172 */ "cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt",
   118616  /* 173 */ "setlist ::= setlist COMMA nm EQ expr",
   118617  /* 174 */ "setlist ::= nm EQ expr",
   118618  /* 175 */ "cmd ::= with insert_cmd INTO fullname inscollist_opt select",
   118619  /* 176 */ "cmd ::= with insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
   118620  /* 177 */ "insert_cmd ::= INSERT orconf",
   118621  /* 178 */ "insert_cmd ::= REPLACE",
   118622  /* 179 */ "inscollist_opt ::=",
   118623  /* 180 */ "inscollist_opt ::= LP idlist RP",
   118624  /* 181 */ "idlist ::= idlist COMMA nm",
   118625  /* 182 */ "idlist ::= nm",
   118626  /* 183 */ "expr ::= term",
   118627  /* 184 */ "expr ::= LP expr RP",
   118628  /* 185 */ "term ::= NULL",
   118629  /* 186 */ "expr ::= ID|INDEXED",
   118630  /* 187 */ "expr ::= JOIN_KW",
   118631  /* 188 */ "expr ::= nm DOT nm",
   118632  /* 189 */ "expr ::= nm DOT nm DOT nm",
   118633  /* 190 */ "term ::= INTEGER|FLOAT|BLOB",
   118634  /* 191 */ "term ::= STRING",
   118635  /* 192 */ "expr ::= VARIABLE",
   118636  /* 193 */ "expr ::= expr COLLATE ID|STRING",
   118637  /* 194 */ "expr ::= CAST LP expr AS typetoken RP",
   118638  /* 195 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
   118639  /* 196 */ "expr ::= ID|INDEXED LP STAR RP",
   118640  /* 197 */ "term ::= CTIME_KW",
   118641  /* 198 */ "expr ::= expr AND expr",
   118642  /* 199 */ "expr ::= expr OR expr",
   118643  /* 200 */ "expr ::= expr LT|GT|GE|LE expr",
   118644  /* 201 */ "expr ::= expr EQ|NE expr",
   118645  /* 202 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
   118646  /* 203 */ "expr ::= expr PLUS|MINUS expr",
   118647  /* 204 */ "expr ::= expr STAR|SLASH|REM expr",
   118648  /* 205 */ "expr ::= expr CONCAT expr",
   118649  /* 206 */ "likeop ::= LIKE_KW|MATCH",
   118650  /* 207 */ "likeop ::= NOT LIKE_KW|MATCH",
   118651  /* 208 */ "expr ::= expr likeop expr",
   118652  /* 209 */ "expr ::= expr likeop expr ESCAPE expr",
   118653  /* 210 */ "expr ::= expr ISNULL|NOTNULL",
   118654  /* 211 */ "expr ::= expr NOT NULL",
   118655  /* 212 */ "expr ::= expr IS expr",
   118656  /* 213 */ "expr ::= expr IS NOT expr",
   118657  /* 214 */ "expr ::= NOT expr",
   118658  /* 215 */ "expr ::= BITNOT expr",
   118659  /* 216 */ "expr ::= MINUS expr",
   118660  /* 217 */ "expr ::= PLUS expr",
   118661  /* 218 */ "between_op ::= BETWEEN",
   118662  /* 219 */ "between_op ::= NOT BETWEEN",
   118663  /* 220 */ "expr ::= expr between_op expr AND expr",
   118664  /* 221 */ "in_op ::= IN",
   118665  /* 222 */ "in_op ::= NOT IN",
   118666  /* 223 */ "expr ::= expr in_op LP exprlist RP",
   118667  /* 224 */ "expr ::= LP select RP",
   118668  /* 225 */ "expr ::= expr in_op LP select RP",
   118669  /* 226 */ "expr ::= expr in_op nm dbnm",
   118670  /* 227 */ "expr ::= EXISTS LP select RP",
   118671  /* 228 */ "expr ::= CASE case_operand case_exprlist case_else END",
   118672  /* 229 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
   118673  /* 230 */ "case_exprlist ::= WHEN expr THEN expr",
   118674  /* 231 */ "case_else ::= ELSE expr",
   118675  /* 232 */ "case_else ::=",
   118676  /* 233 */ "case_operand ::= expr",
   118677  /* 234 */ "case_operand ::=",
   118678  /* 235 */ "exprlist ::= nexprlist",
   118679  /* 236 */ "exprlist ::=",
   118680  /* 237 */ "nexprlist ::= nexprlist COMMA expr",
   118681  /* 238 */ "nexprlist ::= expr",
   118682  /* 239 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt",
   118683  /* 240 */ "uniqueflag ::= UNIQUE",
   118684  /* 241 */ "uniqueflag ::=",
   118685  /* 242 */ "idxlist_opt ::=",
   118686  /* 243 */ "idxlist_opt ::= LP idxlist RP",
   118687  /* 244 */ "idxlist ::= idxlist COMMA nm collate sortorder",
   118688  /* 245 */ "idxlist ::= nm collate sortorder",
   118689  /* 246 */ "collate ::=",
   118690  /* 247 */ "collate ::= COLLATE ID|STRING",
   118691  /* 248 */ "cmd ::= DROP INDEX ifexists fullname",
   118692  /* 249 */ "cmd ::= VACUUM",
   118693  /* 250 */ "cmd ::= VACUUM nm",
   118694  /* 251 */ "cmd ::= PRAGMA nm dbnm",
   118695  /* 252 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
   118696  /* 253 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
   118697  /* 254 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
   118698  /* 255 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
   118699  /* 256 */ "nmnum ::= plus_num",
   118700  /* 257 */ "nmnum ::= nm",
   118701  /* 258 */ "nmnum ::= ON",
   118702  /* 259 */ "nmnum ::= DELETE",
   118703  /* 260 */ "nmnum ::= DEFAULT",
   118704  /* 261 */ "plus_num ::= PLUS INTEGER|FLOAT",
   118705  /* 262 */ "plus_num ::= INTEGER|FLOAT",
   118706  /* 263 */ "minus_num ::= MINUS INTEGER|FLOAT",
   118707  /* 264 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
   118708  /* 265 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
   118709  /* 266 */ "trigger_time ::= BEFORE",
   118710  /* 267 */ "trigger_time ::= AFTER",
   118711  /* 268 */ "trigger_time ::= INSTEAD OF",
   118712  /* 269 */ "trigger_time ::=",
   118713  /* 270 */ "trigger_event ::= DELETE|INSERT",
   118714  /* 271 */ "trigger_event ::= UPDATE",
   118715  /* 272 */ "trigger_event ::= UPDATE OF idlist",
   118716  /* 273 */ "foreach_clause ::=",
   118717  /* 274 */ "foreach_clause ::= FOR EACH ROW",
   118718  /* 275 */ "when_clause ::=",
   118719  /* 276 */ "when_clause ::= WHEN expr",
   118720  /* 277 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
   118721  /* 278 */ "trigger_cmd_list ::= trigger_cmd SEMI",
   118722  /* 279 */ "trnm ::= nm",
   118723  /* 280 */ "trnm ::= nm DOT nm",
   118724  /* 281 */ "tridxby ::=",
   118725  /* 282 */ "tridxby ::= INDEXED BY nm",
   118726  /* 283 */ "tridxby ::= NOT INDEXED",
   118727  /* 284 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
   118728  /* 285 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
   118729  /* 286 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
   118730  /* 287 */ "trigger_cmd ::= select",
   118731  /* 288 */ "expr ::= RAISE LP IGNORE RP",
   118732  /* 289 */ "expr ::= RAISE LP raisetype COMMA nm RP",
   118733  /* 290 */ "raisetype ::= ROLLBACK",
   118734  /* 291 */ "raisetype ::= ABORT",
   118735  /* 292 */ "raisetype ::= FAIL",
   118736  /* 293 */ "cmd ::= DROP TRIGGER ifexists fullname",
   118737  /* 294 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
   118738  /* 295 */ "cmd ::= DETACH database_kw_opt expr",
   118739  /* 296 */ "key_opt ::=",
   118740  /* 297 */ "key_opt ::= KEY expr",
   118741  /* 298 */ "database_kw_opt ::= DATABASE",
   118742  /* 299 */ "database_kw_opt ::=",
   118743  /* 300 */ "cmd ::= REINDEX",
   118744  /* 301 */ "cmd ::= REINDEX nm dbnm",
   118745  /* 302 */ "cmd ::= ANALYZE",
   118746  /* 303 */ "cmd ::= ANALYZE nm dbnm",
   118747  /* 304 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
   118748  /* 305 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
   118749  /* 306 */ "add_column_fullname ::= fullname",
   118750  /* 307 */ "kwcolumn_opt ::=",
   118751  /* 308 */ "kwcolumn_opt ::= COLUMNKW",
   118752  /* 309 */ "cmd ::= create_vtab",
   118753  /* 310 */ "cmd ::= create_vtab LP vtabarglist RP",
   118754  /* 311 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
   118755  /* 312 */ "vtabarglist ::= vtabarg",
   118756  /* 313 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
   118757  /* 314 */ "vtabarg ::=",
   118758  /* 315 */ "vtabarg ::= vtabarg vtabargtoken",
   118759  /* 316 */ "vtabargtoken ::= ANY",
   118760  /* 317 */ "vtabargtoken ::= lp anylist RP",
   118761  /* 318 */ "lp ::= LP",
   118762  /* 319 */ "anylist ::=",
   118763  /* 320 */ "anylist ::= anylist LP anylist RP",
   118764  /* 321 */ "anylist ::= anylist ANY",
   118765  /* 322 */ "with ::=",
   118766  /* 323 */ "with ::= WITH wqlist",
   118767  /* 324 */ "with ::= WITH RECURSIVE wqlist",
   118768  /* 325 */ "wqlist ::= nm idxlist_opt AS LP select RP",
   118769  /* 326 */ "wqlist ::= wqlist COMMA nm idxlist_opt AS LP select RP",
   118770 };
   118771 #endif /* NDEBUG */
   118772 
   118773 
   118774 #if YYSTACKDEPTH<=0
   118775 /*
   118776 ** Try to increase the size of the parser stack.
   118777 */
   118778 static void yyGrowStack(yyParser *p){
   118779   int newSize;
   118780   yyStackEntry *pNew;
   118781 
   118782   newSize = p->yystksz*2 + 100;
   118783   pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
   118784   if( pNew ){
   118785     p->yystack = pNew;
   118786     p->yystksz = newSize;
   118787 #ifndef NDEBUG
   118788     if( yyTraceFILE ){
   118789       fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
   118790               yyTracePrompt, p->yystksz);
   118791     }
   118792 #endif
   118793   }
   118794 }
   118795 #endif
   118796 
   118797 /*
   118798 ** This function allocates a new parser.
   118799 ** The only argument is a pointer to a function which works like
   118800 ** malloc.
   118801 **
   118802 ** Inputs:
   118803 ** A pointer to the function used to allocate memory.
   118804 **
   118805 ** Outputs:
   118806 ** A pointer to a parser.  This pointer is used in subsequent calls
   118807 ** to sqlite3Parser and sqlite3ParserFree.
   118808 */
   118809 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
   118810   yyParser *pParser;
   118811   pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
   118812   if( pParser ){
   118813     pParser->yyidx = -1;
   118814 #ifdef YYTRACKMAXSTACKDEPTH
   118815     pParser->yyidxMax = 0;
   118816 #endif
   118817 #if YYSTACKDEPTH<=0
   118818     pParser->yystack = NULL;
   118819     pParser->yystksz = 0;
   118820     yyGrowStack(pParser);
   118821 #endif
   118822   }
   118823   return pParser;
   118824 }
   118825 
   118826 /* The following function deletes the value associated with a
   118827 ** symbol.  The symbol can be either a terminal or nonterminal.
   118828 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
   118829 ** the value.
   118830 */
   118831 static void yy_destructor(
   118832   yyParser *yypParser,    /* The parser */
   118833   YYCODETYPE yymajor,     /* Type code for object to destroy */
   118834   YYMINORTYPE *yypminor   /* The object to be destroyed */
   118835 ){
   118836   sqlite3ParserARG_FETCH;
   118837   switch( yymajor ){
   118838     /* Here is inserted the actions which take place when a
   118839     ** terminal or non-terminal is destroyed.  This can happen
   118840     ** when the symbol is popped from the stack during a
   118841     ** reduce or during error processing or when a parser is
   118842     ** being destroyed before it is finished parsing.
   118843     **
   118844     ** Note: during a reduce, the only symbols destroyed are those
   118845     ** which appear on the RHS of the rule, but which are not used
   118846     ** inside the C code.
   118847     */
   118848     case 163: /* select */
   118849     case 195: /* selectnowith */
   118850     case 196: /* oneselect */
   118851     case 207: /* values */
   118852 {
   118853 sqlite3SelectDelete(pParse->db, (yypminor->yy3));
   118854 }
   118855       break;
   118856     case 174: /* term */
   118857     case 175: /* expr */
   118858 {
   118859 sqlite3ExprDelete(pParse->db, (yypminor->yy346).pExpr);
   118860 }
   118861       break;
   118862     case 179: /* idxlist_opt */
   118863     case 188: /* idxlist */
   118864     case 200: /* selcollist */
   118865     case 203: /* groupby_opt */
   118866     case 205: /* orderby_opt */
   118867     case 208: /* nexprlist */
   118868     case 209: /* exprlist */
   118869     case 210: /* sclp */
   118870     case 220: /* sortlist */
   118871     case 221: /* setlist */
   118872     case 228: /* case_exprlist */
   118873 {
   118874 sqlite3ExprListDelete(pParse->db, (yypminor->yy14));
   118875 }
   118876       break;
   118877     case 194: /* fullname */
   118878     case 201: /* from */
   118879     case 212: /* seltablist */
   118880     case 213: /* stl_prefix */
   118881 {
   118882 sqlite3SrcListDelete(pParse->db, (yypminor->yy65));
   118883 }
   118884       break;
   118885     case 197: /* with */
   118886     case 252: /* wqlist */
   118887 {
   118888 sqlite3WithDelete(pParse->db, (yypminor->yy59));
   118889 }
   118890       break;
   118891     case 202: /* where_opt */
   118892     case 204: /* having_opt */
   118893     case 216: /* on_opt */
   118894     case 227: /* case_operand */
   118895     case 229: /* case_else */
   118896     case 238: /* when_clause */
   118897     case 243: /* key_opt */
   118898 {
   118899 sqlite3ExprDelete(pParse->db, (yypminor->yy132));
   118900 }
   118901       break;
   118902     case 217: /* using_opt */
   118903     case 219: /* idlist */
   118904     case 223: /* inscollist_opt */
   118905 {
   118906 sqlite3IdListDelete(pParse->db, (yypminor->yy408));
   118907 }
   118908       break;
   118909     case 234: /* trigger_cmd_list */
   118910     case 239: /* trigger_cmd */
   118911 {
   118912 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy473));
   118913 }
   118914       break;
   118915     case 236: /* trigger_event */
   118916 {
   118917 sqlite3IdListDelete(pParse->db, (yypminor->yy378).b);
   118918 }
   118919       break;
   118920     default:  break;   /* If no destructor action specified: do nothing */
   118921   }
   118922 }
   118923 
   118924 /*
   118925 ** Pop the parser's stack once.
   118926 **
   118927 ** If there is a destructor routine associated with the token which
   118928 ** is popped from the stack, then call it.
   118929 **
   118930 ** Return the major token number for the symbol popped.
   118931 */
   118932 static int yy_pop_parser_stack(yyParser *pParser){
   118933   YYCODETYPE yymajor;
   118934   yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
   118935 
   118936   /* There is no mechanism by which the parser stack can be popped below
   118937   ** empty in SQLite.  */
   118938   if( NEVER(pParser->yyidx<0) ) return 0;
   118939 #ifndef NDEBUG
   118940   if( yyTraceFILE && pParser->yyidx>=0 ){
   118941     fprintf(yyTraceFILE,"%sPopping %s\n",
   118942       yyTracePrompt,
   118943       yyTokenName[yytos->major]);
   118944   }
   118945 #endif
   118946   yymajor = yytos->major;
   118947   yy_destructor(pParser, yymajor, &yytos->minor);
   118948   pParser->yyidx--;
   118949   return yymajor;
   118950 }
   118951 
   118952 /*
   118953 ** Deallocate and destroy a parser.  Destructors are all called for
   118954 ** all stack elements before shutting the parser down.
   118955 **
   118956 ** Inputs:
   118957 ** <ul>
   118958 ** <li>  A pointer to the parser.  This should be a pointer
   118959 **       obtained from sqlite3ParserAlloc.
   118960 ** <li>  A pointer to a function used to reclaim memory obtained
   118961 **       from malloc.
   118962 ** </ul>
   118963 */
   118964 SQLITE_PRIVATE void sqlite3ParserFree(
   118965   void *p,                    /* The parser to be deleted */
   118966   void (*freeProc)(void*)     /* Function used to reclaim memory */
   118967 ){
   118968   yyParser *pParser = (yyParser*)p;
   118969   /* In SQLite, we never try to destroy a parser that was not successfully
   118970   ** created in the first place. */
   118971   if( NEVER(pParser==0) ) return;
   118972   while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
   118973 #if YYSTACKDEPTH<=0
   118974   free(pParser->yystack);
   118975 #endif
   118976   (*freeProc)((void*)pParser);
   118977 }
   118978 
   118979 /*
   118980 ** Return the peak depth of the stack for a parser.
   118981 */
   118982 #ifdef YYTRACKMAXSTACKDEPTH
   118983 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
   118984   yyParser *pParser = (yyParser*)p;
   118985   return pParser->yyidxMax;
   118986 }
   118987 #endif
   118988 
   118989 /*
   118990 ** Find the appropriate action for a parser given the terminal
   118991 ** look-ahead token iLookAhead.
   118992 **
   118993 ** If the look-ahead token is YYNOCODE, then check to see if the action is
   118994 ** independent of the look-ahead.  If it is, return the action, otherwise
   118995 ** return YY_NO_ACTION.
   118996 */
   118997 static int yy_find_shift_action(
   118998   yyParser *pParser,        /* The parser */
   118999   YYCODETYPE iLookAhead     /* The look-ahead token */
   119000 ){
   119001   int i;
   119002   int stateno = pParser->yystack[pParser->yyidx].stateno;
   119003 
   119004   if( stateno>YY_SHIFT_COUNT
   119005    || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
   119006     return yy_default[stateno];
   119007   }
   119008   assert( iLookAhead!=YYNOCODE );
   119009   i += iLookAhead;
   119010   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
   119011     if( iLookAhead>0 ){
   119012 #ifdef YYFALLBACK
   119013       YYCODETYPE iFallback;            /* Fallback token */
   119014       if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
   119015              && (iFallback = yyFallback[iLookAhead])!=0 ){
   119016 #ifndef NDEBUG
   119017         if( yyTraceFILE ){
   119018           fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
   119019              yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
   119020         }
   119021 #endif
   119022         return yy_find_shift_action(pParser, iFallback);
   119023       }
   119024 #endif
   119025 #ifdef YYWILDCARD
   119026       {
   119027         int j = i - iLookAhead + YYWILDCARD;
   119028         if(
   119029 #if YY_SHIFT_MIN+YYWILDCARD<0
   119030           j>=0 &&
   119031 #endif
   119032 #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
   119033           j<YY_ACTTAB_COUNT &&
   119034 #endif
   119035           yy_lookahead[j]==YYWILDCARD
   119036         ){
   119037 #ifndef NDEBUG
   119038           if( yyTraceFILE ){
   119039             fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
   119040                yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
   119041           }
   119042 #endif /* NDEBUG */
   119043           return yy_action[j];
   119044         }
   119045       }
   119046 #endif /* YYWILDCARD */
   119047     }
   119048     return yy_default[stateno];
   119049   }else{
   119050     return yy_action[i];
   119051   }
   119052 }
   119053 
   119054 /*
   119055 ** Find the appropriate action for a parser given the non-terminal
   119056 ** look-ahead token iLookAhead.
   119057 **
   119058 ** If the look-ahead token is YYNOCODE, then check to see if the action is
   119059 ** independent of the look-ahead.  If it is, return the action, otherwise
   119060 ** return YY_NO_ACTION.
   119061 */
   119062 static int yy_find_reduce_action(
   119063   int stateno,              /* Current state number */
   119064   YYCODETYPE iLookAhead     /* The look-ahead token */
   119065 ){
   119066   int i;
   119067 #ifdef YYERRORSYMBOL
   119068   if( stateno>YY_REDUCE_COUNT ){
   119069     return yy_default[stateno];
   119070   }
   119071 #else
   119072   assert( stateno<=YY_REDUCE_COUNT );
   119073 #endif
   119074   i = yy_reduce_ofst[stateno];
   119075   assert( i!=YY_REDUCE_USE_DFLT );
   119076   assert( iLookAhead!=YYNOCODE );
   119077   i += iLookAhead;
   119078 #ifdef YYERRORSYMBOL
   119079   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
   119080     return yy_default[stateno];
   119081   }
   119082 #else
   119083   assert( i>=0 && i<YY_ACTTAB_COUNT );
   119084   assert( yy_lookahead[i]==iLookAhead );
   119085 #endif
   119086   return yy_action[i];
   119087 }
   119088 
   119089 /*
   119090 ** The following routine is called if the stack overflows.
   119091 */
   119092 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
   119093    sqlite3ParserARG_FETCH;
   119094    yypParser->yyidx--;
   119095 #ifndef NDEBUG
   119096    if( yyTraceFILE ){
   119097      fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
   119098    }
   119099 #endif
   119100    while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
   119101    /* Here code is inserted which will execute if the parser
   119102    ** stack every overflows */
   119103 
   119104   UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
   119105   sqlite3ErrorMsg(pParse, "parser stack overflow");
   119106    sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
   119107 }
   119108 
   119109 /*
   119110 ** Perform a shift action.
   119111 */
   119112 static void yy_shift(
   119113   yyParser *yypParser,          /* The parser to be shifted */
   119114   int yyNewState,               /* The new state to shift in */
   119115   int yyMajor,                  /* The major token to shift in */
   119116   YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
   119117 ){
   119118   yyStackEntry *yytos;
   119119   yypParser->yyidx++;
   119120 #ifdef YYTRACKMAXSTACKDEPTH
   119121   if( yypParser->yyidx>yypParser->yyidxMax ){
   119122     yypParser->yyidxMax = yypParser->yyidx;
   119123   }
   119124 #endif
   119125 #if YYSTACKDEPTH>0
   119126   if( yypParser->yyidx>=YYSTACKDEPTH ){
   119127     yyStackOverflow(yypParser, yypMinor);
   119128     return;
   119129   }
   119130 #else
   119131   if( yypParser->yyidx>=yypParser->yystksz ){
   119132     yyGrowStack(yypParser);
   119133     if( yypParser->yyidx>=yypParser->yystksz ){
   119134       yyStackOverflow(yypParser, yypMinor);
   119135       return;
   119136     }
   119137   }
   119138 #endif
   119139   yytos = &yypParser->yystack[yypParser->yyidx];
   119140   yytos->stateno = (YYACTIONTYPE)yyNewState;
   119141   yytos->major = (YYCODETYPE)yyMajor;
   119142   yytos->minor = *yypMinor;
   119143 #ifndef NDEBUG
   119144   if( yyTraceFILE && yypParser->yyidx>0 ){
   119145     int i;
   119146     fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
   119147     fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
   119148     for(i=1; i<=yypParser->yyidx; i++)
   119149       fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
   119150     fprintf(yyTraceFILE,"\n");
   119151   }
   119152 #endif
   119153 }
   119154 
   119155 /* The following table contains information about every rule that
   119156 ** is used during the reduce.
   119157 */
   119158 static const struct {
   119159   YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
   119160   unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
   119161 } yyRuleInfo[] = {
   119162   { 144, 1 },
   119163   { 145, 2 },
   119164   { 145, 1 },
   119165   { 146, 1 },
   119166   { 146, 3 },
   119167   { 147, 0 },
   119168   { 147, 1 },
   119169   { 147, 3 },
   119170   { 148, 1 },
   119171   { 149, 3 },
   119172   { 151, 0 },
   119173   { 151, 1 },
   119174   { 151, 2 },
   119175   { 150, 0 },
   119176   { 150, 1 },
   119177   { 150, 1 },
   119178   { 150, 1 },
   119179   { 149, 2 },
   119180   { 149, 2 },
   119181   { 149, 2 },
   119182   { 153, 1 },
   119183   { 153, 0 },
   119184   { 149, 2 },
   119185   { 149, 3 },
   119186   { 149, 5 },
   119187   { 149, 2 },
   119188   { 154, 6 },
   119189   { 156, 1 },
   119190   { 158, 0 },
   119191   { 158, 3 },
   119192   { 157, 1 },
   119193   { 157, 0 },
   119194   { 155, 5 },
   119195   { 155, 2 },
   119196   { 162, 0 },
   119197   { 162, 2 },
   119198   { 160, 3 },
   119199   { 160, 1 },
   119200   { 164, 3 },
   119201   { 165, 1 },
   119202   { 152, 1 },
   119203   { 152, 1 },
   119204   { 152, 1 },
   119205   { 166, 0 },
   119206   { 166, 1 },
   119207   { 168, 1 },
   119208   { 168, 4 },
   119209   { 168, 6 },
   119210   { 169, 1 },
   119211   { 169, 2 },
   119212   { 170, 1 },
   119213   { 170, 1 },
   119214   { 167, 2 },
   119215   { 167, 0 },
   119216   { 173, 2 },
   119217   { 173, 2 },
   119218   { 173, 4 },
   119219   { 173, 3 },
   119220   { 173, 3 },
   119221   { 173, 2 },
   119222   { 173, 2 },
   119223   { 173, 3 },
   119224   { 173, 5 },
   119225   { 173, 2 },
   119226   { 173, 4 },
   119227   { 173, 4 },
   119228   { 173, 1 },
   119229   { 173, 2 },
   119230   { 178, 0 },
   119231   { 178, 1 },
   119232   { 180, 0 },
   119233   { 180, 2 },
   119234   { 182, 2 },
   119235   { 182, 3 },
   119236   { 182, 3 },
   119237   { 182, 3 },
   119238   { 183, 2 },
   119239   { 183, 2 },
   119240   { 183, 1 },
   119241   { 183, 1 },
   119242   { 183, 2 },
   119243   { 181, 3 },
   119244   { 181, 2 },
   119245   { 184, 0 },
   119246   { 184, 2 },
   119247   { 184, 2 },
   119248   { 161, 0 },
   119249   { 161, 2 },
   119250   { 185, 3 },
   119251   { 185, 1 },
   119252   { 186, 1 },
   119253   { 186, 0 },
   119254   { 187, 2 },
   119255   { 187, 7 },
   119256   { 187, 5 },
   119257   { 187, 5 },
   119258   { 187, 10 },
   119259   { 189, 0 },
   119260   { 189, 1 },
   119261   { 176, 0 },
   119262   { 176, 3 },
   119263   { 190, 0 },
   119264   { 190, 2 },
   119265   { 191, 1 },
   119266   { 191, 1 },
   119267   { 191, 1 },
   119268   { 149, 4 },
   119269   { 193, 2 },
   119270   { 193, 0 },
   119271   { 149, 8 },
   119272   { 149, 4 },
   119273   { 149, 1 },
   119274   { 163, 2 },
   119275   { 195, 1 },
   119276   { 195, 3 },
   119277   { 198, 1 },
   119278   { 198, 2 },
   119279   { 198, 1 },
   119280   { 196, 9 },
   119281   { 196, 1 },
   119282   { 207, 4 },
   119283   { 207, 5 },
   119284   { 199, 1 },
   119285   { 199, 1 },
   119286   { 199, 0 },
   119287   { 210, 2 },
   119288   { 210, 0 },
   119289   { 200, 3 },
   119290   { 200, 2 },
   119291   { 200, 4 },
   119292   { 211, 2 },
   119293   { 211, 1 },
   119294   { 211, 0 },
   119295   { 201, 0 },
   119296   { 201, 2 },
   119297   { 213, 2 },
   119298   { 213, 0 },
   119299   { 212, 7 },
   119300   { 212, 7 },
   119301   { 212, 7 },
   119302   { 159, 0 },
   119303   { 159, 2 },
   119304   { 194, 2 },
   119305   { 214, 1 },
   119306   { 214, 2 },
   119307   { 214, 3 },
   119308   { 214, 4 },
   119309   { 216, 2 },
   119310   { 216, 0 },
   119311   { 215, 0 },
   119312   { 215, 3 },
   119313   { 215, 2 },
   119314   { 217, 4 },
   119315   { 217, 0 },
   119316   { 205, 0 },
   119317   { 205, 3 },
   119318   { 220, 4 },
   119319   { 220, 2 },
   119320   { 177, 1 },
   119321   { 177, 1 },
   119322   { 177, 0 },
   119323   { 203, 0 },
   119324   { 203, 3 },
   119325   { 204, 0 },
   119326   { 204, 2 },
   119327   { 206, 0 },
   119328   { 206, 2 },
   119329   { 206, 4 },
   119330   { 206, 4 },
   119331   { 149, 6 },
   119332   { 202, 0 },
   119333   { 202, 2 },
   119334   { 149, 8 },
   119335   { 221, 5 },
   119336   { 221, 3 },
   119337   { 149, 6 },
   119338   { 149, 7 },
   119339   { 222, 2 },
   119340   { 222, 1 },
   119341   { 223, 0 },
   119342   { 223, 3 },
   119343   { 219, 3 },
   119344   { 219, 1 },
   119345   { 175, 1 },
   119346   { 175, 3 },
   119347   { 174, 1 },
   119348   { 175, 1 },
   119349   { 175, 1 },
   119350   { 175, 3 },
   119351   { 175, 5 },
   119352   { 174, 1 },
   119353   { 174, 1 },
   119354   { 175, 1 },
   119355   { 175, 3 },
   119356   { 175, 6 },
   119357   { 175, 5 },
   119358   { 175, 4 },
   119359   { 174, 1 },
   119360   { 175, 3 },
   119361   { 175, 3 },
   119362   { 175, 3 },
   119363   { 175, 3 },
   119364   { 175, 3 },
   119365   { 175, 3 },
   119366   { 175, 3 },
   119367   { 175, 3 },
   119368   { 224, 1 },
   119369   { 224, 2 },
   119370   { 175, 3 },
   119371   { 175, 5 },
   119372   { 175, 2 },
   119373   { 175, 3 },
   119374   { 175, 3 },
   119375   { 175, 4 },
   119376   { 175, 2 },
   119377   { 175, 2 },
   119378   { 175, 2 },
   119379   { 175, 2 },
   119380   { 225, 1 },
   119381   { 225, 2 },
   119382   { 175, 5 },
   119383   { 226, 1 },
   119384   { 226, 2 },
   119385   { 175, 5 },
   119386   { 175, 3 },
   119387   { 175, 5 },
   119388   { 175, 4 },
   119389   { 175, 4 },
   119390   { 175, 5 },
   119391   { 228, 5 },
   119392   { 228, 4 },
   119393   { 229, 2 },
   119394   { 229, 0 },
   119395   { 227, 1 },
   119396   { 227, 0 },
   119397   { 209, 1 },
   119398   { 209, 0 },
   119399   { 208, 3 },
   119400   { 208, 1 },
   119401   { 149, 12 },
   119402   { 230, 1 },
   119403   { 230, 0 },
   119404   { 179, 0 },
   119405   { 179, 3 },
   119406   { 188, 5 },
   119407   { 188, 3 },
   119408   { 231, 0 },
   119409   { 231, 2 },
   119410   { 149, 4 },
   119411   { 149, 1 },
   119412   { 149, 2 },
   119413   { 149, 3 },
   119414   { 149, 5 },
   119415   { 149, 6 },
   119416   { 149, 5 },
   119417   { 149, 6 },
   119418   { 232, 1 },
   119419   { 232, 1 },
   119420   { 232, 1 },
   119421   { 232, 1 },
   119422   { 232, 1 },
   119423   { 171, 2 },
   119424   { 171, 1 },
   119425   { 172, 2 },
   119426   { 149, 5 },
   119427   { 233, 11 },
   119428   { 235, 1 },
   119429   { 235, 1 },
   119430   { 235, 2 },
   119431   { 235, 0 },
   119432   { 236, 1 },
   119433   { 236, 1 },
   119434   { 236, 3 },
   119435   { 237, 0 },
   119436   { 237, 3 },
   119437   { 238, 0 },
   119438   { 238, 2 },
   119439   { 234, 3 },
   119440   { 234, 2 },
   119441   { 240, 1 },
   119442   { 240, 3 },
   119443   { 241, 0 },
   119444   { 241, 3 },
   119445   { 241, 2 },
   119446   { 239, 7 },
   119447   { 239, 5 },
   119448   { 239, 5 },
   119449   { 239, 1 },
   119450   { 175, 4 },
   119451   { 175, 6 },
   119452   { 192, 1 },
   119453   { 192, 1 },
   119454   { 192, 1 },
   119455   { 149, 4 },
   119456   { 149, 6 },
   119457   { 149, 3 },
   119458   { 243, 0 },
   119459   { 243, 2 },
   119460   { 242, 1 },
   119461   { 242, 0 },
   119462   { 149, 1 },
   119463   { 149, 3 },
   119464   { 149, 1 },
   119465   { 149, 3 },
   119466   { 149, 6 },
   119467   { 149, 6 },
   119468   { 244, 1 },
   119469   { 245, 0 },
   119470   { 245, 1 },
   119471   { 149, 1 },
   119472   { 149, 4 },
   119473   { 246, 8 },
   119474   { 247, 1 },
   119475   { 247, 3 },
   119476   { 248, 0 },
   119477   { 248, 2 },
   119478   { 249, 1 },
   119479   { 249, 3 },
   119480   { 250, 1 },
   119481   { 251, 0 },
   119482   { 251, 4 },
   119483   { 251, 2 },
   119484   { 197, 0 },
   119485   { 197, 2 },
   119486   { 197, 3 },
   119487   { 252, 6 },
   119488   { 252, 8 },
   119489 };
   119490 
   119491 static void yy_accept(yyParser*);  /* Forward Declaration */
   119492 
   119493 /*
   119494 ** Perform a reduce action and the shift that must immediately
   119495 ** follow the reduce.
   119496 */
   119497 static void yy_reduce(
   119498   yyParser *yypParser,         /* The parser */
   119499   int yyruleno                 /* Number of the rule by which to reduce */
   119500 ){
   119501   int yygoto;                     /* The next state */
   119502   int yyact;                      /* The next action */
   119503   YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
   119504   yyStackEntry *yymsp;            /* The top of the parser's stack */
   119505   int yysize;                     /* Amount to pop the stack */
   119506   sqlite3ParserARG_FETCH;
   119507   yymsp = &yypParser->yystack[yypParser->yyidx];
   119508 #ifndef NDEBUG
   119509   if( yyTraceFILE && yyruleno>=0
   119510         && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
   119511     fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
   119512       yyRuleName[yyruleno]);
   119513   }
   119514 #endif /* NDEBUG */
   119515 
   119516   /* Silence complaints from purify about yygotominor being uninitialized
   119517   ** in some cases when it is copied into the stack after the following
   119518   ** switch.  yygotominor is uninitialized when a rule reduces that does
   119519   ** not set the value of its left-hand side nonterminal.  Leaving the
   119520   ** value of the nonterminal uninitialized is utterly harmless as long
   119521   ** as the value is never used.  So really the only thing this code
   119522   ** accomplishes is to quieten purify.
   119523   **
   119524   ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
   119525   ** without this code, their parser segfaults.  I'm not sure what there
   119526   ** parser is doing to make this happen.  This is the second bug report
   119527   ** from wireshark this week.  Clearly they are stressing Lemon in ways
   119528   ** that it has not been previously stressed...  (SQLite ticket #2172)
   119529   */
   119530   /*memset(&yygotominor, 0, sizeof(yygotominor));*/
   119531   yygotominor = yyzerominor;
   119532 
   119533 
   119534   switch( yyruleno ){
   119535   /* Beginning here are the reduction cases.  A typical example
   119536   ** follows:
   119537   **   case 0:
   119538   **  #line <lineno> <grammarfile>
   119539   **     { ... }           // User supplied code
   119540   **  #line <lineno> <thisfile>
   119541   **     break;
   119542   */
   119543       case 5: /* explain ::= */
   119544 { sqlite3BeginParse(pParse, 0); }
   119545         break;
   119546       case 6: /* explain ::= EXPLAIN */
   119547 { sqlite3BeginParse(pParse, 1); }
   119548         break;
   119549       case 7: /* explain ::= EXPLAIN QUERY PLAN */
   119550 { sqlite3BeginParse(pParse, 2); }
   119551         break;
   119552       case 8: /* cmdx ::= cmd */
   119553 { sqlite3FinishCoding(pParse); }
   119554         break;
   119555       case 9: /* cmd ::= BEGIN transtype trans_opt */
   119556 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy328);}
   119557         break;
   119558       case 13: /* transtype ::= */
   119559 {yygotominor.yy328 = TK_DEFERRED;}
   119560         break;
   119561       case 14: /* transtype ::= DEFERRED */
   119562       case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
   119563       case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
   119564       case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
   119565       case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
   119566 {yygotominor.yy328 = yymsp[0].major;}
   119567         break;
   119568       case 17: /* cmd ::= COMMIT trans_opt */
   119569       case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
   119570 {sqlite3CommitTransaction(pParse);}
   119571         break;
   119572       case 19: /* cmd ::= ROLLBACK trans_opt */
   119573 {sqlite3RollbackTransaction(pParse);}
   119574         break;
   119575       case 22: /* cmd ::= SAVEPOINT nm */
   119576 {
   119577   sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
   119578 }
   119579         break;
   119580       case 23: /* cmd ::= RELEASE savepoint_opt nm */
   119581 {
   119582   sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
   119583 }
   119584         break;
   119585       case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
   119586 {
   119587   sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
   119588 }
   119589         break;
   119590       case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
   119591 {
   119592    sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy328,0,0,yymsp[-2].minor.yy328);
   119593 }
   119594         break;
   119595       case 27: /* createkw ::= CREATE */
   119596 {
   119597   pParse->db->lookaside.bEnabled = 0;
   119598   yygotominor.yy0 = yymsp[0].minor.yy0;
   119599 }
   119600         break;
   119601       case 28: /* ifnotexists ::= */
   119602       case 31: /* temp ::= */ yytestcase(yyruleno==31);
   119603       case 68: /* autoinc ::= */ yytestcase(yyruleno==68);
   119604       case 81: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==81);
   119605       case 83: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==83);
   119606       case 85: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==85);
   119607       case 97: /* defer_subclause_opt ::= */ yytestcase(yyruleno==97);
   119608       case 108: /* ifexists ::= */ yytestcase(yyruleno==108);
   119609       case 218: /* between_op ::= BETWEEN */ yytestcase(yyruleno==218);
   119610       case 221: /* in_op ::= IN */ yytestcase(yyruleno==221);
   119611 {yygotominor.yy328 = 0;}
   119612         break;
   119613       case 29: /* ifnotexists ::= IF NOT EXISTS */
   119614       case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
   119615       case 69: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==69);
   119616       case 84: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==84);
   119617       case 107: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==107);
   119618       case 219: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==219);
   119619       case 222: /* in_op ::= NOT IN */ yytestcase(yyruleno==222);
   119620 {yygotominor.yy328 = 1;}
   119621         break;
   119622       case 32: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
   119623 {
   119624   sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy186,0);
   119625 }
   119626         break;
   119627       case 33: /* create_table_args ::= AS select */
   119628 {
   119629   sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy3);
   119630   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
   119631 }
   119632         break;
   119633       case 34: /* table_options ::= */
   119634 {yygotominor.yy186 = 0;}
   119635         break;
   119636       case 35: /* table_options ::= WITHOUT nm */
   119637 {
   119638   if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
   119639     yygotominor.yy186 = TF_WithoutRowid;
   119640   }else{
   119641     yygotominor.yy186 = 0;
   119642     sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
   119643   }
   119644 }
   119645         break;
   119646       case 38: /* column ::= columnid type carglist */
   119647 {
   119648   yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
   119649   yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
   119650 }
   119651         break;
   119652       case 39: /* columnid ::= nm */
   119653 {
   119654   sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
   119655   yygotominor.yy0 = yymsp[0].minor.yy0;
   119656   pParse->constraintName.n = 0;
   119657 }
   119658         break;
   119659       case 40: /* nm ::= ID|INDEXED */
   119660       case 41: /* nm ::= STRING */ yytestcase(yyruleno==41);
   119661       case 42: /* nm ::= JOIN_KW */ yytestcase(yyruleno==42);
   119662       case 45: /* typetoken ::= typename */ yytestcase(yyruleno==45);
   119663       case 48: /* typename ::= ID|STRING */ yytestcase(yyruleno==48);
   119664       case 130: /* as ::= AS nm */ yytestcase(yyruleno==130);
   119665       case 131: /* as ::= ID|STRING */ yytestcase(yyruleno==131);
   119666       case 141: /* dbnm ::= DOT nm */ yytestcase(yyruleno==141);
   119667       case 150: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==150);
   119668       case 247: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==247);
   119669       case 256: /* nmnum ::= plus_num */ yytestcase(yyruleno==256);
   119670       case 257: /* nmnum ::= nm */ yytestcase(yyruleno==257);
   119671       case 258: /* nmnum ::= ON */ yytestcase(yyruleno==258);
   119672       case 259: /* nmnum ::= DELETE */ yytestcase(yyruleno==259);
   119673       case 260: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==260);
   119674       case 261: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==261);
   119675       case 262: /* plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==262);
   119676       case 263: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==263);
   119677       case 279: /* trnm ::= nm */ yytestcase(yyruleno==279);
   119678 {yygotominor.yy0 = yymsp[0].minor.yy0;}
   119679         break;
   119680       case 44: /* type ::= typetoken */
   119681 {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
   119682         break;
   119683       case 46: /* typetoken ::= typename LP signed RP */
   119684 {
   119685   yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
   119686   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
   119687 }
   119688         break;
   119689       case 47: /* typetoken ::= typename LP signed COMMA signed RP */
   119690 {
   119691   yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
   119692   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
   119693 }
   119694         break;
   119695       case 49: /* typename ::= typename ID|STRING */
   119696 {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);}
   119697         break;
   119698       case 54: /* ccons ::= CONSTRAINT nm */
   119699       case 92: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==92);
   119700 {pParse->constraintName = yymsp[0].minor.yy0;}
   119701         break;
   119702       case 55: /* ccons ::= DEFAULT term */
   119703       case 57: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==57);
   119704 {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy346);}
   119705         break;
   119706       case 56: /* ccons ::= DEFAULT LP expr RP */
   119707 {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy346);}
   119708         break;
   119709       case 58: /* ccons ::= DEFAULT MINUS term */
   119710 {
   119711   ExprSpan v;
   119712   v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy346.pExpr, 0, 0);
   119713   v.zStart = yymsp[-1].minor.yy0.z;
   119714   v.zEnd = yymsp[0].minor.yy346.zEnd;
   119715   sqlite3AddDefaultValue(pParse,&v);
   119716 }
   119717         break;
   119718       case 59: /* ccons ::= DEFAULT ID|INDEXED */
   119719 {
   119720   ExprSpan v;
   119721   spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
   119722   sqlite3AddDefaultValue(pParse,&v);
   119723 }
   119724         break;
   119725       case 61: /* ccons ::= NOT NULL onconf */
   119726 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy328);}
   119727         break;
   119728       case 62: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
   119729 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy328,yymsp[0].minor.yy328,yymsp[-2].minor.yy328);}
   119730         break;
   119731       case 63: /* ccons ::= UNIQUE onconf */
   119732 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy328,0,0,0,0);}
   119733         break;
   119734       case 64: /* ccons ::= CHECK LP expr RP */
   119735 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy346.pExpr);}
   119736         break;
   119737       case 65: /* ccons ::= REFERENCES nm idxlist_opt refargs */
   119738 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy14,yymsp[0].minor.yy328);}
   119739         break;
   119740       case 66: /* ccons ::= defer_subclause */
   119741 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy328);}
   119742         break;
   119743       case 67: /* ccons ::= COLLATE ID|STRING */
   119744 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
   119745         break;
   119746       case 70: /* refargs ::= */
   119747 { yygotominor.yy328 = OE_None*0x0101; /* EV: R-19803-45884 */}
   119748         break;
   119749       case 71: /* refargs ::= refargs refarg */
   119750 { yygotominor.yy328 = (yymsp[-1].minor.yy328 & ~yymsp[0].minor.yy429.mask) | yymsp[0].minor.yy429.value; }
   119751         break;
   119752       case 72: /* refarg ::= MATCH nm */
   119753       case 73: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==73);
   119754 { yygotominor.yy429.value = 0;     yygotominor.yy429.mask = 0x000000; }
   119755         break;
   119756       case 74: /* refarg ::= ON DELETE refact */
   119757 { yygotominor.yy429.value = yymsp[0].minor.yy328;     yygotominor.yy429.mask = 0x0000ff; }
   119758         break;
   119759       case 75: /* refarg ::= ON UPDATE refact */
   119760 { yygotominor.yy429.value = yymsp[0].minor.yy328<<8;  yygotominor.yy429.mask = 0x00ff00; }
   119761         break;
   119762       case 76: /* refact ::= SET NULL */
   119763 { yygotominor.yy328 = OE_SetNull;  /* EV: R-33326-45252 */}
   119764         break;
   119765       case 77: /* refact ::= SET DEFAULT */
   119766 { yygotominor.yy328 = OE_SetDflt;  /* EV: R-33326-45252 */}
   119767         break;
   119768       case 78: /* refact ::= CASCADE */
   119769 { yygotominor.yy328 = OE_Cascade;  /* EV: R-33326-45252 */}
   119770         break;
   119771       case 79: /* refact ::= RESTRICT */
   119772 { yygotominor.yy328 = OE_Restrict; /* EV: R-33326-45252 */}
   119773         break;
   119774       case 80: /* refact ::= NO ACTION */
   119775 { yygotominor.yy328 = OE_None;     /* EV: R-33326-45252 */}
   119776         break;
   119777       case 82: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
   119778       case 98: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==98);
   119779       case 100: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==100);
   119780       case 103: /* resolvetype ::= raisetype */ yytestcase(yyruleno==103);
   119781 {yygotominor.yy328 = yymsp[0].minor.yy328;}
   119782         break;
   119783       case 86: /* conslist_opt ::= */
   119784 {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
   119785         break;
   119786       case 87: /* conslist_opt ::= COMMA conslist */
   119787 {yygotominor.yy0 = yymsp[-1].minor.yy0;}
   119788         break;
   119789       case 90: /* tconscomma ::= COMMA */
   119790 {pParse->constraintName.n = 0;}
   119791         break;
   119792       case 93: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
   119793 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy14,yymsp[0].minor.yy328,yymsp[-2].minor.yy328,0);}
   119794         break;
   119795       case 94: /* tcons ::= UNIQUE LP idxlist RP onconf */
   119796 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy14,yymsp[0].minor.yy328,0,0,0,0);}
   119797         break;
   119798       case 95: /* tcons ::= CHECK LP expr RP onconf */
   119799 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy346.pExpr);}
   119800         break;
   119801       case 96: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
   119802 {
   119803     sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy14, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy14, yymsp[-1].minor.yy328);
   119804     sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy328);
   119805 }
   119806         break;
   119807       case 99: /* onconf ::= */
   119808 {yygotominor.yy328 = OE_Default;}
   119809         break;
   119810       case 101: /* orconf ::= */
   119811 {yygotominor.yy186 = OE_Default;}
   119812         break;
   119813       case 102: /* orconf ::= OR resolvetype */
   119814 {yygotominor.yy186 = (u8)yymsp[0].minor.yy328;}
   119815         break;
   119816       case 104: /* resolvetype ::= IGNORE */
   119817 {yygotominor.yy328 = OE_Ignore;}
   119818         break;
   119819       case 105: /* resolvetype ::= REPLACE */
   119820 {yygotominor.yy328 = OE_Replace;}
   119821         break;
   119822       case 106: /* cmd ::= DROP TABLE ifexists fullname */
   119823 {
   119824   sqlite3DropTable(pParse, yymsp[0].minor.yy65, 0, yymsp[-1].minor.yy328);
   119825 }
   119826         break;
   119827       case 109: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
   119828 {
   119829   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);
   119830 }
   119831         break;
   119832       case 110: /* cmd ::= DROP VIEW ifexists fullname */
   119833 {
   119834   sqlite3DropTable(pParse, yymsp[0].minor.yy65, 1, yymsp[-1].minor.yy328);
   119835 }
   119836         break;
   119837       case 111: /* cmd ::= select */
   119838 {
   119839   SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
   119840   sqlite3Select(pParse, yymsp[0].minor.yy3, &dest);
   119841   sqlite3ExplainBegin(pParse->pVdbe);
   119842   sqlite3ExplainSelect(pParse->pVdbe, yymsp[0].minor.yy3);
   119843   sqlite3ExplainFinish(pParse->pVdbe);
   119844   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
   119845 }
   119846         break;
   119847       case 112: /* select ::= with selectnowith */
   119848 {
   119849   Select *p = yymsp[0].minor.yy3, *pNext, *pLoop;
   119850   if( p ){
   119851     int cnt = 0, mxSelect;
   119852     p->pWith = yymsp[-1].minor.yy59;
   119853     if( p->pPrior ){
   119854       pNext = 0;
   119855       for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
   119856         pLoop->pNext = pNext;
   119857         pLoop->selFlags |= SF_Compound;
   119858       }
   119859       mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
   119860       if( mxSelect && cnt>mxSelect ){
   119861         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
   119862       }
   119863     }
   119864   }else{
   119865     sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy59);
   119866   }
   119867   yygotominor.yy3 = p;
   119868 }
   119869         break;
   119870       case 113: /* selectnowith ::= oneselect */
   119871       case 119: /* oneselect ::= values */ yytestcase(yyruleno==119);
   119872 {yygotominor.yy3 = yymsp[0].minor.yy3;}
   119873         break;
   119874       case 114: /* selectnowith ::= selectnowith multiselect_op oneselect */
   119875 {
   119876   Select *pRhs = yymsp[0].minor.yy3;
   119877   if( pRhs && pRhs->pPrior ){
   119878     SrcList *pFrom;
   119879     Token x;
   119880     x.n = 0;
   119881     pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
   119882     pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0,0);
   119883   }
   119884   if( pRhs ){
   119885     pRhs->op = (u8)yymsp[-1].minor.yy328;
   119886     pRhs->pPrior = yymsp[-2].minor.yy3;
   119887     if( yymsp[-1].minor.yy328!=TK_ALL ) pParse->hasCompound = 1;
   119888   }else{
   119889     sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy3);
   119890   }
   119891   yygotominor.yy3 = pRhs;
   119892 }
   119893         break;
   119894       case 116: /* multiselect_op ::= UNION ALL */
   119895 {yygotominor.yy328 = TK_ALL;}
   119896         break;
   119897       case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
   119898 {
   119899   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);
   119900 }
   119901         break;
   119902       case 120: /* values ::= VALUES LP nexprlist RP */
   119903 {
   119904   yygotominor.yy3 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy14,0,0,0,0,0,SF_Values,0,0);
   119905 }
   119906         break;
   119907       case 121: /* values ::= values COMMA LP exprlist RP */
   119908 {
   119909   Select *pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy14,0,0,0,0,0,SF_Values,0,0);
   119910   if( pRight ){
   119911     pRight->op = TK_ALL;
   119912     pRight->pPrior = yymsp[-4].minor.yy3;
   119913     yygotominor.yy3 = pRight;
   119914   }else{
   119915     yygotominor.yy3 = yymsp[-4].minor.yy3;
   119916   }
   119917 }
   119918         break;
   119919       case 122: /* distinct ::= DISTINCT */
   119920 {yygotominor.yy381 = SF_Distinct;}
   119921         break;
   119922       case 123: /* distinct ::= ALL */
   119923       case 124: /* distinct ::= */ yytestcase(yyruleno==124);
   119924 {yygotominor.yy381 = 0;}
   119925         break;
   119926       case 125: /* sclp ::= selcollist COMMA */
   119927       case 243: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==243);
   119928 {yygotominor.yy14 = yymsp[-1].minor.yy14;}
   119929         break;
   119930       case 126: /* sclp ::= */
   119931       case 154: /* orderby_opt ::= */ yytestcase(yyruleno==154);
   119932       case 161: /* groupby_opt ::= */ yytestcase(yyruleno==161);
   119933       case 236: /* exprlist ::= */ yytestcase(yyruleno==236);
   119934       case 242: /* idxlist_opt ::= */ yytestcase(yyruleno==242);
   119935 {yygotominor.yy14 = 0;}
   119936         break;
   119937       case 127: /* selcollist ::= sclp expr as */
   119938 {
   119939    yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy14, yymsp[-1].minor.yy346.pExpr);
   119940    if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[0].minor.yy0, 1);
   119941    sqlite3ExprListSetSpan(pParse,yygotominor.yy14,&yymsp[-1].minor.yy346);
   119942 }
   119943         break;
   119944       case 128: /* selcollist ::= sclp STAR */
   119945 {
   119946   Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
   119947   yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy14, p);
   119948 }
   119949         break;
   119950       case 129: /* selcollist ::= sclp nm DOT STAR */
   119951 {
   119952   Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
   119953   Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
   119954   Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
   119955   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14, pDot);
   119956 }
   119957         break;
   119958       case 132: /* as ::= */
   119959 {yygotominor.yy0.n = 0;}
   119960         break;
   119961       case 133: /* from ::= */
   119962 {yygotominor.yy65 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy65));}
   119963         break;
   119964       case 134: /* from ::= FROM seltablist */
   119965 {
   119966   yygotominor.yy65 = yymsp[0].minor.yy65;
   119967   sqlite3SrcListShiftJoinType(yygotominor.yy65);
   119968 }
   119969         break;
   119970       case 135: /* stl_prefix ::= seltablist joinop */
   119971 {
   119972    yygotominor.yy65 = yymsp[-1].minor.yy65;
   119973    if( ALWAYS(yygotominor.yy65 && yygotominor.yy65->nSrc>0) ) yygotominor.yy65->a[yygotominor.yy65->nSrc-1].jointype = (u8)yymsp[0].minor.yy328;
   119974 }
   119975         break;
   119976       case 136: /* stl_prefix ::= */
   119977 {yygotominor.yy65 = 0;}
   119978         break;
   119979       case 137: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
   119980 {
   119981   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);
   119982   sqlite3SrcListIndexedBy(pParse, yygotominor.yy65, &yymsp[-2].minor.yy0);
   119983 }
   119984         break;
   119985       case 138: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
   119986 {
   119987     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);
   119988   }
   119989         break;
   119990       case 139: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
   119991 {
   119992     if( yymsp[-6].minor.yy65==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy132==0 && yymsp[0].minor.yy408==0 ){
   119993       yygotominor.yy65 = yymsp[-4].minor.yy65;
   119994     }else if( yymsp[-4].minor.yy65->nSrc==1 ){
   119995       yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
   119996       if( yygotominor.yy65 ){
   119997         struct SrcList_item *pNew = &yygotominor.yy65->a[yygotominor.yy65->nSrc-1];
   119998         struct SrcList_item *pOld = yymsp[-4].minor.yy65->a;
   119999         pNew->zName = pOld->zName;
   120000         pNew->zDatabase = pOld->zDatabase;
   120001         pNew->pSelect = pOld->pSelect;
   120002         pOld->zName = pOld->zDatabase = 0;
   120003         pOld->pSelect = 0;
   120004       }
   120005       sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy65);
   120006     }else{
   120007       Select *pSubquery;
   120008       sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy65);
   120009       pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy65,0,0,0,0,SF_NestedFrom,0,0);
   120010       yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
   120011     }
   120012   }
   120013         break;
   120014       case 140: /* dbnm ::= */
   120015       case 149: /* indexed_opt ::= */ yytestcase(yyruleno==149);
   120016 {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
   120017         break;
   120018       case 142: /* fullname ::= nm dbnm */
   120019 {yygotominor.yy65 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
   120020         break;
   120021       case 143: /* joinop ::= COMMA|JOIN */
   120022 { yygotominor.yy328 = JT_INNER; }
   120023         break;
   120024       case 144: /* joinop ::= JOIN_KW JOIN */
   120025 { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
   120026         break;
   120027       case 145: /* joinop ::= JOIN_KW nm JOIN */
   120028 { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
   120029         break;
   120030       case 146: /* joinop ::= JOIN_KW nm nm JOIN */
   120031 { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
   120032         break;
   120033       case 147: /* on_opt ::= ON expr */
   120034       case 164: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==164);
   120035       case 171: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==171);
   120036       case 231: /* case_else ::= ELSE expr */ yytestcase(yyruleno==231);
   120037       case 233: /* case_operand ::= expr */ yytestcase(yyruleno==233);
   120038 {yygotominor.yy132 = yymsp[0].minor.yy346.pExpr;}
   120039         break;
   120040       case 148: /* on_opt ::= */
   120041       case 163: /* having_opt ::= */ yytestcase(yyruleno==163);
   120042       case 170: /* where_opt ::= */ yytestcase(yyruleno==170);
   120043       case 232: /* case_else ::= */ yytestcase(yyruleno==232);
   120044       case 234: /* case_operand ::= */ yytestcase(yyruleno==234);
   120045 {yygotominor.yy132 = 0;}
   120046         break;
   120047       case 151: /* indexed_opt ::= NOT INDEXED */
   120048 {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
   120049         break;
   120050       case 152: /* using_opt ::= USING LP idlist RP */
   120051       case 180: /* inscollist_opt ::= LP idlist RP */ yytestcase(yyruleno==180);
   120052 {yygotominor.yy408 = yymsp[-1].minor.yy408;}
   120053         break;
   120054       case 153: /* using_opt ::= */
   120055       case 179: /* inscollist_opt ::= */ yytestcase(yyruleno==179);
   120056 {yygotominor.yy408 = 0;}
   120057         break;
   120058       case 155: /* orderby_opt ::= ORDER BY sortlist */
   120059       case 162: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==162);
   120060       case 235: /* exprlist ::= nexprlist */ yytestcase(yyruleno==235);
   120061 {yygotominor.yy14 = yymsp[0].minor.yy14;}
   120062         break;
   120063       case 156: /* sortlist ::= sortlist COMMA expr sortorder */
   120064 {
   120065   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14,yymsp[-1].minor.yy346.pExpr);
   120066   if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
   120067 }
   120068         break;
   120069       case 157: /* sortlist ::= expr sortorder */
   120070 {
   120071   yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy346.pExpr);
   120072   if( yygotominor.yy14 && ALWAYS(yygotominor.yy14->a) ) yygotominor.yy14->a[0].sortOrder = (u8)yymsp[0].minor.yy328;
   120073 }
   120074         break;
   120075       case 158: /* sortorder ::= ASC */
   120076       case 160: /* sortorder ::= */ yytestcase(yyruleno==160);
   120077 {yygotominor.yy328 = SQLITE_SO_ASC;}
   120078         break;
   120079       case 159: /* sortorder ::= DESC */
   120080 {yygotominor.yy328 = SQLITE_SO_DESC;}
   120081         break;
   120082       case 165: /* limit_opt ::= */
   120083 {yygotominor.yy476.pLimit = 0; yygotominor.yy476.pOffset = 0;}
   120084         break;
   120085       case 166: /* limit_opt ::= LIMIT expr */
   120086 {yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr; yygotominor.yy476.pOffset = 0;}
   120087         break;
   120088       case 167: /* limit_opt ::= LIMIT expr OFFSET expr */
   120089 {yygotominor.yy476.pLimit = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pOffset = yymsp[0].minor.yy346.pExpr;}
   120090         break;
   120091       case 168: /* limit_opt ::= LIMIT expr COMMA expr */
   120092 {yygotominor.yy476.pOffset = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr;}
   120093         break;
   120094       case 169: /* cmd ::= with DELETE FROM fullname indexed_opt where_opt */
   120095 {
   120096   sqlite3WithPush(pParse, yymsp[-5].minor.yy59, 1);
   120097   sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy65, &yymsp[-1].minor.yy0);
   120098   sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy65,yymsp[0].minor.yy132);
   120099 }
   120100         break;
   120101       case 172: /* cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt */
   120102 {
   120103   sqlite3WithPush(pParse, yymsp[-7].minor.yy59, 1);
   120104   sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy65, &yymsp[-3].minor.yy0);
   120105   sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy14,"set list");
   120106   sqlite3Update(pParse,yymsp[-4].minor.yy65,yymsp[-1].minor.yy14,yymsp[0].minor.yy132,yymsp[-5].minor.yy186);
   120107 }
   120108         break;
   120109       case 173: /* setlist ::= setlist COMMA nm EQ expr */
   120110 {
   120111   yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy14, yymsp[0].minor.yy346.pExpr);
   120112   sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
   120113 }
   120114         break;
   120115       case 174: /* setlist ::= nm EQ expr */
   120116 {
   120117   yygotominor.yy14 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy346.pExpr);
   120118   sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
   120119 }
   120120         break;
   120121       case 175: /* cmd ::= with insert_cmd INTO fullname inscollist_opt select */
   120122 {
   120123   sqlite3WithPush(pParse, yymsp[-5].minor.yy59, 1);
   120124   sqlite3Insert(pParse, yymsp[-2].minor.yy65, yymsp[0].minor.yy3, yymsp[-1].minor.yy408, yymsp[-4].minor.yy186);
   120125 }
   120126         break;
   120127       case 176: /* cmd ::= with insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
   120128 {
   120129   sqlite3WithPush(pParse, yymsp[-6].minor.yy59, 1);
   120130   sqlite3Insert(pParse, yymsp[-3].minor.yy65, 0, yymsp[-2].minor.yy408, yymsp[-5].minor.yy186);
   120131 }
   120132         break;
   120133       case 177: /* insert_cmd ::= INSERT orconf */
   120134 {yygotominor.yy186 = yymsp[0].minor.yy186;}
   120135         break;
   120136       case 178: /* insert_cmd ::= REPLACE */
   120137 {yygotominor.yy186 = OE_Replace;}
   120138         break;
   120139       case 181: /* idlist ::= idlist COMMA nm */
   120140 {yygotominor.yy408 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy408,&yymsp[0].minor.yy0);}
   120141         break;
   120142       case 182: /* idlist ::= nm */
   120143 {yygotominor.yy408 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
   120144         break;
   120145       case 183: /* expr ::= term */
   120146 {yygotominor.yy346 = yymsp[0].minor.yy346;}
   120147         break;
   120148       case 184: /* expr ::= LP expr RP */
   120149 {yygotominor.yy346.pExpr = yymsp[-1].minor.yy346.pExpr; spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
   120150         break;
   120151       case 185: /* term ::= NULL */
   120152       case 190: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==190);
   120153       case 191: /* term ::= STRING */ yytestcase(yyruleno==191);
   120154 {spanExpr(&yygotominor.yy346, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
   120155         break;
   120156       case 186: /* expr ::= ID|INDEXED */
   120157       case 187: /* expr ::= JOIN_KW */ yytestcase(yyruleno==187);
   120158 {spanExpr(&yygotominor.yy346, pParse, TK_ID, &yymsp[0].minor.yy0);}
   120159         break;
   120160       case 188: /* expr ::= nm DOT nm */
   120161 {
   120162   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
   120163   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
   120164   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
   120165   spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
   120166 }
   120167         break;
   120168       case 189: /* expr ::= nm DOT nm DOT nm */
   120169 {
   120170   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
   120171   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
   120172   Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
   120173   Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
   120174   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
   120175   spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
   120176 }
   120177         break;
   120178       case 192: /* expr ::= VARIABLE */
   120179 {
   120180   if( yymsp[0].minor.yy0.n>=2 && yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1]) ){
   120181     /* When doing a nested parse, one can include terms in an expression
   120182     ** that look like this:   #1 #2 ...  These terms refer to registers
   120183     ** in the virtual machine.  #N is the N-th register. */
   120184     if( pParse->nested==0 ){
   120185       sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
   120186       yygotominor.yy346.pExpr = 0;
   120187     }else{
   120188       yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
   120189       if( yygotominor.yy346.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy346.pExpr->iTable);
   120190     }
   120191   }else{
   120192     spanExpr(&yygotominor.yy346, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
   120193     sqlite3ExprAssignVarNumber(pParse, yygotominor.yy346.pExpr);
   120194   }
   120195   spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
   120196 }
   120197         break;
   120198       case 193: /* expr ::= expr COLLATE ID|STRING */
   120199 {
   120200   yygotominor.yy346.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy346.pExpr, &yymsp[0].minor.yy0);
   120201   yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
   120202   yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   120203 }
   120204         break;
   120205       case 194: /* expr ::= CAST LP expr AS typetoken RP */
   120206 {
   120207   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy346.pExpr, 0, &yymsp[-1].minor.yy0);
   120208   spanSet(&yygotominor.yy346,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
   120209 }
   120210         break;
   120211       case 195: /* expr ::= ID|INDEXED LP distinct exprlist RP */
   120212 {
   120213   if( yymsp[-1].minor.yy14 && yymsp[-1].minor.yy14->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
   120214     sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
   120215   }
   120216   yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy14, &yymsp[-4].minor.yy0);
   120217   spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
   120218   if( yymsp[-2].minor.yy381 && yygotominor.yy346.pExpr ){
   120219     yygotominor.yy346.pExpr->flags |= EP_Distinct;
   120220   }
   120221 }
   120222         break;
   120223       case 196: /* expr ::= ID|INDEXED LP STAR RP */
   120224 {
   120225   yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
   120226   spanSet(&yygotominor.yy346,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
   120227 }
   120228         break;
   120229       case 197: /* term ::= CTIME_KW */
   120230 {
   120231   yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0);
   120232   spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
   120233 }
   120234         break;
   120235       case 198: /* expr ::= expr AND expr */
   120236       case 199: /* expr ::= expr OR expr */ yytestcase(yyruleno==199);
   120237       case 200: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==200);
   120238       case 201: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==201);
   120239       case 202: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==202);
   120240       case 203: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==203);
   120241       case 204: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==204);
   120242       case 205: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==205);
   120243 {spanBinaryExpr(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);}
   120244         break;
   120245       case 206: /* likeop ::= LIKE_KW|MATCH */
   120246 {yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.bNot = 0;}
   120247         break;
   120248       case 207: /* likeop ::= NOT LIKE_KW|MATCH */
   120249 {yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.bNot = 1;}
   120250         break;
   120251       case 208: /* expr ::= expr likeop expr */
   120252 {
   120253   ExprList *pList;
   120254   pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy346.pExpr);
   120255   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy346.pExpr);
   120256   yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy96.eOperator);
   120257   if( yymsp[-1].minor.yy96.bNot ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
   120258   yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
   120259   yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
   120260   if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
   120261 }
   120262         break;
   120263       case 209: /* expr ::= expr likeop expr ESCAPE expr */
   120264 {
   120265   ExprList *pList;
   120266   pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
   120267   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy346.pExpr);
   120268   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
   120269   yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy96.eOperator);
   120270   if( yymsp[-3].minor.yy96.bNot ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
   120271   yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
   120272   yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
   120273   if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
   120274 }
   120275         break;
   120276       case 210: /* expr ::= expr ISNULL|NOTNULL */
   120277 {spanUnaryPostfix(&yygotominor.yy346,pParse,yymsp[0].major,&yymsp[-1].minor.yy346,&yymsp[0].minor.yy0);}
   120278         break;
   120279       case 211: /* expr ::= expr NOT NULL */
   120280 {spanUnaryPostfix(&yygotominor.yy346,pParse,TK_NOTNULL,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy0);}
   120281         break;
   120282       case 212: /* expr ::= expr IS expr */
   120283 {
   120284   spanBinaryExpr(&yygotominor.yy346,pParse,TK_IS,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);
   120285   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_ISNULL);
   120286 }
   120287         break;
   120288       case 213: /* expr ::= expr IS NOT expr */
   120289 {
   120290   spanBinaryExpr(&yygotominor.yy346,pParse,TK_ISNOT,&yymsp[-3].minor.yy346,&yymsp[0].minor.yy346);
   120291   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_NOTNULL);
   120292 }
   120293         break;
   120294       case 214: /* expr ::= NOT expr */
   120295       case 215: /* expr ::= BITNOT expr */ yytestcase(yyruleno==215);
   120296 {spanUnaryPrefix(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
   120297         break;
   120298       case 216: /* expr ::= MINUS expr */
   120299 {spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UMINUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
   120300         break;
   120301       case 217: /* expr ::= PLUS expr */
   120302 {spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UPLUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
   120303         break;
   120304       case 220: /* expr ::= expr between_op expr AND expr */
   120305 {
   120306   ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
   120307   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
   120308   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy346.pExpr, 0, 0);
   120309   if( yygotominor.yy346.pExpr ){
   120310     yygotominor.yy346.pExpr->x.pList = pList;
   120311   }else{
   120312     sqlite3ExprListDelete(pParse->db, pList);
   120313   }
   120314   if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
   120315   yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
   120316   yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
   120317 }
   120318         break;
   120319       case 223: /* expr ::= expr in_op LP exprlist RP */
   120320 {
   120321     if( yymsp[-1].minor.yy14==0 ){
   120322       /* Expressions of the form
   120323       **
   120324       **      expr1 IN ()
   120325       **      expr1 NOT IN ()
   120326       **
   120327       ** simplify to constants 0 (false) and 1 (true), respectively,
   120328       ** regardless of the value of expr1.
   120329       */
   120330       yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy328]);
   120331       sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy346.pExpr);
   120332     }else if( yymsp[-1].minor.yy14->nExpr==1 ){
   120333       /* Expressions of the form:
   120334       **
   120335       **      expr1 IN (?1)
   120336       **      expr1 NOT IN (?2)
   120337       **
   120338       ** with exactly one value on the RHS can be simplified to something
   120339       ** like this:
   120340       **
   120341       **      expr1 == ?1
   120342       **      expr1 <> ?2
   120343       **
   120344       ** But, the RHS of the == or <> is marked with the EP_Generic flag
   120345       ** so that it may not contribute to the computation of comparison
   120346       ** affinity or the collating sequence to use for comparison.  Otherwise,
   120347       ** the semantics would be subtly different from IN or NOT IN.
   120348       */
   120349       Expr *pRHS = yymsp[-1].minor.yy14->a[0].pExpr;
   120350       yymsp[-1].minor.yy14->a[0].pExpr = 0;
   120351       sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
   120352       /* pRHS cannot be NULL because a malloc error would have been detected
   120353       ** before now and control would have never reached this point */
   120354       if( ALWAYS(pRHS) ){
   120355         pRHS->flags &= ~EP_Collate;
   120356         pRHS->flags |= EP_Generic;
   120357       }
   120358       yygotominor.yy346.pExpr = sqlite3PExpr(pParse, yymsp[-3].minor.yy328 ? TK_NE : TK_EQ, yymsp[-4].minor.yy346.pExpr, pRHS, 0);
   120359     }else{
   120360       yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
   120361       if( yygotominor.yy346.pExpr ){
   120362         yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy14;
   120363         sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
   120364       }else{
   120365         sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
   120366       }
   120367       if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
   120368     }
   120369     yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
   120370     yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   120371   }
   120372         break;
   120373       case 224: /* expr ::= LP select RP */
   120374 {
   120375     yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
   120376     if( yygotominor.yy346.pExpr ){
   120377       yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
   120378       ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
   120379       sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
   120380     }else{
   120381       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
   120382     }
   120383     yygotominor.yy346.zStart = yymsp[-2].minor.yy0.z;
   120384     yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   120385   }
   120386         break;
   120387       case 225: /* expr ::= expr in_op LP select RP */
   120388 {
   120389     yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
   120390     if( yygotominor.yy346.pExpr ){
   120391       yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
   120392       ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
   120393       sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
   120394     }else{
   120395       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
   120396     }
   120397     if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
   120398     yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
   120399     yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   120400   }
   120401         break;
   120402       case 226: /* expr ::= expr in_op nm dbnm */
   120403 {
   120404     SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
   120405     yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy346.pExpr, 0, 0);
   120406     if( yygotominor.yy346.pExpr ){
   120407       yygotominor.yy346.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
   120408       ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
   120409       sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
   120410     }else{
   120411       sqlite3SrcListDelete(pParse->db, pSrc);
   120412     }
   120413     if( yymsp[-2].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
   120414     yygotominor.yy346.zStart = yymsp[-3].minor.yy346.zStart;
   120415     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];
   120416   }
   120417         break;
   120418       case 227: /* expr ::= EXISTS LP select RP */
   120419 {
   120420     Expr *p = yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
   120421     if( p ){
   120422       p->x.pSelect = yymsp[-1].minor.yy3;
   120423       ExprSetProperty(p, EP_xIsSelect);
   120424       sqlite3ExprSetHeight(pParse, p);
   120425     }else{
   120426       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
   120427     }
   120428     yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
   120429     yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   120430   }
   120431         break;
   120432       case 228: /* expr ::= CASE case_operand case_exprlist case_else END */
   120433 {
   120434   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy132, 0, 0);
   120435   if( yygotominor.yy346.pExpr ){
   120436     yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy132 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[-1].minor.yy132) : yymsp[-2].minor.yy14;
   120437     sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
   120438   }else{
   120439     sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy14);
   120440     sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy132);
   120441   }
   120442   yygotominor.yy346.zStart = yymsp[-4].minor.yy0.z;
   120443   yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   120444 }
   120445         break;
   120446       case 229: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
   120447 {
   120448   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, yymsp[-2].minor.yy346.pExpr);
   120449   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
   120450 }
   120451         break;
   120452       case 230: /* case_exprlist ::= WHEN expr THEN expr */
   120453 {
   120454   yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
   120455   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
   120456 }
   120457         break;
   120458       case 237: /* nexprlist ::= nexprlist COMMA expr */
   120459 {yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[0].minor.yy346.pExpr);}
   120460         break;
   120461       case 238: /* nexprlist ::= expr */
   120462 {yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy346.pExpr);}
   120463         break;
   120464       case 239: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt */
   120465 {
   120466   sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
   120467                      sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy14, yymsp[-10].minor.yy328,
   120468                       &yymsp[-11].minor.yy0, yymsp[0].minor.yy132, SQLITE_SO_ASC, yymsp[-8].minor.yy328);
   120469 }
   120470         break;
   120471       case 240: /* uniqueflag ::= UNIQUE */
   120472       case 291: /* raisetype ::= ABORT */ yytestcase(yyruleno==291);
   120473 {yygotominor.yy328 = OE_Abort;}
   120474         break;
   120475       case 241: /* uniqueflag ::= */
   120476 {yygotominor.yy328 = OE_None;}
   120477         break;
   120478       case 244: /* idxlist ::= idxlist COMMA nm collate sortorder */
   120479 {
   120480   Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
   120481   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, p);
   120482   sqlite3ExprListSetName(pParse,yygotominor.yy14,&yymsp[-2].minor.yy0,1);
   120483   sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
   120484   if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
   120485 }
   120486         break;
   120487       case 245: /* idxlist ::= nm collate sortorder */
   120488 {
   120489   Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
   120490   yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, p);
   120491   sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
   120492   sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
   120493   if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
   120494 }
   120495         break;
   120496       case 246: /* collate ::= */
   120497 {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
   120498         break;
   120499       case 248: /* cmd ::= DROP INDEX ifexists fullname */
   120500 {sqlite3DropIndex(pParse, yymsp[0].minor.yy65, yymsp[-1].minor.yy328);}
   120501         break;
   120502       case 249: /* cmd ::= VACUUM */
   120503       case 250: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==250);
   120504 {sqlite3Vacuum(pParse);}
   120505         break;
   120506       case 251: /* cmd ::= PRAGMA nm dbnm */
   120507 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
   120508         break;
   120509       case 252: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
   120510 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
   120511         break;
   120512       case 253: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
   120513 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
   120514         break;
   120515       case 254: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
   120516 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
   120517         break;
   120518       case 255: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
   120519 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
   120520         break;
   120521       case 264: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
   120522 {
   120523   Token all;
   120524   all.z = yymsp[-3].minor.yy0.z;
   120525   all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
   120526   sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy473, &all);
   120527 }
   120528         break;
   120529       case 265: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
   120530 {
   120531   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);
   120532   yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
   120533 }
   120534         break;
   120535       case 266: /* trigger_time ::= BEFORE */
   120536       case 269: /* trigger_time ::= */ yytestcase(yyruleno==269);
   120537 { yygotominor.yy328 = TK_BEFORE; }
   120538         break;
   120539       case 267: /* trigger_time ::= AFTER */
   120540 { yygotominor.yy328 = TK_AFTER;  }
   120541         break;
   120542       case 268: /* trigger_time ::= INSTEAD OF */
   120543 { yygotominor.yy328 = TK_INSTEAD;}
   120544         break;
   120545       case 270: /* trigger_event ::= DELETE|INSERT */
   120546       case 271: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==271);
   120547 {yygotominor.yy378.a = yymsp[0].major; yygotominor.yy378.b = 0;}
   120548         break;
   120549       case 272: /* trigger_event ::= UPDATE OF idlist */
   120550 {yygotominor.yy378.a = TK_UPDATE; yygotominor.yy378.b = yymsp[0].minor.yy408;}
   120551         break;
   120552       case 275: /* when_clause ::= */
   120553       case 296: /* key_opt ::= */ yytestcase(yyruleno==296);
   120554 { yygotominor.yy132 = 0; }
   120555         break;
   120556       case 276: /* when_clause ::= WHEN expr */
   120557       case 297: /* key_opt ::= KEY expr */ yytestcase(yyruleno==297);
   120558 { yygotominor.yy132 = yymsp[0].minor.yy346.pExpr; }
   120559         break;
   120560       case 277: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
   120561 {
   120562   assert( yymsp[-2].minor.yy473!=0 );
   120563   yymsp[-2].minor.yy473->pLast->pNext = yymsp[-1].minor.yy473;
   120564   yymsp[-2].minor.yy473->pLast = yymsp[-1].minor.yy473;
   120565   yygotominor.yy473 = yymsp[-2].minor.yy473;
   120566 }
   120567         break;
   120568       case 278: /* trigger_cmd_list ::= trigger_cmd SEMI */
   120569 {
   120570   assert( yymsp[-1].minor.yy473!=0 );
   120571   yymsp[-1].minor.yy473->pLast = yymsp[-1].minor.yy473;
   120572   yygotominor.yy473 = yymsp[-1].minor.yy473;
   120573 }
   120574         break;
   120575       case 280: /* trnm ::= nm DOT nm */
   120576 {
   120577   yygotominor.yy0 = yymsp[0].minor.yy0;
   120578   sqlite3ErrorMsg(pParse,
   120579         "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
   120580         "statements within triggers");
   120581 }
   120582         break;
   120583       case 282: /* tridxby ::= INDEXED BY nm */
   120584 {
   120585   sqlite3ErrorMsg(pParse,
   120586         "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
   120587         "within triggers");
   120588 }
   120589         break;
   120590       case 283: /* tridxby ::= NOT INDEXED */
   120591 {
   120592   sqlite3ErrorMsg(pParse,
   120593         "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
   120594         "within triggers");
   120595 }
   120596         break;
   120597       case 284: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
   120598 { yygotominor.yy473 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy14, yymsp[0].minor.yy132, yymsp[-5].minor.yy186); }
   120599         break;
   120600       case 285: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
   120601 {yygotominor.yy473 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy408, yymsp[0].minor.yy3, yymsp[-4].minor.yy186);}
   120602         break;
   120603       case 286: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
   120604 {yygotominor.yy473 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy132);}
   120605         break;
   120606       case 287: /* trigger_cmd ::= select */
   120607 {yygotominor.yy473 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy3); }
   120608         break;
   120609       case 288: /* expr ::= RAISE LP IGNORE RP */
   120610 {
   120611   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
   120612   if( yygotominor.yy346.pExpr ){
   120613     yygotominor.yy346.pExpr->affinity = OE_Ignore;
   120614   }
   120615   yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
   120616   yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   120617 }
   120618         break;
   120619       case 289: /* expr ::= RAISE LP raisetype COMMA nm RP */
   120620 {
   120621   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
   120622   if( yygotominor.yy346.pExpr ) {
   120623     yygotominor.yy346.pExpr->affinity = (char)yymsp[-3].minor.yy328;
   120624   }
   120625   yygotominor.yy346.zStart = yymsp[-5].minor.yy0.z;
   120626   yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   120627 }
   120628         break;
   120629       case 290: /* raisetype ::= ROLLBACK */
   120630 {yygotominor.yy328 = OE_Rollback;}
   120631         break;
   120632       case 292: /* raisetype ::= FAIL */
   120633 {yygotominor.yy328 = OE_Fail;}
   120634         break;
   120635       case 293: /* cmd ::= DROP TRIGGER ifexists fullname */
   120636 {
   120637   sqlite3DropTrigger(pParse,yymsp[0].minor.yy65,yymsp[-1].minor.yy328);
   120638 }
   120639         break;
   120640       case 294: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
   120641 {
   120642   sqlite3Attach(pParse, yymsp[-3].minor.yy346.pExpr, yymsp[-1].minor.yy346.pExpr, yymsp[0].minor.yy132);
   120643 }
   120644         break;
   120645       case 295: /* cmd ::= DETACH database_kw_opt expr */
   120646 {
   120647   sqlite3Detach(pParse, yymsp[0].minor.yy346.pExpr);
   120648 }
   120649         break;
   120650       case 300: /* cmd ::= REINDEX */
   120651 {sqlite3Reindex(pParse, 0, 0);}
   120652         break;
   120653       case 301: /* cmd ::= REINDEX nm dbnm */
   120654 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
   120655         break;
   120656       case 302: /* cmd ::= ANALYZE */
   120657 {sqlite3Analyze(pParse, 0, 0);}
   120658         break;
   120659       case 303: /* cmd ::= ANALYZE nm dbnm */
   120660 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
   120661         break;
   120662       case 304: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
   120663 {
   120664   sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy65,&yymsp[0].minor.yy0);
   120665 }
   120666         break;
   120667       case 305: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
   120668 {
   120669   sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
   120670 }
   120671         break;
   120672       case 306: /* add_column_fullname ::= fullname */
   120673 {
   120674   pParse->db->lookaside.bEnabled = 0;
   120675   sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy65);
   120676 }
   120677         break;
   120678       case 309: /* cmd ::= create_vtab */
   120679 {sqlite3VtabFinishParse(pParse,0);}
   120680         break;
   120681       case 310: /* cmd ::= create_vtab LP vtabarglist RP */
   120682 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
   120683         break;
   120684       case 311: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
   120685 {
   120686     sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy328);
   120687 }
   120688         break;
   120689       case 314: /* vtabarg ::= */
   120690 {sqlite3VtabArgInit(pParse);}
   120691         break;
   120692       case 316: /* vtabargtoken ::= ANY */
   120693       case 317: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==317);
   120694       case 318: /* lp ::= LP */ yytestcase(yyruleno==318);
   120695 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
   120696         break;
   120697       case 322: /* with ::= */
   120698 {yygotominor.yy59 = 0;}
   120699         break;
   120700       case 323: /* with ::= WITH wqlist */
   120701       case 324: /* with ::= WITH RECURSIVE wqlist */ yytestcase(yyruleno==324);
   120702 { yygotominor.yy59 = yymsp[0].minor.yy59; }
   120703         break;
   120704       case 325: /* wqlist ::= nm idxlist_opt AS LP select RP */
   120705 {
   120706   yygotominor.yy59 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy14, yymsp[-1].minor.yy3);
   120707 }
   120708         break;
   120709       case 326: /* wqlist ::= wqlist COMMA nm idxlist_opt AS LP select RP */
   120710 {
   120711   yygotominor.yy59 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy59, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy14, yymsp[-1].minor.yy3);
   120712 }
   120713         break;
   120714       default:
   120715       /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
   120716       /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
   120717       /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
   120718       /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
   120719       /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
   120720       /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
   120721       /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
   120722       /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
   120723       /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
   120724       /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
   120725       /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
   120726       /* (36) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==36);
   120727       /* (37) columnlist ::= column */ yytestcase(yyruleno==37);
   120728       /* (43) type ::= */ yytestcase(yyruleno==43);
   120729       /* (50) signed ::= plus_num */ yytestcase(yyruleno==50);
   120730       /* (51) signed ::= minus_num */ yytestcase(yyruleno==51);
   120731       /* (52) carglist ::= carglist ccons */ yytestcase(yyruleno==52);
   120732       /* (53) carglist ::= */ yytestcase(yyruleno==53);
   120733       /* (60) ccons ::= NULL onconf */ yytestcase(yyruleno==60);
   120734       /* (88) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==88);
   120735       /* (89) conslist ::= tcons */ yytestcase(yyruleno==89);
   120736       /* (91) tconscomma ::= */ yytestcase(yyruleno==91);
   120737       /* (273) foreach_clause ::= */ yytestcase(yyruleno==273);
   120738       /* (274) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==274);
   120739       /* (281) tridxby ::= */ yytestcase(yyruleno==281);
   120740       /* (298) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==298);
   120741       /* (299) database_kw_opt ::= */ yytestcase(yyruleno==299);
   120742       /* (307) kwcolumn_opt ::= */ yytestcase(yyruleno==307);
   120743       /* (308) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==308);
   120744       /* (312) vtabarglist ::= vtabarg */ yytestcase(yyruleno==312);
   120745       /* (313) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==313);
   120746       /* (315) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==315);
   120747       /* (319) anylist ::= */ yytestcase(yyruleno==319);
   120748       /* (320) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==320);
   120749       /* (321) anylist ::= anylist ANY */ yytestcase(yyruleno==321);
   120750         break;
   120751   };
   120752   assert( yyruleno>=0 && yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
   120753   yygoto = yyRuleInfo[yyruleno].lhs;
   120754   yysize = yyRuleInfo[yyruleno].nrhs;
   120755   yypParser->yyidx -= yysize;
   120756   yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
   120757   if( yyact < YYNSTATE ){
   120758 #ifdef NDEBUG
   120759     /* If we are not debugging and the reduce action popped at least
   120760     ** one element off the stack, then we can push the new element back
   120761     ** onto the stack here, and skip the stack overflow test in yy_shift().
   120762     ** That gives a significant speed improvement. */
   120763     if( yysize ){
   120764       yypParser->yyidx++;
   120765       yymsp -= yysize-1;
   120766       yymsp->stateno = (YYACTIONTYPE)yyact;
   120767       yymsp->major = (YYCODETYPE)yygoto;
   120768       yymsp->minor = yygotominor;
   120769     }else
   120770 #endif
   120771     {
   120772       yy_shift(yypParser,yyact,yygoto,&yygotominor);
   120773     }
   120774   }else{
   120775     assert( yyact == YYNSTATE + YYNRULE + 1 );
   120776     yy_accept(yypParser);
   120777   }
   120778 }
   120779 
   120780 /*
   120781 ** The following code executes when the parse fails
   120782 */
   120783 #ifndef YYNOERRORRECOVERY
   120784 static void yy_parse_failed(
   120785   yyParser *yypParser           /* The parser */
   120786 ){
   120787   sqlite3ParserARG_FETCH;
   120788 #ifndef NDEBUG
   120789   if( yyTraceFILE ){
   120790     fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
   120791   }
   120792 #endif
   120793   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
   120794   /* Here code is inserted which will be executed whenever the
   120795   ** parser fails */
   120796   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
   120797 }
   120798 #endif /* YYNOERRORRECOVERY */
   120799 
   120800 /*
   120801 ** The following code executes when a syntax error first occurs.
   120802 */
   120803 static void yy_syntax_error(
   120804   yyParser *yypParser,           /* The parser */
   120805   int yymajor,                   /* The major type of the error token */
   120806   YYMINORTYPE yyminor            /* The minor type of the error token */
   120807 ){
   120808   sqlite3ParserARG_FETCH;
   120809 #define TOKEN (yyminor.yy0)
   120810 
   120811   UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
   120812   assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
   120813   sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
   120814   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
   120815 }
   120816 
   120817 /*
   120818 ** The following is executed when the parser accepts
   120819 */
   120820 static void yy_accept(
   120821   yyParser *yypParser           /* The parser */
   120822 ){
   120823   sqlite3ParserARG_FETCH;
   120824 #ifndef NDEBUG
   120825   if( yyTraceFILE ){
   120826     fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
   120827   }
   120828 #endif
   120829   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
   120830   /* Here code is inserted which will be executed whenever the
   120831   ** parser accepts */
   120832   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
   120833 }
   120834 
   120835 /* The main parser program.
   120836 ** The first argument is a pointer to a structure obtained from
   120837 ** "sqlite3ParserAlloc" which describes the current state of the parser.
   120838 ** The second argument is the major token number.  The third is
   120839 ** the minor token.  The fourth optional argument is whatever the
   120840 ** user wants (and specified in the grammar) and is available for
   120841 ** use by the action routines.
   120842 **
   120843 ** Inputs:
   120844 ** <ul>
   120845 ** <li> A pointer to the parser (an opaque structure.)
   120846 ** <li> The major token number.
   120847 ** <li> The minor token number.
   120848 ** <li> An option argument of a grammar-specified type.
   120849 ** </ul>
   120850 **
   120851 ** Outputs:
   120852 ** None.
   120853 */
   120854 SQLITE_PRIVATE void sqlite3Parser(
   120855   void *yyp,                   /* The parser */
   120856   int yymajor,                 /* The major token code number */
   120857   sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
   120858   sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
   120859 ){
   120860   YYMINORTYPE yyminorunion;
   120861   int yyact;            /* The parser action. */
   120862 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
   120863   int yyendofinput;     /* True if we are at the end of input */
   120864 #endif
   120865 #ifdef YYERRORSYMBOL
   120866   int yyerrorhit = 0;   /* True if yymajor has invoked an error */
   120867 #endif
   120868   yyParser *yypParser;  /* The parser */
   120869 
   120870   /* (re)initialize the parser, if necessary */
   120871   yypParser = (yyParser*)yyp;
   120872   if( yypParser->yyidx<0 ){
   120873 #if YYSTACKDEPTH<=0
   120874     if( yypParser->yystksz <=0 ){
   120875       /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
   120876       yyminorunion = yyzerominor;
   120877       yyStackOverflow(yypParser, &yyminorunion);
   120878       return;
   120879     }
   120880 #endif
   120881     yypParser->yyidx = 0;
   120882     yypParser->yyerrcnt = -1;
   120883     yypParser->yystack[0].stateno = 0;
   120884     yypParser->yystack[0].major = 0;
   120885   }
   120886   yyminorunion.yy0 = yyminor;
   120887 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
   120888   yyendofinput = (yymajor==0);
   120889 #endif
   120890   sqlite3ParserARG_STORE;
   120891 
   120892 #ifndef NDEBUG
   120893   if( yyTraceFILE ){
   120894     fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
   120895   }
   120896 #endif
   120897 
   120898   do{
   120899     yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
   120900     if( yyact<YYNSTATE ){
   120901       yy_shift(yypParser,yyact,yymajor,&yyminorunion);
   120902       yypParser->yyerrcnt--;
   120903       yymajor = YYNOCODE;
   120904     }else if( yyact < YYNSTATE + YYNRULE ){
   120905       yy_reduce(yypParser,yyact-YYNSTATE);
   120906     }else{
   120907       assert( yyact == YY_ERROR_ACTION );
   120908 #ifdef YYERRORSYMBOL
   120909       int yymx;
   120910 #endif
   120911 #ifndef NDEBUG
   120912       if( yyTraceFILE ){
   120913         fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
   120914       }
   120915 #endif
   120916 #ifdef YYERRORSYMBOL
   120917       /* A syntax error has occurred.
   120918       ** The response to an error depends upon whether or not the
   120919       ** grammar defines an error token "ERROR".
   120920       **
   120921       ** This is what we do if the grammar does define ERROR:
   120922       **
   120923       **  * Call the %syntax_error function.
   120924       **
   120925       **  * Begin popping the stack until we enter a state where
   120926       **    it is legal to shift the error symbol, then shift
   120927       **    the error symbol.
   120928       **
   120929       **  * Set the error count to three.
   120930       **
   120931       **  * Begin accepting and shifting new tokens.  No new error
   120932       **    processing will occur until three tokens have been
   120933       **    shifted successfully.
   120934       **
   120935       */
   120936       if( yypParser->yyerrcnt<0 ){
   120937         yy_syntax_error(yypParser,yymajor,yyminorunion);
   120938       }
   120939       yymx = yypParser->yystack[yypParser->yyidx].major;
   120940       if( yymx==YYERRORSYMBOL || yyerrorhit ){
   120941 #ifndef NDEBUG
   120942         if( yyTraceFILE ){
   120943           fprintf(yyTraceFILE,"%sDiscard input token %s\n",
   120944              yyTracePrompt,yyTokenName[yymajor]);
   120945         }
   120946 #endif
   120947         yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
   120948         yymajor = YYNOCODE;
   120949       }else{
   120950          while(
   120951           yypParser->yyidx >= 0 &&
   120952           yymx != YYERRORSYMBOL &&
   120953           (yyact = yy_find_reduce_action(
   120954                         yypParser->yystack[yypParser->yyidx].stateno,
   120955                         YYERRORSYMBOL)) >= YYNSTATE
   120956         ){
   120957           yy_pop_parser_stack(yypParser);
   120958         }
   120959         if( yypParser->yyidx < 0 || yymajor==0 ){
   120960           yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
   120961           yy_parse_failed(yypParser);
   120962           yymajor = YYNOCODE;
   120963         }else if( yymx!=YYERRORSYMBOL ){
   120964           YYMINORTYPE u2;
   120965           u2.YYERRSYMDT = 0;
   120966           yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
   120967         }
   120968       }
   120969       yypParser->yyerrcnt = 3;
   120970       yyerrorhit = 1;
   120971 #elif defined(YYNOERRORRECOVERY)
   120972       /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
   120973       ** do any kind of error recovery.  Instead, simply invoke the syntax
   120974       ** error routine and continue going as if nothing had happened.
   120975       **
   120976       ** Applications can set this macro (for example inside %include) if
   120977       ** they intend to abandon the parse upon the first syntax error seen.
   120978       */
   120979       yy_syntax_error(yypParser,yymajor,yyminorunion);
   120980       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
   120981       yymajor = YYNOCODE;
   120982 
   120983 #else  /* YYERRORSYMBOL is not defined */
   120984       /* This is what we do if the grammar does not define ERROR:
   120985       **
   120986       **  * Report an error message, and throw away the input token.
   120987       **
   120988       **  * If the input token is $, then fail the parse.
   120989       **
   120990       ** As before, subsequent error messages are suppressed until
   120991       ** three input tokens have been successfully shifted.
   120992       */
   120993       if( yypParser->yyerrcnt<=0 ){
   120994         yy_syntax_error(yypParser,yymajor,yyminorunion);
   120995       }
   120996       yypParser->yyerrcnt = 3;
   120997       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
   120998       if( yyendofinput ){
   120999         yy_parse_failed(yypParser);
   121000       }
   121001       yymajor = YYNOCODE;
   121002 #endif
   121003     }
   121004   }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
   121005   return;
   121006 }
   121007 
   121008 /************** End of parse.c ***********************************************/
   121009 /************** Begin file tokenize.c ****************************************/
   121010 /*
   121011 ** 2001 September 15
   121012 **
   121013 ** The author disclaims copyright to this source code.  In place of
   121014 ** a legal notice, here is a blessing:
   121015 **
   121016 **    May you do good and not evil.
   121017 **    May you find forgiveness for yourself and forgive others.
   121018 **    May you share freely, never taking more than you give.
   121019 **
   121020 *************************************************************************
   121021 ** An tokenizer for SQL
   121022 **
   121023 ** This file contains C code that splits an SQL input string up into
   121024 ** individual tokens and sends those tokens one-by-one over to the
   121025 ** parser for analysis.
   121026 */
   121027 /* #include <stdlib.h> */
   121028 
   121029 /*
   121030 ** The charMap() macro maps alphabetic characters into their
   121031 ** lower-case ASCII equivalent.  On ASCII machines, this is just
   121032 ** an upper-to-lower case map.  On EBCDIC machines we also need
   121033 ** to adjust the encoding.  Only alphabetic characters and underscores
   121034 ** need to be translated.
   121035 */
   121036 #ifdef SQLITE_ASCII
   121037 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
   121038 #endif
   121039 #ifdef SQLITE_EBCDIC
   121040 # define charMap(X) ebcdicToAscii[(unsigned char)X]
   121041 const unsigned char ebcdicToAscii[] = {
   121042 /* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
   121043    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
   121044    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
   121045    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
   121046    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
   121047    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
   121048    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
   121049    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
   121050    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
   121051    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
   121052    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
   121053    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
   121054    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
   121055    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
   121056    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
   121057    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
   121058    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
   121059 };
   121060 #endif
   121061 
   121062 /*
   121063 ** The sqlite3KeywordCode function looks up an identifier to determine if
   121064 ** it is a keyword.  If it is a keyword, the token code of that keyword is
   121065 ** returned.  If the input is not a keyword, TK_ID is returned.
   121066 **
   121067 ** The implementation of this routine was generated by a program,
   121068 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
   121069 ** The output of the mkkeywordhash.c program is written into a file
   121070 ** named keywordhash.h and then included into this source file by
   121071 ** the #include below.
   121072 */
   121073 /************** Include keywordhash.h in the middle of tokenize.c ************/
   121074 /************** Begin file keywordhash.h *************************************/
   121075 /***** This file contains automatically generated code ******
   121076 **
   121077 ** The code in this file has been automatically generated by
   121078 **
   121079 **   sqlite/tool/mkkeywordhash.c
   121080 **
   121081 ** The code in this file implements a function that determines whether
   121082 ** or not a given identifier is really an SQL keyword.  The same thing
   121083 ** might be implemented more directly using a hand-written hash table.
   121084 ** But by using this automatically generated code, the size of the code
   121085 ** is substantially reduced.  This is important for embedded applications
   121086 ** on platforms with limited memory.
   121087 */
   121088 /* Hash score: 182 */
   121089 static int keywordCode(const char *z, int n){
   121090   /* zText[] encodes 834 bytes of keywords in 554 bytes */
   121091   /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
   121092   /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
   121093   /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
   121094   /*   UNIQUERYWITHOUTERELEASEATTACHAVINGROUPDATEBEGINNERECURSIVE         */
   121095   /*   BETWEENOTNULLIKECASCADELETECASECOLLATECREATECURRENT_DATEDETACH     */
   121096   /*   IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN     */
   121097   /*   WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMIT         */
   121098   /*   CONFLICTCROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAIL        */
   121099   /*   FROMFULLGLOBYIFISNULLORDERESTRICTRIGHTROLLBACKROWUNIONUSING        */
   121100   /*   VACUUMVIEWINITIALLY                                                */
   121101   static const char zText[553] = {
   121102     'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
   121103     'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
   121104     'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
   121105     'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
   121106     'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
   121107     'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
   121108     'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
   121109     'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
   121110     'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
   121111     'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
   121112     'U','E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S',
   121113     'E','A','T','T','A','C','H','A','V','I','N','G','R','O','U','P','D','A',
   121114     'T','E','B','E','G','I','N','N','E','R','E','C','U','R','S','I','V','E',
   121115     'B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C','A',
   121116     'S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L','A',
   121117     'T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A',
   121118     'T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E','J',
   121119     'O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A','L',
   121120     'Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U','E',
   121121     'S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W','H',
   121122     'E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C','E',
   121123     'A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R','E',
   121124     'M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M','M',
   121125     'I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U','R',
   121126     'R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M','A',
   121127     'R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','D',
   121128     'R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L','O',
   121129     'B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S','T',
   121130     'R','I','C','T','R','I','G','H','T','R','O','L','L','B','A','C','K','R',
   121131     'O','W','U','N','I','O','N','U','S','I','N','G','V','A','C','U','U','M',
   121132     'V','I','E','W','I','N','I','T','I','A','L','L','Y',
   121133   };
   121134   static const unsigned char aHash[127] = {
   121135       76, 105, 117,  74,   0,  45,   0,   0,  82,   0,  77,   0,   0,
   121136       42,  12,  78,  15,   0, 116,  85,  54, 112,   0,  19,   0,   0,
   121137      121,   0, 119, 115,   0,  22,  93,   0,   9,   0,   0,  70,  71,
   121138        0,  69,   6,   0,  48,  90, 102,   0, 118, 101,   0,   0,  44,
   121139        0, 103,  24,   0,  17,   0, 122,  53,  23,   0,   5, 110,  25,
   121140       96,   0,   0, 124, 106,  60, 123,  57,  28,  55,   0,  91,   0,
   121141      100,  26,   0,  99,   0,   0,   0,  95,  92,  97,  88, 109,  14,
   121142       39, 108,   0,  81,   0,  18,  89, 111,  32,   0, 120,  80, 113,
   121143       62,  46,  84,   0,   0,  94,  40,  59, 114,   0,  36,   0,   0,
   121144       29,   0,  86,  63,  64,   0,  20,  61,   0,  56,
   121145   };
   121146   static const unsigned char aNext[124] = {
   121147        0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
   121148        0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
   121149        0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
   121150        0,   0,   0,   0,  33,   0,  21,   0,   0,   0,   0,   0,  50,
   121151        0,  43,   3,  47,   0,   0,   0,   0,  30,   0,  58,   0,  38,
   121152        0,   0,   0,   1,  66,   0,   0,  67,   0,  41,   0,   0,   0,
   121153        0,   0,   0,  49,  65,   0,   0,   0,   0,  31,  52,  16,  34,
   121154       10,   0,   0,   0,   0,   0,   0,   0,  11,  72,  79,   0,   8,
   121155        0, 104,  98,   0, 107,   0,  87,   0,  75,  51,   0,  27,  37,
   121156       73,  83,   0,  35,  68,   0,   0,
   121157   };
   121158   static const unsigned char aLen[124] = {
   121159        7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
   121160        7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
   121161       11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
   121162        4,   6,   2,   3,   9,   4,   2,   6,   5,   7,   4,   5,   7,
   121163        6,   6,   5,   6,   5,   5,   9,   7,   7,   3,   2,   4,   4,
   121164        7,   3,   6,   4,   7,   6,  12,   6,   9,   4,   6,   5,   4,
   121165        7,   6,   5,   6,   7,   5,   4,   5,   6,   5,   7,   3,   7,
   121166       13,   2,   2,   4,   6,   6,   8,   5,  17,  12,   7,   8,   8,
   121167        2,   4,   4,   4,   4,   4,   2,   2,   6,   5,   8,   5,   8,
   121168        3,   5,   5,   6,   4,   9,   3,
   121169   };
   121170   static const unsigned short int aOffset[124] = {
   121171        0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
   121172       36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
   121173       86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
   121174      159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 184, 188, 192,
   121175      199, 204, 209, 212, 218, 221, 225, 234, 240, 240, 240, 243, 246,
   121176      250, 251, 255, 261, 265, 272, 278, 290, 296, 305, 307, 313, 318,
   121177      320, 327, 332, 337, 343, 349, 354, 358, 361, 367, 371, 378, 380,
   121178      387, 389, 391, 400, 404, 410, 416, 424, 429, 429, 445, 452, 459,
   121179      460, 467, 471, 475, 479, 483, 486, 488, 490, 496, 500, 508, 513,
   121180      521, 524, 529, 534, 540, 544, 549,
   121181   };
   121182   static const unsigned char aCode[124] = {
   121183     TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,
   121184     TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,
   121185     TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,
   121186     TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,
   121187     TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,
   121188     TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,
   121189     TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,
   121190     TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
   121191     TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,
   121192     TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_WITHOUT,    TK_WITH,
   121193     TK_JOIN_KW,    TK_RELEASE,    TK_ATTACH,     TK_HAVING,     TK_GROUP,
   121194     TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RECURSIVE,  TK_BETWEEN,
   121195     TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,       TK_LIKE_KW,
   121196     TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,       TK_COLLATE,
   121197     TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,  TK_JOIN,
   121198     TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,    TK_PRAGMA,
   121199     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,      TK_WHEN,
   121200     TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,    TK_AND,
   121201     TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,         TK_CAST,
   121202     TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,    TK_CTIME_KW,
   121203     TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,   TK_IS,
   121204     TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,    TK_LIKE_KW,
   121205     TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,      TK_RESTRICT,
   121206     TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,        TK_UNION,      TK_USING,
   121207     TK_VACUUM,     TK_VIEW,       TK_INITIALLY,  TK_ALL,
   121208   };
   121209   int h, i;
   121210   if( n<2 ) return TK_ID;
   121211   h = ((charMap(z[0])*4) ^
   121212       (charMap(z[n-1])*3) ^
   121213       n) % 127;
   121214   for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
   121215     if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
   121216       testcase( i==0 ); /* REINDEX */
   121217       testcase( i==1 ); /* INDEXED */
   121218       testcase( i==2 ); /* INDEX */
   121219       testcase( i==3 ); /* DESC */
   121220       testcase( i==4 ); /* ESCAPE */
   121221       testcase( i==5 ); /* EACH */
   121222       testcase( i==6 ); /* CHECK */
   121223       testcase( i==7 ); /* KEY */
   121224       testcase( i==8 ); /* BEFORE */
   121225       testcase( i==9 ); /* FOREIGN */
   121226       testcase( i==10 ); /* FOR */
   121227       testcase( i==11 ); /* IGNORE */
   121228       testcase( i==12 ); /* REGEXP */
   121229       testcase( i==13 ); /* EXPLAIN */
   121230       testcase( i==14 ); /* INSTEAD */
   121231       testcase( i==15 ); /* ADD */
   121232       testcase( i==16 ); /* DATABASE */
   121233       testcase( i==17 ); /* AS */
   121234       testcase( i==18 ); /* SELECT */
   121235       testcase( i==19 ); /* TABLE */
   121236       testcase( i==20 ); /* LEFT */
   121237       testcase( i==21 ); /* THEN */
   121238       testcase( i==22 ); /* END */
   121239       testcase( i==23 ); /* DEFERRABLE */
   121240       testcase( i==24 ); /* ELSE */
   121241       testcase( i==25 ); /* EXCEPT */
   121242       testcase( i==26 ); /* TRANSACTION */
   121243       testcase( i==27 ); /* ACTION */
   121244       testcase( i==28 ); /* ON */
   121245       testcase( i==29 ); /* NATURAL */
   121246       testcase( i==30 ); /* ALTER */
   121247       testcase( i==31 ); /* RAISE */
   121248       testcase( i==32 ); /* EXCLUSIVE */
   121249       testcase( i==33 ); /* EXISTS */
   121250       testcase( i==34 ); /* SAVEPOINT */
   121251       testcase( i==35 ); /* INTERSECT */
   121252       testcase( i==36 ); /* TRIGGER */
   121253       testcase( i==37 ); /* REFERENCES */
   121254       testcase( i==38 ); /* CONSTRAINT */
   121255       testcase( i==39 ); /* INTO */
   121256       testcase( i==40 ); /* OFFSET */
   121257       testcase( i==41 ); /* OF */
   121258       testcase( i==42 ); /* SET */
   121259       testcase( i==43 ); /* TEMPORARY */
   121260       testcase( i==44 ); /* TEMP */
   121261       testcase( i==45 ); /* OR */
   121262       testcase( i==46 ); /* UNIQUE */
   121263       testcase( i==47 ); /* QUERY */
   121264       testcase( i==48 ); /* WITHOUT */
   121265       testcase( i==49 ); /* WITH */
   121266       testcase( i==50 ); /* OUTER */
   121267       testcase( i==51 ); /* RELEASE */
   121268       testcase( i==52 ); /* ATTACH */
   121269       testcase( i==53 ); /* HAVING */
   121270       testcase( i==54 ); /* GROUP */
   121271       testcase( i==55 ); /* UPDATE */
   121272       testcase( i==56 ); /* BEGIN */
   121273       testcase( i==57 ); /* INNER */
   121274       testcase( i==58 ); /* RECURSIVE */
   121275       testcase( i==59 ); /* BETWEEN */
   121276       testcase( i==60 ); /* NOTNULL */
   121277       testcase( i==61 ); /* NOT */
   121278       testcase( i==62 ); /* NO */
   121279       testcase( i==63 ); /* NULL */
   121280       testcase( i==64 ); /* LIKE */
   121281       testcase( i==65 ); /* CASCADE */
   121282       testcase( i==66 ); /* ASC */
   121283       testcase( i==67 ); /* DELETE */
   121284       testcase( i==68 ); /* CASE */
   121285       testcase( i==69 ); /* COLLATE */
   121286       testcase( i==70 ); /* CREATE */
   121287       testcase( i==71 ); /* CURRENT_DATE */
   121288       testcase( i==72 ); /* DETACH */
   121289       testcase( i==73 ); /* IMMEDIATE */
   121290       testcase( i==74 ); /* JOIN */
   121291       testcase( i==75 ); /* INSERT */
   121292       testcase( i==76 ); /* MATCH */
   121293       testcase( i==77 ); /* PLAN */
   121294       testcase( i==78 ); /* ANALYZE */
   121295       testcase( i==79 ); /* PRAGMA */
   121296       testcase( i==80 ); /* ABORT */
   121297       testcase( i==81 ); /* VALUES */
   121298       testcase( i==82 ); /* VIRTUAL */
   121299       testcase( i==83 ); /* LIMIT */
   121300       testcase( i==84 ); /* WHEN */
   121301       testcase( i==85 ); /* WHERE */
   121302       testcase( i==86 ); /* RENAME */
   121303       testcase( i==87 ); /* AFTER */
   121304       testcase( i==88 ); /* REPLACE */
   121305       testcase( i==89 ); /* AND */
   121306       testcase( i==90 ); /* DEFAULT */
   121307       testcase( i==91 ); /* AUTOINCREMENT */
   121308       testcase( i==92 ); /* TO */
   121309       testcase( i==93 ); /* IN */
   121310       testcase( i==94 ); /* CAST */
   121311       testcase( i==95 ); /* COLUMN */
   121312       testcase( i==96 ); /* COMMIT */
   121313       testcase( i==97 ); /* CONFLICT */
   121314       testcase( i==98 ); /* CROSS */
   121315       testcase( i==99 ); /* CURRENT_TIMESTAMP */
   121316       testcase( i==100 ); /* CURRENT_TIME */
   121317       testcase( i==101 ); /* PRIMARY */
   121318       testcase( i==102 ); /* DEFERRED */
   121319       testcase( i==103 ); /* DISTINCT */
   121320       testcase( i==104 ); /* IS */
   121321       testcase( i==105 ); /* DROP */
   121322       testcase( i==106 ); /* FAIL */
   121323       testcase( i==107 ); /* FROM */
   121324       testcase( i==108 ); /* FULL */
   121325       testcase( i==109 ); /* GLOB */
   121326       testcase( i==110 ); /* BY */
   121327       testcase( i==111 ); /* IF */
   121328       testcase( i==112 ); /* ISNULL */
   121329       testcase( i==113 ); /* ORDER */
   121330       testcase( i==114 ); /* RESTRICT */
   121331       testcase( i==115 ); /* RIGHT */
   121332       testcase( i==116 ); /* ROLLBACK */
   121333       testcase( i==117 ); /* ROW */
   121334       testcase( i==118 ); /* UNION */
   121335       testcase( i==119 ); /* USING */
   121336       testcase( i==120 ); /* VACUUM */
   121337       testcase( i==121 ); /* VIEW */
   121338       testcase( i==122 ); /* INITIALLY */
   121339       testcase( i==123 ); /* ALL */
   121340       return aCode[i];
   121341     }
   121342   }
   121343   return TK_ID;
   121344 }
   121345 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
   121346   return keywordCode((char*)z, n);
   121347 }
   121348 #define SQLITE_N_KEYWORD 124
   121349 
   121350 /************** End of keywordhash.h *****************************************/
   121351 /************** Continuing where we left off in tokenize.c *******************/
   121352 
   121353 
   121354 /*
   121355 ** If X is a character that can be used in an identifier then
   121356 ** IdChar(X) will be true.  Otherwise it is false.
   121357 **
   121358 ** For ASCII, any character with the high-order bit set is
   121359 ** allowed in an identifier.  For 7-bit characters,
   121360 ** sqlite3IsIdChar[X] must be 1.
   121361 **
   121362 ** For EBCDIC, the rules are more complex but have the same
   121363 ** end result.
   121364 **
   121365 ** Ticket #1066.  the SQL standard does not allow '$' in the
   121366 ** middle of identfiers.  But many SQL implementations do.
   121367 ** SQLite will allow '$' in identifiers for compatibility.
   121368 ** But the feature is undocumented.
   121369 */
   121370 #ifdef SQLITE_ASCII
   121371 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
   121372 #endif
   121373 #ifdef SQLITE_EBCDIC
   121374 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
   121375 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
   121376     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
   121377     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
   121378     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
   121379     0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
   121380     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
   121381     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
   121382     1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
   121383     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
   121384     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
   121385     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
   121386     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
   121387     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
   121388 };
   121389 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
   121390 #endif
   121391 
   121392 
   121393 /*
   121394 ** Return the length of the token that begins at z[0].
   121395 ** Store the token type in *tokenType before returning.
   121396 */
   121397 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
   121398   int i, c;
   121399   switch( *z ){
   121400     case ' ': case '\t': case '\n': case '\f': case '\r': {
   121401       testcase( z[0]==' ' );
   121402       testcase( z[0]=='\t' );
   121403       testcase( z[0]=='\n' );
   121404       testcase( z[0]=='\f' );
   121405       testcase( z[0]=='\r' );
   121406       for(i=1; sqlite3Isspace(z[i]); i++){}
   121407       *tokenType = TK_SPACE;
   121408       return i;
   121409     }
   121410     case '-': {
   121411       if( z[1]=='-' ){
   121412         for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
   121413         *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
   121414         return i;
   121415       }
   121416       *tokenType = TK_MINUS;
   121417       return 1;
   121418     }
   121419     case '(': {
   121420       *tokenType = TK_LP;
   121421       return 1;
   121422     }
   121423     case ')': {
   121424       *tokenType = TK_RP;
   121425       return 1;
   121426     }
   121427     case ';': {
   121428       *tokenType = TK_SEMI;
   121429       return 1;
   121430     }
   121431     case '+': {
   121432       *tokenType = TK_PLUS;
   121433       return 1;
   121434     }
   121435     case '*': {
   121436       *tokenType = TK_STAR;
   121437       return 1;
   121438     }
   121439     case '/': {
   121440       if( z[1]!='*' || z[2]==0 ){
   121441         *tokenType = TK_SLASH;
   121442         return 1;
   121443       }
   121444       for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
   121445       if( c ) i++;
   121446       *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
   121447       return i;
   121448     }
   121449     case '%': {
   121450       *tokenType = TK_REM;
   121451       return 1;
   121452     }
   121453     case '=': {
   121454       *tokenType = TK_EQ;
   121455       return 1 + (z[1]=='=');
   121456     }
   121457     case '<': {
   121458       if( (c=z[1])=='=' ){
   121459         *tokenType = TK_LE;
   121460         return 2;
   121461       }else if( c=='>' ){
   121462         *tokenType = TK_NE;
   121463         return 2;
   121464       }else if( c=='<' ){
   121465         *tokenType = TK_LSHIFT;
   121466         return 2;
   121467       }else{
   121468         *tokenType = TK_LT;
   121469         return 1;
   121470       }
   121471     }
   121472     case '>': {
   121473       if( (c=z[1])=='=' ){
   121474         *tokenType = TK_GE;
   121475         return 2;
   121476       }else if( c=='>' ){
   121477         *tokenType = TK_RSHIFT;
   121478         return 2;
   121479       }else{
   121480         *tokenType = TK_GT;
   121481         return 1;
   121482       }
   121483     }
   121484     case '!': {
   121485       if( z[1]!='=' ){
   121486         *tokenType = TK_ILLEGAL;
   121487         return 2;
   121488       }else{
   121489         *tokenType = TK_NE;
   121490         return 2;
   121491       }
   121492     }
   121493     case '|': {
   121494       if( z[1]!='|' ){
   121495         *tokenType = TK_BITOR;
   121496         return 1;
   121497       }else{
   121498         *tokenType = TK_CONCAT;
   121499         return 2;
   121500       }
   121501     }
   121502     case ',': {
   121503       *tokenType = TK_COMMA;
   121504       return 1;
   121505     }
   121506     case '&': {
   121507       *tokenType = TK_BITAND;
   121508       return 1;
   121509     }
   121510     case '~': {
   121511       *tokenType = TK_BITNOT;
   121512       return 1;
   121513     }
   121514     case '`':
   121515     case '\'':
   121516     case '"': {
   121517       int delim = z[0];
   121518       testcase( delim=='`' );
   121519       testcase( delim=='\'' );
   121520       testcase( delim=='"' );
   121521       for(i=1; (c=z[i])!=0; i++){
   121522         if( c==delim ){
   121523           if( z[i+1]==delim ){
   121524             i++;
   121525           }else{
   121526             break;
   121527           }
   121528         }
   121529       }
   121530       if( c=='\'' ){
   121531         *tokenType = TK_STRING;
   121532         return i+1;
   121533       }else if( c!=0 ){
   121534         *tokenType = TK_ID;
   121535         return i+1;
   121536       }else{
   121537         *tokenType = TK_ILLEGAL;
   121538         return i;
   121539       }
   121540     }
   121541     case '.': {
   121542 #ifndef SQLITE_OMIT_FLOATING_POINT
   121543       if( !sqlite3Isdigit(z[1]) )
   121544 #endif
   121545       {
   121546         *tokenType = TK_DOT;
   121547         return 1;
   121548       }
   121549       /* If the next character is a digit, this is a floating point
   121550       ** number that begins with ".".  Fall thru into the next case */
   121551     }
   121552     case '0': case '1': case '2': case '3': case '4':
   121553     case '5': case '6': case '7': case '8': case '9': {
   121554       testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
   121555       testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
   121556       testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
   121557       testcase( z[0]=='9' );
   121558       *tokenType = TK_INTEGER;
   121559 #ifndef SQLITE_OMIT_HEX_INTEGER
   121560       if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){
   121561         for(i=3; sqlite3Isxdigit(z[i]); i++){}
   121562         return i;
   121563       }
   121564 #endif
   121565       for(i=0; sqlite3Isdigit(z[i]); i++){}
   121566 #ifndef SQLITE_OMIT_FLOATING_POINT
   121567       if( z[i]=='.' ){
   121568         i++;
   121569         while( sqlite3Isdigit(z[i]) ){ i++; }
   121570         *tokenType = TK_FLOAT;
   121571       }
   121572       if( (z[i]=='e' || z[i]=='E') &&
   121573            ( sqlite3Isdigit(z[i+1])
   121574             || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
   121575            )
   121576       ){
   121577         i += 2;
   121578         while( sqlite3Isdigit(z[i]) ){ i++; }
   121579         *tokenType = TK_FLOAT;
   121580       }
   121581 #endif
   121582       while( IdChar(z[i]) ){
   121583         *tokenType = TK_ILLEGAL;
   121584         i++;
   121585       }
   121586       return i;
   121587     }
   121588     case '[': {
   121589       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
   121590       *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
   121591       return i;
   121592     }
   121593     case '?': {
   121594       *tokenType = TK_VARIABLE;
   121595       for(i=1; sqlite3Isdigit(z[i]); i++){}
   121596       return i;
   121597     }
   121598 #ifndef SQLITE_OMIT_TCL_VARIABLE
   121599     case '$':
   121600 #endif
   121601     case '@':  /* For compatibility with MS SQL Server */
   121602     case '#':
   121603     case ':': {
   121604       int n = 0;
   121605       testcase( z[0]=='$' );  testcase( z[0]=='@' );
   121606       testcase( z[0]==':' );  testcase( z[0]=='#' );
   121607       *tokenType = TK_VARIABLE;
   121608       for(i=1; (c=z[i])!=0; i++){
   121609         if( IdChar(c) ){
   121610           n++;
   121611 #ifndef SQLITE_OMIT_TCL_VARIABLE
   121612         }else if( c=='(' && n>0 ){
   121613           do{
   121614             i++;
   121615           }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
   121616           if( c==')' ){
   121617             i++;
   121618           }else{
   121619             *tokenType = TK_ILLEGAL;
   121620           }
   121621           break;
   121622         }else if( c==':' && z[i+1]==':' ){
   121623           i++;
   121624 #endif
   121625         }else{
   121626           break;
   121627         }
   121628       }
   121629       if( n==0 ) *tokenType = TK_ILLEGAL;
   121630       return i;
   121631     }
   121632 #ifndef SQLITE_OMIT_BLOB_LITERAL
   121633     case 'x': case 'X': {
   121634       testcase( z[0]=='x' ); testcase( z[0]=='X' );
   121635       if( z[1]=='\'' ){
   121636         *tokenType = TK_BLOB;
   121637         for(i=2; sqlite3Isxdigit(z[i]); i++){}
   121638         if( z[i]!='\'' || i%2 ){
   121639           *tokenType = TK_ILLEGAL;
   121640           while( z[i] && z[i]!='\'' ){ i++; }
   121641         }
   121642         if( z[i] ) i++;
   121643         return i;
   121644       }
   121645       /* Otherwise fall through to the next case */
   121646     }
   121647 #endif
   121648     default: {
   121649       if( !IdChar(*z) ){
   121650         break;
   121651       }
   121652       for(i=1; IdChar(z[i]); i++){}
   121653       *tokenType = keywordCode((char*)z, i);
   121654       return i;
   121655     }
   121656   }
   121657   *tokenType = TK_ILLEGAL;
   121658   return 1;
   121659 }
   121660 
   121661 /*
   121662 ** Run the parser on the given SQL string.  The parser structure is
   121663 ** passed in.  An SQLITE_ status code is returned.  If an error occurs
   121664 ** then an and attempt is made to write an error message into
   121665 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
   121666 ** error message.
   121667 */
   121668 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
   121669   int nErr = 0;                   /* Number of errors encountered */
   121670   int i;                          /* Loop counter */
   121671   void *pEngine;                  /* The LEMON-generated LALR(1) parser */
   121672   int tokenType;                  /* type of the next token */
   121673   int lastTokenParsed = -1;       /* type of the previous token */
   121674   u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
   121675   sqlite3 *db = pParse->db;       /* The database connection */
   121676   int mxSqlLen;                   /* Max length of an SQL string */
   121677 
   121678 
   121679   mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
   121680   if( db->nVdbeActive==0 ){
   121681     db->u1.isInterrupted = 0;
   121682   }
   121683   pParse->rc = SQLITE_OK;
   121684   pParse->zTail = zSql;
   121685   i = 0;
   121686   assert( pzErrMsg!=0 );
   121687   pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
   121688   if( pEngine==0 ){
   121689     db->mallocFailed = 1;
   121690     return SQLITE_NOMEM;
   121691   }
   121692   assert( pParse->pNewTable==0 );
   121693   assert( pParse->pNewTrigger==0 );
   121694   assert( pParse->nVar==0 );
   121695   assert( pParse->nzVar==0 );
   121696   assert( pParse->azVar==0 );
   121697   enableLookaside = db->lookaside.bEnabled;
   121698   if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
   121699   while( !db->mallocFailed && zSql[i]!=0 ){
   121700     assert( i>=0 );
   121701     pParse->sLastToken.z = &zSql[i];
   121702     pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
   121703     i += pParse->sLastToken.n;
   121704     if( i>mxSqlLen ){
   121705       pParse->rc = SQLITE_TOOBIG;
   121706       break;
   121707     }
   121708     switch( tokenType ){
   121709       case TK_SPACE: {
   121710         if( db->u1.isInterrupted ){
   121711           sqlite3ErrorMsg(pParse, "interrupt");
   121712           pParse->rc = SQLITE_INTERRUPT;
   121713           goto abort_parse;
   121714         }
   121715         break;
   121716       }
   121717       case TK_ILLEGAL: {
   121718         sqlite3DbFree(db, *pzErrMsg);
   121719         *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
   121720                         &pParse->sLastToken);
   121721         nErr++;
   121722         goto abort_parse;
   121723       }
   121724       case TK_SEMI: {
   121725         pParse->zTail = &zSql[i];
   121726         /* Fall thru into the default case */
   121727       }
   121728       default: {
   121729         sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
   121730         lastTokenParsed = tokenType;
   121731         if( pParse->rc!=SQLITE_OK ){
   121732           goto abort_parse;
   121733         }
   121734         break;
   121735       }
   121736     }
   121737   }
   121738 abort_parse:
   121739   if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
   121740     if( lastTokenParsed!=TK_SEMI ){
   121741       sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
   121742       pParse->zTail = &zSql[i];
   121743     }
   121744     sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
   121745   }
   121746 #ifdef YYTRACKMAXSTACKDEPTH
   121747   sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
   121748       sqlite3ParserStackPeak(pEngine)
   121749   );
   121750 #endif /* YYDEBUG */
   121751   sqlite3ParserFree(pEngine, sqlite3_free);
   121752   db->lookaside.bEnabled = enableLookaside;
   121753   if( db->mallocFailed ){
   121754     pParse->rc = SQLITE_NOMEM;
   121755   }
   121756   if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
   121757     sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
   121758   }
   121759   assert( pzErrMsg!=0 );
   121760   if( pParse->zErrMsg ){
   121761     *pzErrMsg = pParse->zErrMsg;
   121762     sqlite3_log(pParse->rc, "%s", *pzErrMsg);
   121763     pParse->zErrMsg = 0;
   121764     nErr++;
   121765   }
   121766   if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
   121767     sqlite3VdbeDelete(pParse->pVdbe);
   121768     pParse->pVdbe = 0;
   121769   }
   121770 #ifndef SQLITE_OMIT_SHARED_CACHE
   121771   if( pParse->nested==0 ){
   121772     sqlite3DbFree(db, pParse->aTableLock);
   121773     pParse->aTableLock = 0;
   121774     pParse->nTableLock = 0;
   121775   }
   121776 #endif
   121777 #ifndef SQLITE_OMIT_VIRTUALTABLE
   121778   sqlite3_free(pParse->apVtabLock);
   121779 #endif
   121780 
   121781   if( !IN_DECLARE_VTAB ){
   121782     /* If the pParse->declareVtab flag is set, do not delete any table
   121783     ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
   121784     ** will take responsibility for freeing the Table structure.
   121785     */
   121786     sqlite3DeleteTable(db, pParse->pNewTable);
   121787   }
   121788 
   121789   if( pParse->bFreeWith ) sqlite3WithDelete(db, pParse->pWith);
   121790   sqlite3DeleteTrigger(db, pParse->pNewTrigger);
   121791   for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
   121792   sqlite3DbFree(db, pParse->azVar);
   121793   while( pParse->pAinc ){
   121794     AutoincInfo *p = pParse->pAinc;
   121795     pParse->pAinc = p->pNext;
   121796     sqlite3DbFree(db, p);
   121797   }
   121798   while( pParse->pZombieTab ){
   121799     Table *p = pParse->pZombieTab;
   121800     pParse->pZombieTab = p->pNextZombie;
   121801     sqlite3DeleteTable(db, p);
   121802   }
   121803   if( nErr>0 && pParse->rc==SQLITE_OK ){
   121804     pParse->rc = SQLITE_ERROR;
   121805   }
   121806   return nErr;
   121807 }
   121808 
   121809 /************** End of tokenize.c ********************************************/
   121810 /************** Begin file complete.c ****************************************/
   121811 /*
   121812 ** 2001 September 15
   121813 **
   121814 ** The author disclaims copyright to this source code.  In place of
   121815 ** a legal notice, here is a blessing:
   121816 **
   121817 **    May you do good and not evil.
   121818 **    May you find forgiveness for yourself and forgive others.
   121819 **    May you share freely, never taking more than you give.
   121820 **
   121821 *************************************************************************
   121822 ** An tokenizer for SQL
   121823 **
   121824 ** This file contains C code that implements the sqlite3_complete() API.
   121825 ** This code used to be part of the tokenizer.c source file.  But by
   121826 ** separating it out, the code will be automatically omitted from
   121827 ** static links that do not use it.
   121828 */
   121829 #ifndef SQLITE_OMIT_COMPLETE
   121830 
   121831 /*
   121832 ** This is defined in tokenize.c.  We just have to import the definition.
   121833 */
   121834 #ifndef SQLITE_AMALGAMATION
   121835 #ifdef SQLITE_ASCII
   121836 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
   121837 #endif
   121838 #ifdef SQLITE_EBCDIC
   121839 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
   121840 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
   121841 #endif
   121842 #endif /* SQLITE_AMALGAMATION */
   121843 
   121844 
   121845 /*
   121846 ** Token types used by the sqlite3_complete() routine.  See the header
   121847 ** comments on that procedure for additional information.
   121848 */
   121849 #define tkSEMI    0
   121850 #define tkWS      1
   121851 #define tkOTHER   2
   121852 #ifndef SQLITE_OMIT_TRIGGER
   121853 #define tkEXPLAIN 3
   121854 #define tkCREATE  4
   121855 #define tkTEMP    5
   121856 #define tkTRIGGER 6
   121857 #define tkEND     7
   121858 #endif
   121859 
   121860 /*
   121861 ** Return TRUE if the given SQL string ends in a semicolon.
   121862 **
   121863 ** Special handling is require for CREATE TRIGGER statements.
   121864 ** Whenever the CREATE TRIGGER keywords are seen, the statement
   121865 ** must end with ";END;".
   121866 **
   121867 ** This implementation uses a state machine with 8 states:
   121868 **
   121869 **   (0) INVALID   We have not yet seen a non-whitespace character.
   121870 **
   121871 **   (1) START     At the beginning or end of an SQL statement.  This routine
   121872 **                 returns 1 if it ends in the START state and 0 if it ends
   121873 **                 in any other state.
   121874 **
   121875 **   (2) NORMAL    We are in the middle of statement which ends with a single
   121876 **                 semicolon.
   121877 **
   121878 **   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of
   121879 **                 a statement.
   121880 **
   121881 **   (4) CREATE    The keyword CREATE has been seen at the beginning of a
   121882 **                 statement, possibly preceeded by EXPLAIN and/or followed by
   121883 **                 TEMP or TEMPORARY
   121884 **
   121885 **   (5) TRIGGER   We are in the middle of a trigger definition that must be
   121886 **                 ended by a semicolon, the keyword END, and another semicolon.
   121887 **
   121888 **   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
   121889 **                 the end of a trigger definition.
   121890 **
   121891 **   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
   121892 **                 of a trigger difinition.
   121893 **
   121894 ** Transitions between states above are determined by tokens extracted
   121895 ** from the input.  The following tokens are significant:
   121896 **
   121897 **   (0) tkSEMI      A semicolon.
   121898 **   (1) tkWS        Whitespace.
   121899 **   (2) tkOTHER     Any other SQL token.
   121900 **   (3) tkEXPLAIN   The "explain" keyword.
   121901 **   (4) tkCREATE    The "create" keyword.
   121902 **   (5) tkTEMP      The "temp" or "temporary" keyword.
   121903 **   (6) tkTRIGGER   The "trigger" keyword.
   121904 **   (7) tkEND       The "end" keyword.
   121905 **
   121906 ** Whitespace never causes a state transition and is always ignored.
   121907 ** This means that a SQL string of all whitespace is invalid.
   121908 **
   121909 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
   121910 ** to recognize the end of a trigger can be omitted.  All we have to do
   121911 ** is look for a semicolon that is not part of an string or comment.
   121912 */
   121913 SQLITE_API int sqlite3_complete(const char *zSql){
   121914   u8 state = 0;   /* Current state, using numbers defined in header comment */
   121915   u8 token;       /* Value of the next token */
   121916 
   121917 #ifndef SQLITE_OMIT_TRIGGER
   121918   /* A complex statement machine used to detect the end of a CREATE TRIGGER
   121919   ** statement.  This is the normal case.
   121920   */
   121921   static const u8 trans[8][8] = {
   121922                      /* Token:                                                */
   121923      /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
   121924      /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
   121925      /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
   121926      /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
   121927      /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
   121928      /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
   121929      /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
   121930      /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
   121931      /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
   121932   };
   121933 #else
   121934   /* If triggers are not supported by this compile then the statement machine
   121935   ** used to detect the end of a statement is much simplier
   121936   */
   121937   static const u8 trans[3][3] = {
   121938                      /* Token:           */
   121939      /* State:       **  SEMI  WS  OTHER */
   121940      /* 0 INVALID: */ {    1,  0,     2, },
   121941      /* 1   START: */ {    1,  1,     2, },
   121942      /* 2  NORMAL: */ {    1,  2,     2, },
   121943   };
   121944 #endif /* SQLITE_OMIT_TRIGGER */
   121945 
   121946   while( *zSql ){
   121947     switch( *zSql ){
   121948       case ';': {  /* A semicolon */
   121949         token = tkSEMI;
   121950         break;
   121951       }
   121952       case ' ':
   121953       case '\r':
   121954       case '\t':
   121955       case '\n':
   121956       case '\f': {  /* White space is ignored */
   121957         token = tkWS;
   121958         break;
   121959       }
   121960       case '/': {   /* C-style comments */
   121961         if( zSql[1]!='*' ){
   121962           token = tkOTHER;
   121963           break;
   121964         }
   121965         zSql += 2;
   121966         while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
   121967         if( zSql[0]==0 ) return 0;
   121968         zSql++;
   121969         token = tkWS;
   121970         break;
   121971       }
   121972       case '-': {   /* SQL-style comments from "--" to end of line */
   121973         if( zSql[1]!='-' ){
   121974           token = tkOTHER;
   121975           break;
   121976         }
   121977         while( *zSql && *zSql!='\n' ){ zSql++; }
   121978         if( *zSql==0 ) return state==1;
   121979         token = tkWS;
   121980         break;
   121981       }
   121982       case '[': {   /* Microsoft-style identifiers in [...] */
   121983         zSql++;
   121984         while( *zSql && *zSql!=']' ){ zSql++; }
   121985         if( *zSql==0 ) return 0;
   121986         token = tkOTHER;
   121987         break;
   121988       }
   121989       case '`':     /* Grave-accent quoted symbols used by MySQL */
   121990       case '"':     /* single- and double-quoted strings */
   121991       case '\'': {
   121992         int c = *zSql;
   121993         zSql++;
   121994         while( *zSql && *zSql!=c ){ zSql++; }
   121995         if( *zSql==0 ) return 0;
   121996         token = tkOTHER;
   121997         break;
   121998       }
   121999       default: {
   122000 #ifdef SQLITE_EBCDIC
   122001         unsigned char c;
   122002 #endif
   122003         if( IdChar((u8)*zSql) ){
   122004           /* Keywords and unquoted identifiers */
   122005           int nId;
   122006           for(nId=1; IdChar(zSql[nId]); nId++){}
   122007 #ifdef SQLITE_OMIT_TRIGGER
   122008           token = tkOTHER;
   122009 #else
   122010           switch( *zSql ){
   122011             case 'c': case 'C': {
   122012               if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
   122013                 token = tkCREATE;
   122014               }else{
   122015                 token = tkOTHER;
   122016               }
   122017               break;
   122018             }
   122019             case 't': case 'T': {
   122020               if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
   122021                 token = tkTRIGGER;
   122022               }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
   122023                 token = tkTEMP;
   122024               }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
   122025                 token = tkTEMP;
   122026               }else{
   122027                 token = tkOTHER;
   122028               }
   122029               break;
   122030             }
   122031             case 'e':  case 'E': {
   122032               if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
   122033                 token = tkEND;
   122034               }else
   122035 #ifndef SQLITE_OMIT_EXPLAIN
   122036               if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
   122037                 token = tkEXPLAIN;
   122038               }else
   122039 #endif
   122040               {
   122041                 token = tkOTHER;
   122042               }
   122043               break;
   122044             }
   122045             default: {
   122046               token = tkOTHER;
   122047               break;
   122048             }
   122049           }
   122050 #endif /* SQLITE_OMIT_TRIGGER */
   122051           zSql += nId-1;
   122052         }else{
   122053           /* Operators and special symbols */
   122054           token = tkOTHER;
   122055         }
   122056         break;
   122057       }
   122058     }
   122059     state = trans[state][token];
   122060     zSql++;
   122061   }
   122062   return state==1;
   122063 }
   122064 
   122065 #ifndef SQLITE_OMIT_UTF16
   122066 /*
   122067 ** This routine is the same as the sqlite3_complete() routine described
   122068 ** above, except that the parameter is required to be UTF-16 encoded, not
   122069 ** UTF-8.
   122070 */
   122071 SQLITE_API int sqlite3_complete16(const void *zSql){
   122072   sqlite3_value *pVal;
   122073   char const *zSql8;
   122074   int rc = SQLITE_NOMEM;
   122075 
   122076 #ifndef SQLITE_OMIT_AUTOINIT
   122077   rc = sqlite3_initialize();
   122078   if( rc ) return rc;
   122079 #endif
   122080   pVal = sqlite3ValueNew(0);
   122081   sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
   122082   zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
   122083   if( zSql8 ){
   122084     rc = sqlite3_complete(zSql8);
   122085   }else{
   122086     rc = SQLITE_NOMEM;
   122087   }
   122088   sqlite3ValueFree(pVal);
   122089   return sqlite3ApiExit(0, rc);
   122090 }
   122091 #endif /* SQLITE_OMIT_UTF16 */
   122092 #endif /* SQLITE_OMIT_COMPLETE */
   122093 
   122094 /************** End of complete.c ********************************************/
   122095 /************** Begin file main.c ********************************************/
   122096 /*
   122097 ** 2001 September 15
   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 ** Main file for the SQLite library.  The routines in this file
   122108 ** implement the programmer interface to the library.  Routines in
   122109 ** other files are for internal use by SQLite and should not be
   122110 ** accessed by users of the library.
   122111 */
   122112 
   122113 #ifdef SQLITE_ENABLE_FTS3
   122114 /************** Include fts3.h in the middle of main.c ***********************/
   122115 /************** Begin file fts3.h ********************************************/
   122116 /*
   122117 ** 2006 Oct 10
   122118 **
   122119 ** The author disclaims copyright to this source code.  In place of
   122120 ** a legal notice, here is a blessing:
   122121 **
   122122 **    May you do good and not evil.
   122123 **    May you find forgiveness for yourself and forgive others.
   122124 **    May you share freely, never taking more than you give.
   122125 **
   122126 ******************************************************************************
   122127 **
   122128 ** This header file is used by programs that want to link against the
   122129 ** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
   122130 */
   122131 
   122132 #if 0
   122133 extern "C" {
   122134 #endif  /* __cplusplus */
   122135 
   122136 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
   122137 
   122138 #if 0
   122139 }  /* extern "C" */
   122140 #endif  /* __cplusplus */
   122141 
   122142 /************** End of fts3.h ************************************************/
   122143 /************** Continuing where we left off in main.c ***********************/
   122144 #endif
   122145 #ifdef SQLITE_ENABLE_RTREE
   122146 /************** Include rtree.h in the middle of main.c **********************/
   122147 /************** Begin file rtree.h *******************************************/
   122148 /*
   122149 ** 2008 May 26
   122150 **
   122151 ** The author disclaims copyright to this source code.  In place of
   122152 ** a legal notice, here is a blessing:
   122153 **
   122154 **    May you do good and not evil.
   122155 **    May you find forgiveness for yourself and forgive others.
   122156 **    May you share freely, never taking more than you give.
   122157 **
   122158 ******************************************************************************
   122159 **
   122160 ** This header file is used by programs that want to link against the
   122161 ** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
   122162 */
   122163 
   122164 #if 0
   122165 extern "C" {
   122166 #endif  /* __cplusplus */
   122167 
   122168 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
   122169 
   122170 #if 0
   122171 }  /* extern "C" */
   122172 #endif  /* __cplusplus */
   122173 
   122174 /************** End of rtree.h ***********************************************/
   122175 /************** Continuing where we left off in main.c ***********************/
   122176 #endif
   122177 #ifdef SQLITE_ENABLE_ICU
   122178 /************** Include sqliteicu.h in the middle of main.c ******************/
   122179 /************** Begin file sqliteicu.h ***************************************/
   122180 /*
   122181 ** 2008 May 26
   122182 **
   122183 ** The author disclaims copyright to this source code.  In place of
   122184 ** a legal notice, here is a blessing:
   122185 **
   122186 **    May you do good and not evil.
   122187 **    May you find forgiveness for yourself and forgive others.
   122188 **    May you share freely, never taking more than you give.
   122189 **
   122190 ******************************************************************************
   122191 **
   122192 ** This header file is used by programs that want to link against the
   122193 ** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
   122194 */
   122195 
   122196 #if 0
   122197 extern "C" {
   122198 #endif  /* __cplusplus */
   122199 
   122200 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
   122201 
   122202 #if 0
   122203 }  /* extern "C" */
   122204 #endif  /* __cplusplus */
   122205 
   122206 
   122207 /************** End of sqliteicu.h *******************************************/
   122208 /************** Continuing where we left off in main.c ***********************/
   122209 #endif
   122210 
   122211 #ifndef SQLITE_AMALGAMATION
   122212 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
   122213 ** contains the text of SQLITE_VERSION macro.
   122214 */
   122215 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
   122216 #endif
   122217 
   122218 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
   122219 ** a pointer to the to the sqlite3_version[] string constant.
   122220 */
   122221 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
   122222 
   122223 /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
   122224 ** pointer to a string constant whose value is the same as the
   122225 ** SQLITE_SOURCE_ID C preprocessor macro.
   122226 */
   122227 SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
   122228 
   122229 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
   122230 ** returns an integer equal to SQLITE_VERSION_NUMBER.
   122231 */
   122232 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
   122233 
   122234 /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
   122235 ** zero if and only if SQLite was compiled with mutexing code omitted due to
   122236 ** the SQLITE_THREADSAFE compile-time option being set to 0.
   122237 */
   122238 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
   122239 
   122240 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
   122241 /*
   122242 ** If the following function pointer is not NULL and if
   122243 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
   122244 ** I/O active are written using this function.  These messages
   122245 ** are intended for debugging activity only.
   122246 */
   122247 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
   122248 #endif
   122249 
   122250 /*
   122251 ** If the following global variable points to a string which is the
   122252 ** name of a directory, then that directory will be used to store
   122253 ** temporary files.
   122254 **
   122255 ** See also the "PRAGMA temp_store_directory" SQL command.
   122256 */
   122257 SQLITE_API char *sqlite3_temp_directory = 0;
   122258 
   122259 /*
   122260 ** If the following global variable points to a string which is the
   122261 ** name of a directory, then that directory will be used to store
   122262 ** all database files specified with a relative pathname.
   122263 **
   122264 ** See also the "PRAGMA data_store_directory" SQL command.
   122265 */
   122266 SQLITE_API char *sqlite3_data_directory = 0;
   122267 
   122268 /*
   122269 ** Initialize SQLite.
   122270 **
   122271 ** This routine must be called to initialize the memory allocation,
   122272 ** VFS, and mutex subsystems prior to doing any serious work with
   122273 ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
   122274 ** this routine will be called automatically by key routines such as
   122275 ** sqlite3_open().
   122276 **
   122277 ** This routine is a no-op except on its very first call for the process,
   122278 ** or for the first call after a call to sqlite3_shutdown.
   122279 **
   122280 ** The first thread to call this routine runs the initialization to
   122281 ** completion.  If subsequent threads call this routine before the first
   122282 ** thread has finished the initialization process, then the subsequent
   122283 ** threads must block until the first thread finishes with the initialization.
   122284 **
   122285 ** The first thread might call this routine recursively.  Recursive
   122286 ** calls to this routine should not block, of course.  Otherwise the
   122287 ** initialization process would never complete.
   122288 **
   122289 ** Let X be the first thread to enter this routine.  Let Y be some other
   122290 ** thread.  Then while the initial invocation of this routine by X is
   122291 ** incomplete, it is required that:
   122292 **
   122293 **    *  Calls to this routine from Y must block until the outer-most
   122294 **       call by X completes.
   122295 **
   122296 **    *  Recursive calls to this routine from thread X return immediately
   122297 **       without blocking.
   122298 */
   122299 SQLITE_API int sqlite3_initialize(void){
   122300   MUTEX_LOGIC( sqlite3_mutex *pMaster; )       /* The main static mutex */
   122301   int rc;                                      /* Result code */
   122302 #ifdef SQLITE_EXTRA_INIT
   122303   int bRunExtraInit = 0;                       /* Extra initialization needed */
   122304 #endif
   122305 
   122306 #ifdef SQLITE_OMIT_WSD
   122307   rc = sqlite3_wsd_init(4096, 24);
   122308   if( rc!=SQLITE_OK ){
   122309     return rc;
   122310   }
   122311 #endif
   122312 
   122313   /* If SQLite is already completely initialized, then this call
   122314   ** to sqlite3_initialize() should be a no-op.  But the initialization
   122315   ** must be complete.  So isInit must not be set until the very end
   122316   ** of this routine.
   122317   */
   122318   if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
   122319 
   122320   /* Make sure the mutex subsystem is initialized.  If unable to
   122321   ** initialize the mutex subsystem, return early with the error.
   122322   ** If the system is so sick that we are unable to allocate a mutex,
   122323   ** there is not much SQLite is going to be able to do.
   122324   **
   122325   ** The mutex subsystem must take care of serializing its own
   122326   ** initialization.
   122327   */
   122328   rc = sqlite3MutexInit();
   122329   if( rc ) return rc;
   122330 
   122331   /* Initialize the malloc() system and the recursive pInitMutex mutex.
   122332   ** This operation is protected by the STATIC_MASTER mutex.  Note that
   122333   ** MutexAlloc() is called for a static mutex prior to initializing the
   122334   ** malloc subsystem - this implies that the allocation of a static
   122335   ** mutex must not require support from the malloc subsystem.
   122336   */
   122337   MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
   122338   sqlite3_mutex_enter(pMaster);
   122339   sqlite3GlobalConfig.isMutexInit = 1;
   122340   if( !sqlite3GlobalConfig.isMallocInit ){
   122341     rc = sqlite3MallocInit();
   122342   }
   122343   if( rc==SQLITE_OK ){
   122344     sqlite3GlobalConfig.isMallocInit = 1;
   122345     if( !sqlite3GlobalConfig.pInitMutex ){
   122346       sqlite3GlobalConfig.pInitMutex =
   122347            sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
   122348       if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
   122349         rc = SQLITE_NOMEM;
   122350       }
   122351     }
   122352   }
   122353   if( rc==SQLITE_OK ){
   122354     sqlite3GlobalConfig.nRefInitMutex++;
   122355   }
   122356   sqlite3_mutex_leave(pMaster);
   122357 
   122358   /* If rc is not SQLITE_OK at this point, then either the malloc
   122359   ** subsystem could not be initialized or the system failed to allocate
   122360   ** the pInitMutex mutex. Return an error in either case.  */
   122361   if( rc!=SQLITE_OK ){
   122362     return rc;
   122363   }
   122364 
   122365   /* Do the rest of the initialization under the recursive mutex so
   122366   ** that we will be able to handle recursive calls into
   122367   ** sqlite3_initialize().  The recursive calls normally come through
   122368   ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
   122369   ** recursive calls might also be possible.
   122370   **
   122371   ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
   122372   ** to the xInit method, so the xInit method need not be threadsafe.
   122373   **
   122374   ** The following mutex is what serializes access to the appdef pcache xInit
   122375   ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
   122376   ** call to sqlite3PcacheInitialize().
   122377   */
   122378   sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
   122379   if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
   122380     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
   122381     sqlite3GlobalConfig.inProgress = 1;
   122382     memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
   122383     sqlite3RegisterGlobalFunctions();
   122384     if( sqlite3GlobalConfig.isPCacheInit==0 ){
   122385       rc = sqlite3PcacheInitialize();
   122386     }
   122387     if( rc==SQLITE_OK ){
   122388       sqlite3GlobalConfig.isPCacheInit = 1;
   122389       rc = sqlite3OsInit();
   122390     }
   122391     if( rc==SQLITE_OK ){
   122392       sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
   122393           sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
   122394       sqlite3GlobalConfig.isInit = 1;
   122395 #ifdef SQLITE_EXTRA_INIT
   122396       bRunExtraInit = 1;
   122397 #endif
   122398     }
   122399     sqlite3GlobalConfig.inProgress = 0;
   122400   }
   122401   sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
   122402 
   122403   /* Go back under the static mutex and clean up the recursive
   122404   ** mutex to prevent a resource leak.
   122405   */
   122406   sqlite3_mutex_enter(pMaster);
   122407   sqlite3GlobalConfig.nRefInitMutex--;
   122408   if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
   122409     assert( sqlite3GlobalConfig.nRefInitMutex==0 );
   122410     sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
   122411     sqlite3GlobalConfig.pInitMutex = 0;
   122412   }
   122413   sqlite3_mutex_leave(pMaster);
   122414 
   122415   /* The following is just a sanity check to make sure SQLite has
   122416   ** been compiled correctly.  It is important to run this code, but
   122417   ** we don't want to run it too often and soak up CPU cycles for no
   122418   ** reason.  So we run it once during initialization.
   122419   */
   122420 #ifndef NDEBUG
   122421 #ifndef SQLITE_OMIT_FLOATING_POINT
   122422   /* This section of code's only "output" is via assert() statements. */
   122423   if ( rc==SQLITE_OK ){
   122424     u64 x = (((u64)1)<<63)-1;
   122425     double y;
   122426     assert(sizeof(x)==8);
   122427     assert(sizeof(x)==sizeof(y));
   122428     memcpy(&y, &x, 8);
   122429     assert( sqlite3IsNaN(y) );
   122430   }
   122431 #endif
   122432 #endif
   122433 
   122434   /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
   122435   ** compile-time option.
   122436   */
   122437 #ifdef SQLITE_EXTRA_INIT
   122438   if( bRunExtraInit ){
   122439     int SQLITE_EXTRA_INIT(const char*);
   122440     rc = SQLITE_EXTRA_INIT(0);
   122441   }
   122442 #endif
   122443 
   122444   return rc;
   122445 }
   122446 
   122447 /*
   122448 ** Undo the effects of sqlite3_initialize().  Must not be called while
   122449 ** there are outstanding database connections or memory allocations or
   122450 ** while any part of SQLite is otherwise in use in any thread.  This
   122451 ** routine is not threadsafe.  But it is safe to invoke this routine
   122452 ** on when SQLite is already shut down.  If SQLite is already shut down
   122453 ** when this routine is invoked, then this routine is a harmless no-op.
   122454 */
   122455 SQLITE_API int sqlite3_shutdown(void){
   122456   if( sqlite3GlobalConfig.isInit ){
   122457 #ifdef SQLITE_EXTRA_SHUTDOWN
   122458     void SQLITE_EXTRA_SHUTDOWN(void);
   122459     SQLITE_EXTRA_SHUTDOWN();
   122460 #endif
   122461     sqlite3_os_end();
   122462     sqlite3_reset_auto_extension();
   122463     sqlite3GlobalConfig.isInit = 0;
   122464   }
   122465   if( sqlite3GlobalConfig.isPCacheInit ){
   122466     sqlite3PcacheShutdown();
   122467     sqlite3GlobalConfig.isPCacheInit = 0;
   122468   }
   122469   if( sqlite3GlobalConfig.isMallocInit ){
   122470     sqlite3MallocEnd();
   122471     sqlite3GlobalConfig.isMallocInit = 0;
   122472 
   122473 #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
   122474     /* The heap subsystem has now been shutdown and these values are supposed
   122475     ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
   122476     ** which would rely on that heap subsystem; therefore, make sure these
   122477     ** values cannot refer to heap memory that was just invalidated when the
   122478     ** heap subsystem was shutdown.  This is only done if the current call to
   122479     ** this function resulted in the heap subsystem actually being shutdown.
   122480     */
   122481     sqlite3_data_directory = 0;
   122482     sqlite3_temp_directory = 0;
   122483 #endif
   122484   }
   122485   if( sqlite3GlobalConfig.isMutexInit ){
   122486     sqlite3MutexEnd();
   122487     sqlite3GlobalConfig.isMutexInit = 0;
   122488   }
   122489 
   122490   return SQLITE_OK;
   122491 }
   122492 
   122493 /*
   122494 ** This API allows applications to modify the global configuration of
   122495 ** the SQLite library at run-time.
   122496 **
   122497 ** This routine should only be called when there are no outstanding
   122498 ** database connections or memory allocations.  This routine is not
   122499 ** threadsafe.  Failure to heed these warnings can lead to unpredictable
   122500 ** behavior.
   122501 */
   122502 SQLITE_API int sqlite3_config(int op, ...){
   122503   va_list ap;
   122504   int rc = SQLITE_OK;
   122505 
   122506   /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
   122507   ** the SQLite library is in use. */
   122508   if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
   122509 
   122510   va_start(ap, op);
   122511   switch( op ){
   122512 
   122513     /* Mutex configuration options are only available in a threadsafe
   122514     ** compile.
   122515     */
   122516 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
   122517     case SQLITE_CONFIG_SINGLETHREAD: {
   122518       /* Disable all mutexing */
   122519       sqlite3GlobalConfig.bCoreMutex = 0;
   122520       sqlite3GlobalConfig.bFullMutex = 0;
   122521       break;
   122522     }
   122523     case SQLITE_CONFIG_MULTITHREAD: {
   122524       /* Disable mutexing of database connections */
   122525       /* Enable mutexing of core data structures */
   122526       sqlite3GlobalConfig.bCoreMutex = 1;
   122527       sqlite3GlobalConfig.bFullMutex = 0;
   122528       break;
   122529     }
   122530     case SQLITE_CONFIG_SERIALIZED: {
   122531       /* Enable all mutexing */
   122532       sqlite3GlobalConfig.bCoreMutex = 1;
   122533       sqlite3GlobalConfig.bFullMutex = 1;
   122534       break;
   122535     }
   122536     case SQLITE_CONFIG_MUTEX: {
   122537       /* Specify an alternative mutex implementation */
   122538       sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
   122539       break;
   122540     }
   122541     case SQLITE_CONFIG_GETMUTEX: {
   122542       /* Retrieve the current mutex implementation */
   122543       *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
   122544       break;
   122545     }
   122546 #endif
   122547 
   122548 
   122549     case SQLITE_CONFIG_MALLOC: {
   122550       /* Specify an alternative malloc implementation */
   122551       sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
   122552       break;
   122553     }
   122554     case SQLITE_CONFIG_GETMALLOC: {
   122555       /* Retrieve the current malloc() implementation */
   122556       if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
   122557       *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
   122558       break;
   122559     }
   122560     case SQLITE_CONFIG_MEMSTATUS: {
   122561       /* Enable or disable the malloc status collection */
   122562       sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
   122563       break;
   122564     }
   122565     case SQLITE_CONFIG_SCRATCH: {
   122566       /* Designate a buffer for scratch memory space */
   122567       sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
   122568       sqlite3GlobalConfig.szScratch = va_arg(ap, int);
   122569       sqlite3GlobalConfig.nScratch = va_arg(ap, int);
   122570       break;
   122571     }
   122572     case SQLITE_CONFIG_PAGECACHE: {
   122573       /* Designate a buffer for page cache memory space */
   122574       sqlite3GlobalConfig.pPage = va_arg(ap, void*);
   122575       sqlite3GlobalConfig.szPage = va_arg(ap, int);
   122576       sqlite3GlobalConfig.nPage = va_arg(ap, int);
   122577       break;
   122578     }
   122579 
   122580     case SQLITE_CONFIG_PCACHE: {
   122581       /* no-op */
   122582       break;
   122583     }
   122584     case SQLITE_CONFIG_GETPCACHE: {
   122585       /* now an error */
   122586       rc = SQLITE_ERROR;
   122587       break;
   122588     }
   122589 
   122590     case SQLITE_CONFIG_PCACHE2: {
   122591       /* Specify an alternative page cache implementation */
   122592       sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
   122593       break;
   122594     }
   122595     case SQLITE_CONFIG_GETPCACHE2: {
   122596       if( sqlite3GlobalConfig.pcache2.xInit==0 ){
   122597         sqlite3PCacheSetDefault();
   122598       }
   122599       *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
   122600       break;
   122601     }
   122602 
   122603 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
   122604     case SQLITE_CONFIG_HEAP: {
   122605       /* Designate a buffer for heap memory space */
   122606       sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
   122607       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
   122608       sqlite3GlobalConfig.mnReq = va_arg(ap, int);
   122609 
   122610       if( sqlite3GlobalConfig.mnReq<1 ){
   122611         sqlite3GlobalConfig.mnReq = 1;
   122612       }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
   122613         /* cap min request size at 2^12 */
   122614         sqlite3GlobalConfig.mnReq = (1<<12);
   122615       }
   122616 
   122617       if( sqlite3GlobalConfig.pHeap==0 ){
   122618         /* If the heap pointer is NULL, then restore the malloc implementation
   122619         ** back to NULL pointers too.  This will cause the malloc to go
   122620         ** back to its default implementation when sqlite3_initialize() is
   122621         ** run.
   122622         */
   122623         memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
   122624       }else{
   122625         /* The heap pointer is not NULL, then install one of the
   122626         ** mem5.c/mem3.c methods.  The enclosing #if guarantees at
   122627         ** least one of these methods is currently enabled.
   122628         */
   122629 #ifdef SQLITE_ENABLE_MEMSYS3
   122630         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
   122631 #endif
   122632 #ifdef SQLITE_ENABLE_MEMSYS5
   122633         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
   122634 #endif
   122635       }
   122636       break;
   122637     }
   122638 #endif
   122639 
   122640     case SQLITE_CONFIG_LOOKASIDE: {
   122641       sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
   122642       sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
   122643       break;
   122644     }
   122645 
   122646     /* Record a pointer to the logger function and its first argument.
   122647     ** The default is NULL.  Logging is disabled if the function pointer is
   122648     ** NULL.
   122649     */
   122650     case SQLITE_CONFIG_LOG: {
   122651       /* MSVC is picky about pulling func ptrs from va lists.
   122652       ** http://support.microsoft.com/kb/47961
   122653       ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
   122654       */
   122655       typedef void(*LOGFUNC_t)(void*,int,const char*);
   122656       sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
   122657       sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
   122658       break;
   122659     }
   122660 
   122661     case SQLITE_CONFIG_URI: {
   122662       sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
   122663       break;
   122664     }
   122665 
   122666     case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
   122667       sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
   122668       break;
   122669     }
   122670 
   122671 #ifdef SQLITE_ENABLE_SQLLOG
   122672     case SQLITE_CONFIG_SQLLOG: {
   122673       typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
   122674       sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
   122675       sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
   122676       break;
   122677     }
   122678 #endif
   122679 
   122680     case SQLITE_CONFIG_MMAP_SIZE: {
   122681       sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
   122682       sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
   122683       if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
   122684         mxMmap = SQLITE_MAX_MMAP_SIZE;
   122685       }
   122686       sqlite3GlobalConfig.mxMmap = mxMmap;
   122687       if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
   122688       if( szMmap>mxMmap) szMmap = mxMmap;
   122689       sqlite3GlobalConfig.szMmap = szMmap;
   122690       break;
   122691     }
   122692 
   122693 #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC)
   122694     case SQLITE_CONFIG_WIN32_HEAPSIZE: {
   122695       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
   122696       break;
   122697     }
   122698 #endif
   122699 
   122700     default: {
   122701       rc = SQLITE_ERROR;
   122702       break;
   122703     }
   122704   }
   122705   va_end(ap);
   122706   return rc;
   122707 }
   122708 
   122709 /*
   122710 ** Set up the lookaside buffers for a database connection.
   122711 ** Return SQLITE_OK on success.
   122712 ** If lookaside is already active, return SQLITE_BUSY.
   122713 **
   122714 ** The sz parameter is the number of bytes in each lookaside slot.
   122715 ** The cnt parameter is the number of slots.  If pStart is NULL the
   122716 ** space for the lookaside memory is obtained from sqlite3_malloc().
   122717 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
   122718 ** the lookaside memory.
   122719 */
   122720 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
   122721   void *pStart;
   122722   if( db->lookaside.nOut ){
   122723     return SQLITE_BUSY;
   122724   }
   122725   /* Free any existing lookaside buffer for this handle before
   122726   ** allocating a new one so we don't have to have space for
   122727   ** both at the same time.
   122728   */
   122729   if( db->lookaside.bMalloced ){
   122730     sqlite3_free(db->lookaside.pStart);
   122731   }
   122732   /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
   122733   ** than a pointer to be useful.
   122734   */
   122735   sz = ROUNDDOWN8(sz);  /* IMP: R-33038-09382 */
   122736   if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
   122737   if( cnt<0 ) cnt = 0;
   122738   if( sz==0 || cnt==0 ){
   122739     sz = 0;
   122740     pStart = 0;
   122741   }else if( pBuf==0 ){
   122742     sqlite3BeginBenignMalloc();
   122743     pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
   122744     sqlite3EndBenignMalloc();
   122745     if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
   122746   }else{
   122747     pStart = pBuf;
   122748   }
   122749   db->lookaside.pStart = pStart;
   122750   db->lookaside.pFree = 0;
   122751   db->lookaside.sz = (u16)sz;
   122752   if( pStart ){
   122753     int i;
   122754     LookasideSlot *p;
   122755     assert( sz > (int)sizeof(LookasideSlot*) );
   122756     p = (LookasideSlot*)pStart;
   122757     for(i=cnt-1; i>=0; i--){
   122758       p->pNext = db->lookaside.pFree;
   122759       db->lookaside.pFree = p;
   122760       p = (LookasideSlot*)&((u8*)p)[sz];
   122761     }
   122762     db->lookaside.pEnd = p;
   122763     db->lookaside.bEnabled = 1;
   122764     db->lookaside.bMalloced = pBuf==0 ?1:0;
   122765   }else{
   122766     db->lookaside.pStart = db;
   122767     db->lookaside.pEnd = db;
   122768     db->lookaside.bEnabled = 0;
   122769     db->lookaside.bMalloced = 0;
   122770   }
   122771   return SQLITE_OK;
   122772 }
   122773 
   122774 /*
   122775 ** Return the mutex associated with a database connection.
   122776 */
   122777 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
   122778   return db->mutex;
   122779 }
   122780 
   122781 /*
   122782 ** Free up as much memory as we can from the given database
   122783 ** connection.
   122784 */
   122785 SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
   122786   int i;
   122787   sqlite3_mutex_enter(db->mutex);
   122788   sqlite3BtreeEnterAll(db);
   122789   for(i=0; i<db->nDb; i++){
   122790     Btree *pBt = db->aDb[i].pBt;
   122791     if( pBt ){
   122792       Pager *pPager = sqlite3BtreePager(pBt);
   122793       sqlite3PagerShrink(pPager);
   122794     }
   122795   }
   122796   sqlite3BtreeLeaveAll(db);
   122797   sqlite3_mutex_leave(db->mutex);
   122798   return SQLITE_OK;
   122799 }
   122800 
   122801 /*
   122802 ** Configuration settings for an individual database connection
   122803 */
   122804 SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
   122805   va_list ap;
   122806   int rc;
   122807   va_start(ap, op);
   122808   switch( op ){
   122809     case SQLITE_DBCONFIG_LOOKASIDE: {
   122810       void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
   122811       int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
   122812       int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
   122813       rc = setupLookaside(db, pBuf, sz, cnt);
   122814       break;
   122815     }
   122816     default: {
   122817       static const struct {
   122818         int op;      /* The opcode */
   122819         u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */
   122820       } aFlagOp[] = {
   122821         { SQLITE_DBCONFIG_ENABLE_FKEY,    SQLITE_ForeignKeys    },
   122822         { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger  },
   122823       };
   122824       unsigned int i;
   122825       rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
   122826       for(i=0; i<ArraySize(aFlagOp); i++){
   122827         if( aFlagOp[i].op==op ){
   122828           int onoff = va_arg(ap, int);
   122829           int *pRes = va_arg(ap, int*);
   122830           int oldFlags = db->flags;
   122831           if( onoff>0 ){
   122832             db->flags |= aFlagOp[i].mask;
   122833           }else if( onoff==0 ){
   122834             db->flags &= ~aFlagOp[i].mask;
   122835           }
   122836           if( oldFlags!=db->flags ){
   122837             sqlite3ExpirePreparedStatements(db);
   122838           }
   122839           if( pRes ){
   122840             *pRes = (db->flags & aFlagOp[i].mask)!=0;
   122841           }
   122842           rc = SQLITE_OK;
   122843           break;
   122844         }
   122845       }
   122846       break;
   122847     }
   122848   }
   122849   va_end(ap);
   122850   return rc;
   122851 }
   122852 
   122853 
   122854 /*
   122855 ** Return true if the buffer z[0..n-1] contains all spaces.
   122856 */
   122857 static int allSpaces(const char *z, int n){
   122858   while( n>0 && z[n-1]==' ' ){ n--; }
   122859   return n==0;
   122860 }
   122861 
   122862 /*
   122863 ** This is the default collating function named "BINARY" which is always
   122864 ** available.
   122865 **
   122866 ** If the padFlag argument is not NULL then space padding at the end
   122867 ** of strings is ignored.  This implements the RTRIM collation.
   122868 */
   122869 static int binCollFunc(
   122870   void *padFlag,
   122871   int nKey1, const void *pKey1,
   122872   int nKey2, const void *pKey2
   122873 ){
   122874   int rc, n;
   122875   n = nKey1<nKey2 ? nKey1 : nKey2;
   122876   rc = memcmp(pKey1, pKey2, n);
   122877   if( rc==0 ){
   122878     if( padFlag
   122879      && allSpaces(((char*)pKey1)+n, nKey1-n)
   122880      && allSpaces(((char*)pKey2)+n, nKey2-n)
   122881     ){
   122882       /* Leave rc unchanged at 0 */
   122883     }else{
   122884       rc = nKey1 - nKey2;
   122885     }
   122886   }
   122887   return rc;
   122888 }
   122889 
   122890 /*
   122891 ** Another built-in collating sequence: NOCASE.
   122892 **
   122893 ** This collating sequence is intended to be used for "case independent
   122894 ** comparison". SQLite's knowledge of upper and lower case equivalents
   122895 ** extends only to the 26 characters used in the English language.
   122896 **
   122897 ** At the moment there is only a UTF-8 implementation.
   122898 */
   122899 static int nocaseCollatingFunc(
   122900   void *NotUsed,
   122901   int nKey1, const void *pKey1,
   122902   int nKey2, const void *pKey2
   122903 ){
   122904   int r = sqlite3StrNICmp(
   122905       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
   122906   UNUSED_PARAMETER(NotUsed);
   122907   if( 0==r ){
   122908     r = nKey1-nKey2;
   122909   }
   122910   return r;
   122911 }
   122912 
   122913 /*
   122914 ** Return the ROWID of the most recent insert
   122915 */
   122916 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
   122917   return db->lastRowid;
   122918 }
   122919 
   122920 /*
   122921 ** Return the number of changes in the most recent call to sqlite3_exec().
   122922 */
   122923 SQLITE_API int sqlite3_changes(sqlite3 *db){
   122924   return db->nChange;
   122925 }
   122926 
   122927 /*
   122928 ** Return the number of changes since the database handle was opened.
   122929 */
   122930 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
   122931   return db->nTotalChange;
   122932 }
   122933 
   122934 /*
   122935 ** Close all open savepoints. This function only manipulates fields of the
   122936 ** database handle object, it does not close any savepoints that may be open
   122937 ** at the b-tree/pager level.
   122938 */
   122939 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
   122940   while( db->pSavepoint ){
   122941     Savepoint *pTmp = db->pSavepoint;
   122942     db->pSavepoint = pTmp->pNext;
   122943     sqlite3DbFree(db, pTmp);
   122944   }
   122945   db->nSavepoint = 0;
   122946   db->nStatement = 0;
   122947   db->isTransactionSavepoint = 0;
   122948 }
   122949 
   122950 /*
   122951 ** Invoke the destructor function associated with FuncDef p, if any. Except,
   122952 ** if this is not the last copy of the function, do not invoke it. Multiple
   122953 ** copies of a single function are created when create_function() is called
   122954 ** with SQLITE_ANY as the encoding.
   122955 */
   122956 static void functionDestroy(sqlite3 *db, FuncDef *p){
   122957   FuncDestructor *pDestructor = p->pDestructor;
   122958   if( pDestructor ){
   122959     pDestructor->nRef--;
   122960     if( pDestructor->nRef==0 ){
   122961       pDestructor->xDestroy(pDestructor->pUserData);
   122962       sqlite3DbFree(db, pDestructor);
   122963     }
   122964   }
   122965 }
   122966 
   122967 /*
   122968 ** Disconnect all sqlite3_vtab objects that belong to database connection
   122969 ** db. This is called when db is being closed.
   122970 */
   122971 static void disconnectAllVtab(sqlite3 *db){
   122972 #ifndef SQLITE_OMIT_VIRTUALTABLE
   122973   int i;
   122974   sqlite3BtreeEnterAll(db);
   122975   for(i=0; i<db->nDb; i++){
   122976     Schema *pSchema = db->aDb[i].pSchema;
   122977     if( db->aDb[i].pSchema ){
   122978       HashElem *p;
   122979       for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
   122980         Table *pTab = (Table *)sqliteHashData(p);
   122981         if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
   122982       }
   122983     }
   122984   }
   122985   sqlite3VtabUnlockList(db);
   122986   sqlite3BtreeLeaveAll(db);
   122987 #else
   122988   UNUSED_PARAMETER(db);
   122989 #endif
   122990 }
   122991 
   122992 /*
   122993 ** Return TRUE if database connection db has unfinalized prepared
   122994 ** statements or unfinished sqlite3_backup objects.
   122995 */
   122996 static int connectionIsBusy(sqlite3 *db){
   122997   int j;
   122998   assert( sqlite3_mutex_held(db->mutex) );
   122999   if( db->pVdbe ) return 1;
   123000   for(j=0; j<db->nDb; j++){
   123001     Btree *pBt = db->aDb[j].pBt;
   123002     if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
   123003   }
   123004   return 0;
   123005 }
   123006 
   123007 /*
   123008 ** Close an existing SQLite database
   123009 */
   123010 static int sqlite3Close(sqlite3 *db, int forceZombie){
   123011   if( !db ){
   123012     /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
   123013     ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
   123014     return SQLITE_OK;
   123015   }
   123016   if( !sqlite3SafetyCheckSickOrOk(db) ){
   123017     return SQLITE_MISUSE_BKPT;
   123018   }
   123019   sqlite3_mutex_enter(db->mutex);
   123020 
   123021   /* Force xDisconnect calls on all virtual tables */
   123022   disconnectAllVtab(db);
   123023 
   123024   /* If a transaction is open, the disconnectAllVtab() call above
   123025   ** will not have called the xDisconnect() method on any virtual
   123026   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
   123027   ** call will do so. We need to do this before the check for active
   123028   ** SQL statements below, as the v-table implementation may be storing
   123029   ** some prepared statements internally.
   123030   */
   123031   sqlite3VtabRollback(db);
   123032 
   123033   /* Legacy behavior (sqlite3_close() behavior) is to return
   123034   ** SQLITE_BUSY if the connection can not be closed immediately.
   123035   */
   123036   if( !forceZombie && connectionIsBusy(db) ){
   123037     sqlite3Error(db, SQLITE_BUSY, "unable to close due to unfinalized "
   123038        "statements or unfinished backups");
   123039     sqlite3_mutex_leave(db->mutex);
   123040     return SQLITE_BUSY;
   123041   }
   123042 
   123043 #ifdef SQLITE_ENABLE_SQLLOG
   123044   if( sqlite3GlobalConfig.xSqllog ){
   123045     /* Closing the handle. Fourth parameter is passed the value 2. */
   123046     sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
   123047   }
   123048 #endif
   123049 
   123050   /* Convert the connection into a zombie and then close it.
   123051   */
   123052   db->magic = SQLITE_MAGIC_ZOMBIE;
   123053   sqlite3LeaveMutexAndCloseZombie(db);
   123054   return SQLITE_OK;
   123055 }
   123056 
   123057 /*
   123058 ** Two variations on the public interface for closing a database
   123059 ** connection. The sqlite3_close() version returns SQLITE_BUSY and
   123060 ** leaves the connection option if there are unfinalized prepared
   123061 ** statements or unfinished sqlite3_backups.  The sqlite3_close_v2()
   123062 ** version forces the connection to become a zombie if there are
   123063 ** unclosed resources, and arranges for deallocation when the last
   123064 ** prepare statement or sqlite3_backup closes.
   123065 */
   123066 SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
   123067 SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
   123068 
   123069 
   123070 /*
   123071 ** Close the mutex on database connection db.
   123072 **
   123073 ** Furthermore, if database connection db is a zombie (meaning that there
   123074 ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
   123075 ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
   123076 ** finished, then free all resources.
   123077 */
   123078 SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
   123079   HashElem *i;                    /* Hash table iterator */
   123080   int j;
   123081 
   123082   /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
   123083   ** or if the connection has not yet been closed by sqlite3_close_v2(),
   123084   ** then just leave the mutex and return.
   123085   */
   123086   if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
   123087     sqlite3_mutex_leave(db->mutex);
   123088     return;
   123089   }
   123090 
   123091   /* If we reach this point, it means that the database connection has
   123092   ** closed all sqlite3_stmt and sqlite3_backup objects and has been
   123093   ** passed to sqlite3_close (meaning that it is a zombie).  Therefore,
   123094   ** go ahead and free all resources.
   123095   */
   123096 
   123097   /* If a transaction is open, roll it back. This also ensures that if
   123098   ** any database schemas have been modified by an uncommitted transaction
   123099   ** they are reset. And that the required b-tree mutex is held to make
   123100   ** the pager rollback and schema reset an atomic operation. */
   123101   sqlite3RollbackAll(db, SQLITE_OK);
   123102 
   123103   /* Free any outstanding Savepoint structures. */
   123104   sqlite3CloseSavepoints(db);
   123105 
   123106   /* Close all database connections */
   123107   for(j=0; j<db->nDb; j++){
   123108     struct Db *pDb = &db->aDb[j];
   123109     if( pDb->pBt ){
   123110       sqlite3BtreeClose(pDb->pBt);
   123111       pDb->pBt = 0;
   123112       if( j!=1 ){
   123113         pDb->pSchema = 0;
   123114       }
   123115     }
   123116   }
   123117   /* Clear the TEMP schema separately and last */
   123118   if( db->aDb[1].pSchema ){
   123119     sqlite3SchemaClear(db->aDb[1].pSchema);
   123120   }
   123121   sqlite3VtabUnlockList(db);
   123122 
   123123   /* Free up the array of auxiliary databases */
   123124   sqlite3CollapseDatabaseArray(db);
   123125   assert( db->nDb<=2 );
   123126   assert( db->aDb==db->aDbStatic );
   123127 
   123128   /* Tell the code in notify.c that the connection no longer holds any
   123129   ** locks and does not require any further unlock-notify callbacks.
   123130   */
   123131   sqlite3ConnectionClosed(db);
   123132 
   123133   for(j=0; j<ArraySize(db->aFunc.a); j++){
   123134     FuncDef *pNext, *pHash, *p;
   123135     for(p=db->aFunc.a[j]; p; p=pHash){
   123136       pHash = p->pHash;
   123137       while( p ){
   123138         functionDestroy(db, p);
   123139         pNext = p->pNext;
   123140         sqlite3DbFree(db, p);
   123141         p = pNext;
   123142       }
   123143     }
   123144   }
   123145   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
   123146     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
   123147     /* Invoke any destructors registered for collation sequence user data. */
   123148     for(j=0; j<3; j++){
   123149       if( pColl[j].xDel ){
   123150         pColl[j].xDel(pColl[j].pUser);
   123151       }
   123152     }
   123153     sqlite3DbFree(db, pColl);
   123154   }
   123155   sqlite3HashClear(&db->aCollSeq);
   123156 #ifndef SQLITE_OMIT_VIRTUALTABLE
   123157   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
   123158     Module *pMod = (Module *)sqliteHashData(i);
   123159     if( pMod->xDestroy ){
   123160       pMod->xDestroy(pMod->pAux);
   123161     }
   123162     sqlite3DbFree(db, pMod);
   123163   }
   123164   sqlite3HashClear(&db->aModule);
   123165 #endif
   123166 
   123167   sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
   123168   sqlite3ValueFree(db->pErr);
   123169   sqlite3CloseExtensions(db);
   123170 
   123171   db->magic = SQLITE_MAGIC_ERROR;
   123172 
   123173   /* The temp-database schema is allocated differently from the other schema
   123174   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
   123175   ** So it needs to be freed here. Todo: Why not roll the temp schema into
   123176   ** the same sqliteMalloc() as the one that allocates the database
   123177   ** structure?
   123178   */
   123179   sqlite3DbFree(db, db->aDb[1].pSchema);
   123180   sqlite3_mutex_leave(db->mutex);
   123181   db->magic = SQLITE_MAGIC_CLOSED;
   123182   sqlite3_mutex_free(db->mutex);
   123183   assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
   123184   if( db->lookaside.bMalloced ){
   123185     sqlite3_free(db->lookaside.pStart);
   123186   }
   123187   sqlite3_free(db);
   123188 }
   123189 
   123190 /*
   123191 ** Rollback all database files.  If tripCode is not SQLITE_OK, then
   123192 ** any open cursors are invalidated ("tripped" - as in "tripping a circuit
   123193 ** breaker") and made to return tripCode if there are any further
   123194 ** attempts to use that cursor.
   123195 */
   123196 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
   123197   int i;
   123198   int inTrans = 0;
   123199   assert( sqlite3_mutex_held(db->mutex) );
   123200   sqlite3BeginBenignMalloc();
   123201 
   123202   /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
   123203   ** This is important in case the transaction being rolled back has
   123204   ** modified the database schema. If the b-tree mutexes are not taken
   123205   ** here, then another shared-cache connection might sneak in between
   123206   ** the database rollback and schema reset, which can cause false
   123207   ** corruption reports in some cases.  */
   123208   sqlite3BtreeEnterAll(db);
   123209 
   123210   for(i=0; i<db->nDb; i++){
   123211     Btree *p = db->aDb[i].pBt;
   123212     if( p ){
   123213       if( sqlite3BtreeIsInTrans(p) ){
   123214         inTrans = 1;
   123215       }
   123216       sqlite3BtreeRollback(p, tripCode);
   123217     }
   123218   }
   123219   sqlite3VtabRollback(db);
   123220   sqlite3EndBenignMalloc();
   123221 
   123222   if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
   123223     sqlite3ExpirePreparedStatements(db);
   123224     sqlite3ResetAllSchemasOfConnection(db);
   123225   }
   123226   sqlite3BtreeLeaveAll(db);
   123227 
   123228   /* Any deferred constraint violations have now been resolved. */
   123229   db->nDeferredCons = 0;
   123230   db->nDeferredImmCons = 0;
   123231   db->flags &= ~SQLITE_DeferFKs;
   123232 
   123233   /* If one has been configured, invoke the rollback-hook callback */
   123234   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
   123235     db->xRollbackCallback(db->pRollbackArg);
   123236   }
   123237 }
   123238 
   123239 /*
   123240 ** Return a static string containing the name corresponding to the error code
   123241 ** specified in the argument.
   123242 */
   123243 #if (defined(SQLITE_DEBUG) && SQLITE_OS_WIN) || defined(SQLITE_TEST)
   123244 SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
   123245   const char *zName = 0;
   123246   int i, origRc = rc;
   123247   for(i=0; i<2 && zName==0; i++, rc &= 0xff){
   123248     switch( rc ){
   123249       case SQLITE_OK:                 zName = "SQLITE_OK";                break;
   123250       case SQLITE_ERROR:              zName = "SQLITE_ERROR";             break;
   123251       case SQLITE_INTERNAL:           zName = "SQLITE_INTERNAL";          break;
   123252       case SQLITE_PERM:               zName = "SQLITE_PERM";              break;
   123253       case SQLITE_ABORT:              zName = "SQLITE_ABORT";             break;
   123254       case SQLITE_ABORT_ROLLBACK:     zName = "SQLITE_ABORT_ROLLBACK";    break;
   123255       case SQLITE_BUSY:               zName = "SQLITE_BUSY";              break;
   123256       case SQLITE_BUSY_RECOVERY:      zName = "SQLITE_BUSY_RECOVERY";     break;
   123257       case SQLITE_BUSY_SNAPSHOT:      zName = "SQLITE_BUSY_SNAPSHOT";     break;
   123258       case SQLITE_LOCKED:             zName = "SQLITE_LOCKED";            break;
   123259       case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
   123260       case SQLITE_NOMEM:              zName = "SQLITE_NOMEM";             break;
   123261       case SQLITE_READONLY:           zName = "SQLITE_READONLY";          break;
   123262       case SQLITE_READONLY_RECOVERY:  zName = "SQLITE_READONLY_RECOVERY"; break;
   123263       case SQLITE_READONLY_CANTLOCK:  zName = "SQLITE_READONLY_CANTLOCK"; break;
   123264       case SQLITE_READONLY_ROLLBACK:  zName = "SQLITE_READONLY_ROLLBACK"; break;
   123265       case SQLITE_READONLY_DBMOVED:   zName = "SQLITE_READONLY_DBMOVED";  break;
   123266       case SQLITE_INTERRUPT:          zName = "SQLITE_INTERRUPT";         break;
   123267       case SQLITE_IOERR:              zName = "SQLITE_IOERR";             break;
   123268       case SQLITE_IOERR_READ:         zName = "SQLITE_IOERR_READ";        break;
   123269       case SQLITE_IOERR_SHORT_READ:   zName = "SQLITE_IOERR_SHORT_READ";  break;
   123270       case SQLITE_IOERR_WRITE:        zName = "SQLITE_IOERR_WRITE";       break;
   123271       case SQLITE_IOERR_FSYNC:        zName = "SQLITE_IOERR_FSYNC";       break;
   123272       case SQLITE_IOERR_DIR_FSYNC:    zName = "SQLITE_IOERR_DIR_FSYNC";   break;
   123273       case SQLITE_IOERR_TRUNCATE:     zName = "SQLITE_IOERR_TRUNCATE";    break;
   123274       case SQLITE_IOERR_FSTAT:        zName = "SQLITE_IOERR_FSTAT";       break;
   123275       case SQLITE_IOERR_UNLOCK:       zName = "SQLITE_IOERR_UNLOCK";      break;
   123276       case SQLITE_IOERR_RDLOCK:       zName = "SQLITE_IOERR_RDLOCK";      break;
   123277       case SQLITE_IOERR_DELETE:       zName = "SQLITE_IOERR_DELETE";      break;
   123278       case SQLITE_IOERR_NOMEM:        zName = "SQLITE_IOERR_NOMEM";       break;
   123279       case SQLITE_IOERR_ACCESS:       zName = "SQLITE_IOERR_ACCESS";      break;
   123280       case SQLITE_IOERR_CHECKRESERVEDLOCK:
   123281                                 zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
   123282       case SQLITE_IOERR_LOCK:         zName = "SQLITE_IOERR_LOCK";        break;
   123283       case SQLITE_IOERR_CLOSE:        zName = "SQLITE_IOERR_CLOSE";       break;
   123284       case SQLITE_IOERR_DIR_CLOSE:    zName = "SQLITE_IOERR_DIR_CLOSE";   break;
   123285       case SQLITE_IOERR_SHMOPEN:      zName = "SQLITE_IOERR_SHMOPEN";     break;
   123286       case SQLITE_IOERR_SHMSIZE:      zName = "SQLITE_IOERR_SHMSIZE";     break;
   123287       case SQLITE_IOERR_SHMLOCK:      zName = "SQLITE_IOERR_SHMLOCK";     break;
   123288       case SQLITE_IOERR_SHMMAP:       zName = "SQLITE_IOERR_SHMMAP";      break;
   123289       case SQLITE_IOERR_SEEK:         zName = "SQLITE_IOERR_SEEK";        break;
   123290       case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
   123291       case SQLITE_IOERR_MMAP:         zName = "SQLITE_IOERR_MMAP";        break;
   123292       case SQLITE_IOERR_GETTEMPPATH:  zName = "SQLITE_IOERR_GETTEMPPATH"; break;
   123293       case SQLITE_IOERR_CONVPATH:     zName = "SQLITE_IOERR_CONVPATH";    break;
   123294       case SQLITE_CORRUPT:            zName = "SQLITE_CORRUPT";           break;
   123295       case SQLITE_CORRUPT_VTAB:       zName = "SQLITE_CORRUPT_VTAB";      break;
   123296       case SQLITE_NOTFOUND:           zName = "SQLITE_NOTFOUND";          break;
   123297       case SQLITE_FULL:               zName = "SQLITE_FULL";              break;
   123298       case SQLITE_CANTOPEN:           zName = "SQLITE_CANTOPEN";          break;
   123299       case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
   123300       case SQLITE_CANTOPEN_ISDIR:     zName = "SQLITE_CANTOPEN_ISDIR";    break;
   123301       case SQLITE_CANTOPEN_FULLPATH:  zName = "SQLITE_CANTOPEN_FULLPATH"; break;
   123302       case SQLITE_CANTOPEN_CONVPATH:  zName = "SQLITE_CANTOPEN_CONVPATH"; break;
   123303       case SQLITE_PROTOCOL:           zName = "SQLITE_PROTOCOL";          break;
   123304       case SQLITE_EMPTY:              zName = "SQLITE_EMPTY";             break;
   123305       case SQLITE_SCHEMA:             zName = "SQLITE_SCHEMA";            break;
   123306       case SQLITE_TOOBIG:             zName = "SQLITE_TOOBIG";            break;
   123307       case SQLITE_CONSTRAINT:         zName = "SQLITE_CONSTRAINT";        break;
   123308       case SQLITE_CONSTRAINT_UNIQUE:  zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
   123309       case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
   123310       case SQLITE_CONSTRAINT_FOREIGNKEY:
   123311                                 zName = "SQLITE_CONSTRAINT_FOREIGNKEY";   break;
   123312       case SQLITE_CONSTRAINT_CHECK:   zName = "SQLITE_CONSTRAINT_CHECK";  break;
   123313       case SQLITE_CONSTRAINT_PRIMARYKEY:
   123314                                 zName = "SQLITE_CONSTRAINT_PRIMARYKEY";   break;
   123315       case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
   123316       case SQLITE_CONSTRAINT_COMMITHOOK:
   123317                                 zName = "SQLITE_CONSTRAINT_COMMITHOOK";   break;
   123318       case SQLITE_CONSTRAINT_VTAB:    zName = "SQLITE_CONSTRAINT_VTAB";   break;
   123319       case SQLITE_CONSTRAINT_FUNCTION:
   123320                                 zName = "SQLITE_CONSTRAINT_FUNCTION";     break;
   123321       case SQLITE_CONSTRAINT_ROWID:   zName = "SQLITE_CONSTRAINT_ROWID";  break;
   123322       case SQLITE_MISMATCH:           zName = "SQLITE_MISMATCH";          break;
   123323       case SQLITE_MISUSE:             zName = "SQLITE_MISUSE";            break;
   123324       case SQLITE_NOLFS:              zName = "SQLITE_NOLFS";             break;
   123325       case SQLITE_AUTH:               zName = "SQLITE_AUTH";              break;
   123326       case SQLITE_FORMAT:             zName = "SQLITE_FORMAT";            break;
   123327       case SQLITE_RANGE:              zName = "SQLITE_RANGE";             break;
   123328       case SQLITE_NOTADB:             zName = "SQLITE_NOTADB";            break;
   123329       case SQLITE_ROW:                zName = "SQLITE_ROW";               break;
   123330       case SQLITE_NOTICE:             zName = "SQLITE_NOTICE";            break;
   123331       case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
   123332       case SQLITE_NOTICE_RECOVER_ROLLBACK:
   123333                                 zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
   123334       case SQLITE_WARNING:            zName = "SQLITE_WARNING";           break;
   123335       case SQLITE_WARNING_AUTOINDEX:  zName = "SQLITE_WARNING_AUTOINDEX"; break;
   123336       case SQLITE_DONE:               zName = "SQLITE_DONE";              break;
   123337     }
   123338   }
   123339   if( zName==0 ){
   123340     static char zBuf[50];
   123341     sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
   123342     zName = zBuf;
   123343   }
   123344   return zName;
   123345 }
   123346 #endif
   123347 
   123348 /*
   123349 ** Return a static string that describes the kind of error specified in the
   123350 ** argument.
   123351 */
   123352 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
   123353   static const char* const aMsg[] = {
   123354     /* SQLITE_OK          */ "not an error",
   123355     /* SQLITE_ERROR       */ "SQL logic error or missing database",
   123356     /* SQLITE_INTERNAL    */ 0,
   123357     /* SQLITE_PERM        */ "access permission denied",
   123358     /* SQLITE_ABORT       */ "callback requested query abort",
   123359     /* SQLITE_BUSY        */ "database is locked",
   123360     /* SQLITE_LOCKED      */ "database table is locked",
   123361     /* SQLITE_NOMEM       */ "out of memory",
   123362     /* SQLITE_READONLY    */ "attempt to write a readonly database",
   123363     /* SQLITE_INTERRUPT   */ "interrupted",
   123364     /* SQLITE_IOERR       */ "disk I/O error",
   123365     /* SQLITE_CORRUPT     */ "database disk image is malformed",
   123366     /* SQLITE_NOTFOUND    */ "unknown operation",
   123367     /* SQLITE_FULL        */ "database or disk is full",
   123368     /* SQLITE_CANTOPEN    */ "unable to open database file",
   123369     /* SQLITE_PROTOCOL    */ "locking protocol",
   123370     /* SQLITE_EMPTY       */ "table contains no data",
   123371     /* SQLITE_SCHEMA      */ "database schema has changed",
   123372     /* SQLITE_TOOBIG      */ "string or blob too big",
   123373     /* SQLITE_CONSTRAINT  */ "constraint failed",
   123374     /* SQLITE_MISMATCH    */ "datatype mismatch",
   123375     /* SQLITE_MISUSE      */ "library routine called out of sequence",
   123376     /* SQLITE_NOLFS       */ "large file support is disabled",
   123377     /* SQLITE_AUTH        */ "authorization denied",
   123378     /* SQLITE_FORMAT      */ "auxiliary database format error",
   123379     /* SQLITE_RANGE       */ "bind or column index out of range",
   123380     /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
   123381   };
   123382   const char *zErr = "unknown error";
   123383   switch( rc ){
   123384     case SQLITE_ABORT_ROLLBACK: {
   123385       zErr = "abort due to ROLLBACK";
   123386       break;
   123387     }
   123388     default: {
   123389       rc &= 0xff;
   123390       if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
   123391         zErr = aMsg[rc];
   123392       }
   123393       break;
   123394     }
   123395   }
   123396   return zErr;
   123397 }
   123398 
   123399 /*
   123400 ** This routine implements a busy callback that sleeps and tries
   123401 ** again until a timeout value is reached.  The timeout value is
   123402 ** an integer number of milliseconds passed in as the first
   123403 ** argument.
   123404 */
   123405 static int sqliteDefaultBusyCallback(
   123406  void *ptr,               /* Database connection */
   123407  int count                /* Number of times table has been busy */
   123408 ){
   123409 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
   123410   static const u8 delays[] =
   123411      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
   123412   static const u8 totals[] =
   123413      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
   123414 # define NDELAY ArraySize(delays)
   123415   sqlite3 *db = (sqlite3 *)ptr;
   123416   int timeout = db->busyTimeout;
   123417   int delay, prior;
   123418 
   123419   assert( count>=0 );
   123420   if( count < NDELAY ){
   123421     delay = delays[count];
   123422     prior = totals[count];
   123423   }else{
   123424     delay = delays[NDELAY-1];
   123425     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
   123426   }
   123427   if( prior + delay > timeout ){
   123428     delay = timeout - prior;
   123429     if( delay<=0 ) return 0;
   123430   }
   123431   sqlite3OsSleep(db->pVfs, delay*1000);
   123432   return 1;
   123433 #else
   123434   sqlite3 *db = (sqlite3 *)ptr;
   123435   int timeout = ((sqlite3 *)ptr)->busyTimeout;
   123436   if( (count+1)*1000 > timeout ){
   123437     return 0;
   123438   }
   123439   sqlite3OsSleep(db->pVfs, 1000000);
   123440   return 1;
   123441 #endif
   123442 }
   123443 
   123444 /*
   123445 ** Invoke the given busy handler.
   123446 **
   123447 ** This routine is called when an operation failed with a lock.
   123448 ** If this routine returns non-zero, the lock is retried.  If it
   123449 ** returns 0, the operation aborts with an SQLITE_BUSY error.
   123450 */
   123451 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
   123452   int rc;
   123453   if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
   123454   rc = p->xFunc(p->pArg, p->nBusy);
   123455   if( rc==0 ){
   123456     p->nBusy = -1;
   123457   }else{
   123458     p->nBusy++;
   123459   }
   123460   return rc;
   123461 }
   123462 
   123463 /*
   123464 ** This routine sets the busy callback for an Sqlite database to the
   123465 ** given callback function with the given argument.
   123466 */
   123467 SQLITE_API int sqlite3_busy_handler(
   123468   sqlite3 *db,
   123469   int (*xBusy)(void*,int),
   123470   void *pArg
   123471 ){
   123472   sqlite3_mutex_enter(db->mutex);
   123473   db->busyHandler.xFunc = xBusy;
   123474   db->busyHandler.pArg = pArg;
   123475   db->busyHandler.nBusy = 0;
   123476   db->busyTimeout = 0;
   123477   sqlite3_mutex_leave(db->mutex);
   123478   return SQLITE_OK;
   123479 }
   123480 
   123481 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   123482 /*
   123483 ** This routine sets the progress callback for an Sqlite database to the
   123484 ** given callback function with the given argument. The progress callback will
   123485 ** be invoked every nOps opcodes.
   123486 */
   123487 SQLITE_API void sqlite3_progress_handler(
   123488   sqlite3 *db,
   123489   int nOps,
   123490   int (*xProgress)(void*),
   123491   void *pArg
   123492 ){
   123493   sqlite3_mutex_enter(db->mutex);
   123494   if( nOps>0 ){
   123495     db->xProgress = xProgress;
   123496     db->nProgressOps = (unsigned)nOps;
   123497     db->pProgressArg = pArg;
   123498   }else{
   123499     db->xProgress = 0;
   123500     db->nProgressOps = 0;
   123501     db->pProgressArg = 0;
   123502   }
   123503   sqlite3_mutex_leave(db->mutex);
   123504 }
   123505 #endif
   123506 
   123507 
   123508 /*
   123509 ** This routine installs a default busy handler that waits for the
   123510 ** specified number of milliseconds before returning 0.
   123511 */
   123512 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
   123513   if( ms>0 ){
   123514     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
   123515     db->busyTimeout = ms;
   123516   }else{
   123517     sqlite3_busy_handler(db, 0, 0);
   123518   }
   123519   return SQLITE_OK;
   123520 }
   123521 
   123522 /*
   123523 ** Cause any pending operation to stop at its earliest opportunity.
   123524 */
   123525 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
   123526   db->u1.isInterrupted = 1;
   123527 }
   123528 
   123529 
   123530 /*
   123531 ** This function is exactly the same as sqlite3_create_function(), except
   123532 ** that it is designed to be called by internal code. The difference is
   123533 ** that if a malloc() fails in sqlite3_create_function(), an error code
   123534 ** is returned and the mallocFailed flag cleared.
   123535 */
   123536 SQLITE_PRIVATE int sqlite3CreateFunc(
   123537   sqlite3 *db,
   123538   const char *zFunctionName,
   123539   int nArg,
   123540   int enc,
   123541   void *pUserData,
   123542   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
   123543   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
   123544   void (*xFinal)(sqlite3_context*),
   123545   FuncDestructor *pDestructor
   123546 ){
   123547   FuncDef *p;
   123548   int nName;
   123549   int extraFlags;
   123550 
   123551   assert( sqlite3_mutex_held(db->mutex) );
   123552   if( zFunctionName==0 ||
   123553       (xFunc && (xFinal || xStep)) ||
   123554       (!xFunc && (xFinal && !xStep)) ||
   123555       (!xFunc && (!xFinal && xStep)) ||
   123556       (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
   123557       (255<(nName = sqlite3Strlen30( zFunctionName))) ){
   123558     return SQLITE_MISUSE_BKPT;
   123559   }
   123560 
   123561   assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
   123562   extraFlags = enc &  SQLITE_DETERMINISTIC;
   123563   enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
   123564 
   123565 #ifndef SQLITE_OMIT_UTF16
   123566   /* If SQLITE_UTF16 is specified as the encoding type, transform this
   123567   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
   123568   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
   123569   **
   123570   ** If SQLITE_ANY is specified, add three versions of the function
   123571   ** to the hash table.
   123572   */
   123573   if( enc==SQLITE_UTF16 ){
   123574     enc = SQLITE_UTF16NATIVE;
   123575   }else if( enc==SQLITE_ANY ){
   123576     int rc;
   123577     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
   123578          pUserData, xFunc, xStep, xFinal, pDestructor);
   123579     if( rc==SQLITE_OK ){
   123580       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
   123581           pUserData, xFunc, xStep, xFinal, pDestructor);
   123582     }
   123583     if( rc!=SQLITE_OK ){
   123584       return rc;
   123585     }
   123586     enc = SQLITE_UTF16BE;
   123587   }
   123588 #else
   123589   enc = SQLITE_UTF8;
   123590 #endif
   123591 
   123592   /* Check if an existing function is being overridden or deleted. If so,
   123593   ** and there are active VMs, then return SQLITE_BUSY. If a function
   123594   ** is being overridden/deleted but there are no active VMs, allow the
   123595   ** operation to continue but invalidate all precompiled statements.
   123596   */
   123597   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
   123598   if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
   123599     if( db->nVdbeActive ){
   123600       sqlite3Error(db, SQLITE_BUSY,
   123601         "unable to delete/modify user-function due to active statements");
   123602       assert( !db->mallocFailed );
   123603       return SQLITE_BUSY;
   123604     }else{
   123605       sqlite3ExpirePreparedStatements(db);
   123606     }
   123607   }
   123608 
   123609   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
   123610   assert(p || db->mallocFailed);
   123611   if( !p ){
   123612     return SQLITE_NOMEM;
   123613   }
   123614 
   123615   /* If an older version of the function with a configured destructor is
   123616   ** being replaced invoke the destructor function here. */
   123617   functionDestroy(db, p);
   123618 
   123619   if( pDestructor ){
   123620     pDestructor->nRef++;
   123621   }
   123622   p->pDestructor = pDestructor;
   123623   p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
   123624   testcase( p->funcFlags & SQLITE_DETERMINISTIC );
   123625   p->xFunc = xFunc;
   123626   p->xStep = xStep;
   123627   p->xFinalize = xFinal;
   123628   p->pUserData = pUserData;
   123629   p->nArg = (u16)nArg;
   123630   return SQLITE_OK;
   123631 }
   123632 
   123633 /*
   123634 ** Create new user functions.
   123635 */
   123636 SQLITE_API int sqlite3_create_function(
   123637   sqlite3 *db,
   123638   const char *zFunc,
   123639   int nArg,
   123640   int enc,
   123641   void *p,
   123642   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
   123643   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
   123644   void (*xFinal)(sqlite3_context*)
   123645 ){
   123646   return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
   123647                                     xFinal, 0);
   123648 }
   123649 
   123650 SQLITE_API int sqlite3_create_function_v2(
   123651   sqlite3 *db,
   123652   const char *zFunc,
   123653   int nArg,
   123654   int enc,
   123655   void *p,
   123656   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
   123657   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
   123658   void (*xFinal)(sqlite3_context*),
   123659   void (*xDestroy)(void *)
   123660 ){
   123661   int rc = SQLITE_ERROR;
   123662   FuncDestructor *pArg = 0;
   123663   sqlite3_mutex_enter(db->mutex);
   123664   if( xDestroy ){
   123665     pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
   123666     if( !pArg ){
   123667       xDestroy(p);
   123668       goto out;
   123669     }
   123670     pArg->xDestroy = xDestroy;
   123671     pArg->pUserData = p;
   123672   }
   123673   rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
   123674   if( pArg && pArg->nRef==0 ){
   123675     assert( rc!=SQLITE_OK );
   123676     xDestroy(p);
   123677     sqlite3DbFree(db, pArg);
   123678   }
   123679 
   123680  out:
   123681   rc = sqlite3ApiExit(db, rc);
   123682   sqlite3_mutex_leave(db->mutex);
   123683   return rc;
   123684 }
   123685 
   123686 #ifndef SQLITE_OMIT_UTF16
   123687 SQLITE_API int sqlite3_create_function16(
   123688   sqlite3 *db,
   123689   const void *zFunctionName,
   123690   int nArg,
   123691   int eTextRep,
   123692   void *p,
   123693   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
   123694   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
   123695   void (*xFinal)(sqlite3_context*)
   123696 ){
   123697   int rc;
   123698   char *zFunc8;
   123699   sqlite3_mutex_enter(db->mutex);
   123700   assert( !db->mallocFailed );
   123701   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
   123702   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
   123703   sqlite3DbFree(db, zFunc8);
   123704   rc = sqlite3ApiExit(db, rc);
   123705   sqlite3_mutex_leave(db->mutex);
   123706   return rc;
   123707 }
   123708 #endif
   123709 
   123710 
   123711 /*
   123712 ** Declare that a function has been overloaded by a virtual table.
   123713 **
   123714 ** If the function already exists as a regular global function, then
   123715 ** this routine is a no-op.  If the function does not exist, then create
   123716 ** a new one that always throws a run-time error.
   123717 **
   123718 ** When virtual tables intend to provide an overloaded function, they
   123719 ** should call this routine to make sure the global function exists.
   123720 ** A global function must exist in order for name resolution to work
   123721 ** properly.
   123722 */
   123723 SQLITE_API int sqlite3_overload_function(
   123724   sqlite3 *db,
   123725   const char *zName,
   123726   int nArg
   123727 ){
   123728   int nName = sqlite3Strlen30(zName);
   123729   int rc = SQLITE_OK;
   123730   sqlite3_mutex_enter(db->mutex);
   123731   if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
   123732     rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
   123733                            0, sqlite3InvalidFunction, 0, 0, 0);
   123734   }
   123735   rc = sqlite3ApiExit(db, rc);
   123736   sqlite3_mutex_leave(db->mutex);
   123737   return rc;
   123738 }
   123739 
   123740 #ifndef SQLITE_OMIT_TRACE
   123741 /*
   123742 ** Register a trace function.  The pArg from the previously registered trace
   123743 ** is returned.
   123744 **
   123745 ** A NULL trace function means that no tracing is executes.  A non-NULL
   123746 ** trace is a pointer to a function that is invoked at the start of each
   123747 ** SQL statement.
   123748 */
   123749 SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
   123750   void *pOld;
   123751   sqlite3_mutex_enter(db->mutex);
   123752   pOld = db->pTraceArg;
   123753   db->xTrace = xTrace;
   123754   db->pTraceArg = pArg;
   123755   sqlite3_mutex_leave(db->mutex);
   123756   return pOld;
   123757 }
   123758 /*
   123759 ** Register a profile function.  The pArg from the previously registered
   123760 ** profile function is returned.
   123761 **
   123762 ** A NULL profile function means that no profiling is executes.  A non-NULL
   123763 ** profile is a pointer to a function that is invoked at the conclusion of
   123764 ** each SQL statement that is run.
   123765 */
   123766 SQLITE_API void *sqlite3_profile(
   123767   sqlite3 *db,
   123768   void (*xProfile)(void*,const char*,sqlite_uint64),
   123769   void *pArg
   123770 ){
   123771   void *pOld;
   123772   sqlite3_mutex_enter(db->mutex);
   123773   pOld = db->pProfileArg;
   123774   db->xProfile = xProfile;
   123775   db->pProfileArg = pArg;
   123776   sqlite3_mutex_leave(db->mutex);
   123777   return pOld;
   123778 }
   123779 #endif /* SQLITE_OMIT_TRACE */
   123780 
   123781 /*
   123782 ** Register a function to be invoked when a transaction commits.
   123783 ** If the invoked function returns non-zero, then the commit becomes a
   123784 ** rollback.
   123785 */
   123786 SQLITE_API void *sqlite3_commit_hook(
   123787   sqlite3 *db,              /* Attach the hook to this database */
   123788   int (*xCallback)(void*),  /* Function to invoke on each commit */
   123789   void *pArg                /* Argument to the function */
   123790 ){
   123791   void *pOld;
   123792   sqlite3_mutex_enter(db->mutex);
   123793   pOld = db->pCommitArg;
   123794   db->xCommitCallback = xCallback;
   123795   db->pCommitArg = pArg;
   123796   sqlite3_mutex_leave(db->mutex);
   123797   return pOld;
   123798 }
   123799 
   123800 /*
   123801 ** Register a callback to be invoked each time a row is updated,
   123802 ** inserted or deleted using this database connection.
   123803 */
   123804 SQLITE_API void *sqlite3_update_hook(
   123805   sqlite3 *db,              /* Attach the hook to this database */
   123806   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
   123807   void *pArg                /* Argument to the function */
   123808 ){
   123809   void *pRet;
   123810   sqlite3_mutex_enter(db->mutex);
   123811   pRet = db->pUpdateArg;
   123812   db->xUpdateCallback = xCallback;
   123813   db->pUpdateArg = pArg;
   123814   sqlite3_mutex_leave(db->mutex);
   123815   return pRet;
   123816 }
   123817 
   123818 /*
   123819 ** Register a callback to be invoked each time a transaction is rolled
   123820 ** back by this database connection.
   123821 */
   123822 SQLITE_API void *sqlite3_rollback_hook(
   123823   sqlite3 *db,              /* Attach the hook to this database */
   123824   void (*xCallback)(void*), /* Callback function */
   123825   void *pArg                /* Argument to the function */
   123826 ){
   123827   void *pRet;
   123828   sqlite3_mutex_enter(db->mutex);
   123829   pRet = db->pRollbackArg;
   123830   db->xRollbackCallback = xCallback;
   123831   db->pRollbackArg = pArg;
   123832   sqlite3_mutex_leave(db->mutex);
   123833   return pRet;
   123834 }
   123835 
   123836 #ifndef SQLITE_OMIT_WAL
   123837 /*
   123838 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
   123839 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
   123840 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
   123841 ** wal_autocheckpoint()).
   123842 */
   123843 SQLITE_PRIVATE int sqlite3WalDefaultHook(
   123844   void *pClientData,     /* Argument */
   123845   sqlite3 *db,           /* Connection */
   123846   const char *zDb,       /* Database */
   123847   int nFrame             /* Size of WAL */
   123848 ){
   123849   if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
   123850     sqlite3BeginBenignMalloc();
   123851     sqlite3_wal_checkpoint(db, zDb);
   123852     sqlite3EndBenignMalloc();
   123853   }
   123854   return SQLITE_OK;
   123855 }
   123856 #endif /* SQLITE_OMIT_WAL */
   123857 
   123858 /*
   123859 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
   123860 ** a database after committing a transaction if there are nFrame or
   123861 ** more frames in the log file. Passing zero or a negative value as the
   123862 ** nFrame parameter disables automatic checkpoints entirely.
   123863 **
   123864 ** The callback registered by this function replaces any existing callback
   123865 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
   123866 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
   123867 ** configured by this function.
   123868 */
   123869 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
   123870 #ifdef SQLITE_OMIT_WAL
   123871   UNUSED_PARAMETER(db);
   123872   UNUSED_PARAMETER(nFrame);
   123873 #else
   123874   if( nFrame>0 ){
   123875     sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
   123876   }else{
   123877     sqlite3_wal_hook(db, 0, 0);
   123878   }
   123879 #endif
   123880   return SQLITE_OK;
   123881 }
   123882 
   123883 /*
   123884 ** Register a callback to be invoked each time a transaction is written
   123885 ** into the write-ahead-log by this database connection.
   123886 */
   123887 SQLITE_API void *sqlite3_wal_hook(
   123888   sqlite3 *db,                    /* Attach the hook to this db handle */
   123889   int(*xCallback)(void *, sqlite3*, const char*, int),
   123890   void *pArg                      /* First argument passed to xCallback() */
   123891 ){
   123892 #ifndef SQLITE_OMIT_WAL
   123893   void *pRet;
   123894   sqlite3_mutex_enter(db->mutex);
   123895   pRet = db->pWalArg;
   123896   db->xWalCallback = xCallback;
   123897   db->pWalArg = pArg;
   123898   sqlite3_mutex_leave(db->mutex);
   123899   return pRet;
   123900 #else
   123901   return 0;
   123902 #endif
   123903 }
   123904 
   123905 /*
   123906 ** Checkpoint database zDb.
   123907 */
   123908 SQLITE_API int sqlite3_wal_checkpoint_v2(
   123909   sqlite3 *db,                    /* Database handle */
   123910   const char *zDb,                /* Name of attached database (or NULL) */
   123911   int eMode,                      /* SQLITE_CHECKPOINT_* value */
   123912   int *pnLog,                     /* OUT: Size of WAL log in frames */
   123913   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
   123914 ){
   123915 #ifdef SQLITE_OMIT_WAL
   123916   return SQLITE_OK;
   123917 #else
   123918   int rc;                         /* Return code */
   123919   int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
   123920 
   123921   /* Initialize the output variables to -1 in case an error occurs. */
   123922   if( pnLog ) *pnLog = -1;
   123923   if( pnCkpt ) *pnCkpt = -1;
   123924 
   123925   assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE );
   123926   assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART );
   123927   assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART );
   123928   if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){
   123929     return SQLITE_MISUSE;
   123930   }
   123931 
   123932   sqlite3_mutex_enter(db->mutex);
   123933   if( zDb && zDb[0] ){
   123934     iDb = sqlite3FindDbName(db, zDb);
   123935   }
   123936   if( iDb<0 ){
   123937     rc = SQLITE_ERROR;
   123938     sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
   123939   }else{
   123940     rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
   123941     sqlite3Error(db, rc, 0);
   123942   }
   123943   rc = sqlite3ApiExit(db, rc);
   123944   sqlite3_mutex_leave(db->mutex);
   123945   return rc;
   123946 #endif
   123947 }
   123948 
   123949 
   123950 /*
   123951 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
   123952 ** to contains a zero-length string, all attached databases are
   123953 ** checkpointed.
   123954 */
   123955 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
   123956   return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0);
   123957 }
   123958 
   123959 #ifndef SQLITE_OMIT_WAL
   123960 /*
   123961 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
   123962 ** not currently open in WAL mode.
   123963 **
   123964 ** If a transaction is open on the database being checkpointed, this
   123965 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
   123966 ** an error occurs while running the checkpoint, an SQLite error code is
   123967 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
   123968 **
   123969 ** The mutex on database handle db should be held by the caller. The mutex
   123970 ** associated with the specific b-tree being checkpointed is taken by
   123971 ** this function while the checkpoint is running.
   123972 **
   123973 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
   123974 ** checkpointed. If an error is encountered it is returned immediately -
   123975 ** no attempt is made to checkpoint any remaining databases.
   123976 **
   123977 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
   123978 */
   123979 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
   123980   int rc = SQLITE_OK;             /* Return code */
   123981   int i;                          /* Used to iterate through attached dbs */
   123982   int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */
   123983 
   123984   assert( sqlite3_mutex_held(db->mutex) );
   123985   assert( !pnLog || *pnLog==-1 );
   123986   assert( !pnCkpt || *pnCkpt==-1 );
   123987 
   123988   for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
   123989     if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
   123990       rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
   123991       pnLog = 0;
   123992       pnCkpt = 0;
   123993       if( rc==SQLITE_BUSY ){
   123994         bBusy = 1;
   123995         rc = SQLITE_OK;
   123996       }
   123997     }
   123998   }
   123999 
   124000   return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
   124001 }
   124002 #endif /* SQLITE_OMIT_WAL */
   124003 
   124004 /*
   124005 ** This function returns true if main-memory should be used instead of
   124006 ** a temporary file for transient pager files and statement journals.
   124007 ** The value returned depends on the value of db->temp_store (runtime
   124008 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
   124009 ** following table describes the relationship between these two values
   124010 ** and this functions return value.
   124011 **
   124012 **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
   124013 **   -----------------     --------------     ------------------------------
   124014 **   0                     any                file      (return 0)
   124015 **   1                     1                  file      (return 0)
   124016 **   1                     2                  memory    (return 1)
   124017 **   1                     0                  file      (return 0)
   124018 **   2                     1                  file      (return 0)
   124019 **   2                     2                  memory    (return 1)
   124020 **   2                     0                  memory    (return 1)
   124021 **   3                     any                memory    (return 1)
   124022 */
   124023 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
   124024 #if SQLITE_TEMP_STORE==1
   124025   return ( db->temp_store==2 );
   124026 #endif
   124027 #if SQLITE_TEMP_STORE==2
   124028   return ( db->temp_store!=1 );
   124029 #endif
   124030 #if SQLITE_TEMP_STORE==3
   124031   return 1;
   124032 #endif
   124033 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
   124034   return 0;
   124035 #endif
   124036 }
   124037 
   124038 /*
   124039 ** Return UTF-8 encoded English language explanation of the most recent
   124040 ** error.
   124041 */
   124042 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
   124043   const char *z;
   124044   if( !db ){
   124045     return sqlite3ErrStr(SQLITE_NOMEM);
   124046   }
   124047   if( !sqlite3SafetyCheckSickOrOk(db) ){
   124048     return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
   124049   }
   124050   sqlite3_mutex_enter(db->mutex);
   124051   if( db->mallocFailed ){
   124052     z = sqlite3ErrStr(SQLITE_NOMEM);
   124053   }else{
   124054     testcase( db->pErr==0 );
   124055     z = (char*)sqlite3_value_text(db->pErr);
   124056     assert( !db->mallocFailed );
   124057     if( z==0 ){
   124058       z = sqlite3ErrStr(db->errCode);
   124059     }
   124060   }
   124061   sqlite3_mutex_leave(db->mutex);
   124062   return z;
   124063 }
   124064 
   124065 #ifndef SQLITE_OMIT_UTF16
   124066 /*
   124067 ** Return UTF-16 encoded English language explanation of the most recent
   124068 ** error.
   124069 */
   124070 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
   124071   static const u16 outOfMem[] = {
   124072     'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
   124073   };
   124074   static const u16 misuse[] = {
   124075     'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
   124076     'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
   124077     'c', 'a', 'l', 'l', 'e', 'd', ' ',
   124078     'o', 'u', 't', ' ',
   124079     'o', 'f', ' ',
   124080     's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
   124081   };
   124082 
   124083   const void *z;
   124084   if( !db ){
   124085     return (void *)outOfMem;
   124086   }
   124087   if( !sqlite3SafetyCheckSickOrOk(db) ){
   124088     return (void *)misuse;
   124089   }
   124090   sqlite3_mutex_enter(db->mutex);
   124091   if( db->mallocFailed ){
   124092     z = (void *)outOfMem;
   124093   }else{
   124094     z = sqlite3_value_text16(db->pErr);
   124095     if( z==0 ){
   124096       sqlite3Error(db, db->errCode, sqlite3ErrStr(db->errCode));
   124097       z = sqlite3_value_text16(db->pErr);
   124098     }
   124099     /* A malloc() may have failed within the call to sqlite3_value_text16()
   124100     ** above. If this is the case, then the db->mallocFailed flag needs to
   124101     ** be cleared before returning. Do this directly, instead of via
   124102     ** sqlite3ApiExit(), to avoid setting the database handle error message.
   124103     */
   124104     db->mallocFailed = 0;
   124105   }
   124106   sqlite3_mutex_leave(db->mutex);
   124107   return z;
   124108 }
   124109 #endif /* SQLITE_OMIT_UTF16 */
   124110 
   124111 /*
   124112 ** Return the most recent error code generated by an SQLite routine. If NULL is
   124113 ** passed to this function, we assume a malloc() failed during sqlite3_open().
   124114 */
   124115 SQLITE_API int sqlite3_errcode(sqlite3 *db){
   124116   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
   124117     return SQLITE_MISUSE_BKPT;
   124118   }
   124119   if( !db || db->mallocFailed ){
   124120     return SQLITE_NOMEM;
   124121   }
   124122   return db->errCode & db->errMask;
   124123 }
   124124 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
   124125   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
   124126     return SQLITE_MISUSE_BKPT;
   124127   }
   124128   if( !db || db->mallocFailed ){
   124129     return SQLITE_NOMEM;
   124130   }
   124131   return db->errCode;
   124132 }
   124133 
   124134 /*
   124135 ** Return a string that describes the kind of error specified in the
   124136 ** argument.  For now, this simply calls the internal sqlite3ErrStr()
   124137 ** function.
   124138 */
   124139 SQLITE_API const char *sqlite3_errstr(int rc){
   124140   return sqlite3ErrStr(rc);
   124141 }
   124142 
   124143 /*
   124144 ** Invalidate all cached KeyInfo objects for database connection "db"
   124145 */
   124146 static void invalidateCachedKeyInfo(sqlite3 *db){
   124147   Db *pDb;                    /* A single database */
   124148   int iDb;                    /* The database index number */
   124149   HashElem *k;                /* For looping over tables in pDb */
   124150   Table *pTab;                /* A table in the database */
   124151   Index *pIdx;                /* Each index */
   124152 
   124153   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
   124154     if( pDb->pBt==0 ) continue;
   124155     sqlite3BtreeEnter(pDb->pBt);
   124156     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
   124157       pTab = (Table*)sqliteHashData(k);
   124158       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   124159         if( pIdx->pKeyInfo && pIdx->pKeyInfo->db==db ){
   124160           sqlite3KeyInfoUnref(pIdx->pKeyInfo);
   124161           pIdx->pKeyInfo = 0;
   124162         }
   124163       }
   124164     }
   124165     sqlite3BtreeLeave(pDb->pBt);
   124166   }
   124167 }
   124168 
   124169 /*
   124170 ** Create a new collating function for database "db".  The name is zName
   124171 ** and the encoding is enc.
   124172 */
   124173 static int createCollation(
   124174   sqlite3* db,
   124175   const char *zName,
   124176   u8 enc,
   124177   void* pCtx,
   124178   int(*xCompare)(void*,int,const void*,int,const void*),
   124179   void(*xDel)(void*)
   124180 ){
   124181   CollSeq *pColl;
   124182   int enc2;
   124183   int nName = sqlite3Strlen30(zName);
   124184 
   124185   assert( sqlite3_mutex_held(db->mutex) );
   124186 
   124187   /* If SQLITE_UTF16 is specified as the encoding type, transform this
   124188   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
   124189   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
   124190   */
   124191   enc2 = enc;
   124192   testcase( enc2==SQLITE_UTF16 );
   124193   testcase( enc2==SQLITE_UTF16_ALIGNED );
   124194   if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
   124195     enc2 = SQLITE_UTF16NATIVE;
   124196   }
   124197   if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
   124198     return SQLITE_MISUSE_BKPT;
   124199   }
   124200 
   124201   /* Check if this call is removing or replacing an existing collation
   124202   ** sequence. If so, and there are active VMs, return busy. If there
   124203   ** are no active VMs, invalidate any pre-compiled statements.
   124204   */
   124205   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
   124206   if( pColl && pColl->xCmp ){
   124207     if( db->nVdbeActive ){
   124208       sqlite3Error(db, SQLITE_BUSY,
   124209         "unable to delete/modify collation sequence due to active statements");
   124210       return SQLITE_BUSY;
   124211     }
   124212     sqlite3ExpirePreparedStatements(db);
   124213     invalidateCachedKeyInfo(db);
   124214 
   124215     /* If collation sequence pColl was created directly by a call to
   124216     ** sqlite3_create_collation, and not generated by synthCollSeq(),
   124217     ** then any copies made by synthCollSeq() need to be invalidated.
   124218     ** Also, collation destructor - CollSeq.xDel() - function may need
   124219     ** to be called.
   124220     */
   124221     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
   124222       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
   124223       int j;
   124224       for(j=0; j<3; j++){
   124225         CollSeq *p = &aColl[j];
   124226         if( p->enc==pColl->enc ){
   124227           if( p->xDel ){
   124228             p->xDel(p->pUser);
   124229           }
   124230           p->xCmp = 0;
   124231         }
   124232       }
   124233     }
   124234   }
   124235 
   124236   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
   124237   if( pColl==0 ) return SQLITE_NOMEM;
   124238   pColl->xCmp = xCompare;
   124239   pColl->pUser = pCtx;
   124240   pColl->xDel = xDel;
   124241   pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
   124242   sqlite3Error(db, SQLITE_OK, 0);
   124243   return SQLITE_OK;
   124244 }
   124245 
   124246 
   124247 /*
   124248 ** This array defines hard upper bounds on limit values.  The
   124249 ** initializer must be kept in sync with the SQLITE_LIMIT_*
   124250 ** #defines in sqlite3.h.
   124251 */
   124252 static const int aHardLimit[] = {
   124253   SQLITE_MAX_LENGTH,
   124254   SQLITE_MAX_SQL_LENGTH,
   124255   SQLITE_MAX_COLUMN,
   124256   SQLITE_MAX_EXPR_DEPTH,
   124257   SQLITE_MAX_COMPOUND_SELECT,
   124258   SQLITE_MAX_VDBE_OP,
   124259   SQLITE_MAX_FUNCTION_ARG,
   124260   SQLITE_MAX_ATTACHED,
   124261   SQLITE_MAX_LIKE_PATTERN_LENGTH,
   124262   SQLITE_MAX_VARIABLE_NUMBER,      /* IMP: R-38091-32352 */
   124263   SQLITE_MAX_TRIGGER_DEPTH,
   124264 };
   124265 
   124266 /*
   124267 ** Make sure the hard limits are set to reasonable values
   124268 */
   124269 #if SQLITE_MAX_LENGTH<100
   124270 # error SQLITE_MAX_LENGTH must be at least 100
   124271 #endif
   124272 #if SQLITE_MAX_SQL_LENGTH<100
   124273 # error SQLITE_MAX_SQL_LENGTH must be at least 100
   124274 #endif
   124275 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
   124276 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
   124277 #endif
   124278 #if SQLITE_MAX_COMPOUND_SELECT<2
   124279 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
   124280 #endif
   124281 #if SQLITE_MAX_VDBE_OP<40
   124282 # error SQLITE_MAX_VDBE_OP must be at least 40
   124283 #endif
   124284 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
   124285 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
   124286 #endif
   124287 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
   124288 # error SQLITE_MAX_ATTACHED must be between 0 and 125
   124289 #endif
   124290 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
   124291 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
   124292 #endif
   124293 #if SQLITE_MAX_COLUMN>32767
   124294 # error SQLITE_MAX_COLUMN must not exceed 32767
   124295 #endif
   124296 #if SQLITE_MAX_TRIGGER_DEPTH<1
   124297 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
   124298 #endif
   124299 
   124300 
   124301 /*
   124302 ** Change the value of a limit.  Report the old value.
   124303 ** If an invalid limit index is supplied, report -1.
   124304 ** Make no changes but still report the old value if the
   124305 ** new limit is negative.
   124306 **
   124307 ** A new lower limit does not shrink existing constructs.
   124308 ** It merely prevents new constructs that exceed the limit
   124309 ** from forming.
   124310 */
   124311 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
   124312   int oldLimit;
   124313 
   124314 
   124315   /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
   124316   ** there is a hard upper bound set at compile-time by a C preprocessor
   124317   ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
   124318   ** "_MAX_".)
   124319   */
   124320   assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
   124321   assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
   124322   assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
   124323   assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
   124324   assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
   124325   assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
   124326   assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
   124327   assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
   124328   assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
   124329                                                SQLITE_MAX_LIKE_PATTERN_LENGTH );
   124330   assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
   124331   assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
   124332   assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );
   124333 
   124334 
   124335   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
   124336     return -1;
   124337   }
   124338   oldLimit = db->aLimit[limitId];
   124339   if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
   124340     if( newLimit>aHardLimit[limitId] ){
   124341       newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
   124342     }
   124343     db->aLimit[limitId] = newLimit;
   124344   }
   124345   return oldLimit;                     /* IMP: R-53341-35419 */
   124346 }
   124347 
   124348 /*
   124349 ** This function is used to parse both URIs and non-URI filenames passed by the
   124350 ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
   124351 ** URIs specified as part of ATTACH statements.
   124352 **
   124353 ** The first argument to this function is the name of the VFS to use (or
   124354 ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
   124355 ** query parameter. The second argument contains the URI (or non-URI filename)
   124356 ** itself. When this function is called the *pFlags variable should contain
   124357 ** the default flags to open the database handle with. The value stored in
   124358 ** *pFlags may be updated before returning if the URI filename contains
   124359 ** "cache=xxx" or "mode=xxx" query parameters.
   124360 **
   124361 ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
   124362 ** the VFS that should be used to open the database file. *pzFile is set to
   124363 ** point to a buffer containing the name of the file to open. It is the
   124364 ** responsibility of the caller to eventually call sqlite3_free() to release
   124365 ** this buffer.
   124366 **
   124367 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
   124368 ** may be set to point to a buffer containing an English language error
   124369 ** message. It is the responsibility of the caller to eventually release
   124370 ** this buffer by calling sqlite3_free().
   124371 */
   124372 SQLITE_PRIVATE int sqlite3ParseUri(
   124373   const char *zDefaultVfs,        /* VFS to use if no "vfs=xxx" query option */
   124374   const char *zUri,               /* Nul-terminated URI to parse */
   124375   unsigned int *pFlags,           /* IN/OUT: SQLITE_OPEN_XXX flags */
   124376   sqlite3_vfs **ppVfs,            /* OUT: VFS to use */
   124377   char **pzFile,                  /* OUT: Filename component of URI */
   124378   char **pzErrMsg                 /* OUT: Error message (if rc!=SQLITE_OK) */
   124379 ){
   124380   int rc = SQLITE_OK;
   124381   unsigned int flags = *pFlags;
   124382   const char *zVfs = zDefaultVfs;
   124383   char *zFile;
   124384   char c;
   124385   int nUri = sqlite3Strlen30(zUri);
   124386 
   124387   assert( *pzErrMsg==0 );
   124388 
   124389   if( ((flags & SQLITE_OPEN_URI) || sqlite3GlobalConfig.bOpenUri)
   124390    && nUri>=5 && memcmp(zUri, "file:", 5)==0
   124391   ){
   124392     char *zOpt;
   124393     int eState;                   /* Parser state when parsing URI */
   124394     int iIn;                      /* Input character index */
   124395     int iOut = 0;                 /* Output character index */
   124396     int nByte = nUri+2;           /* Bytes of space to allocate */
   124397 
   124398     /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
   124399     ** method that there may be extra parameters following the file-name.  */
   124400     flags |= SQLITE_OPEN_URI;
   124401 
   124402     for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
   124403     zFile = sqlite3_malloc(nByte);
   124404     if( !zFile ) return SQLITE_NOMEM;
   124405 
   124406     iIn = 5;
   124407 #ifndef SQLITE_ALLOW_URI_AUTHORITY
   124408     /* Discard the scheme and authority segments of the URI. */
   124409     if( zUri[5]=='/' && zUri[6]=='/' ){
   124410       iIn = 7;
   124411       while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
   124412       if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
   124413         *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
   124414             iIn-7, &zUri[7]);
   124415         rc = SQLITE_ERROR;
   124416         goto parse_uri_out;
   124417       }
   124418     }
   124419 #endif
   124420 
   124421     /* Copy the filename and any query parameters into the zFile buffer.
   124422     ** Decode %HH escape codes along the way.
   124423     **
   124424     ** Within this loop, variable eState may be set to 0, 1 or 2, depending
   124425     ** on the parsing context. As follows:
   124426     **
   124427     **   0: Parsing file-name.
   124428     **   1: Parsing name section of a name=value query parameter.
   124429     **   2: Parsing value section of a name=value query parameter.
   124430     */
   124431     eState = 0;
   124432     while( (c = zUri[iIn])!=0 && c!='#' ){
   124433       iIn++;
   124434       if( c=='%'
   124435        && sqlite3Isxdigit(zUri[iIn])
   124436        && sqlite3Isxdigit(zUri[iIn+1])
   124437       ){
   124438         int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
   124439         octet += sqlite3HexToInt(zUri[iIn++]);
   124440 
   124441         assert( octet>=0 && octet<256 );
   124442         if( octet==0 ){
   124443           /* This branch is taken when "%00" appears within the URI. In this
   124444           ** case we ignore all text in the remainder of the path, name or
   124445           ** value currently being parsed. So ignore the current character
   124446           ** and skip to the next "?", "=" or "&", as appropriate. */
   124447           while( (c = zUri[iIn])!=0 && c!='#'
   124448               && (eState!=0 || c!='?')
   124449               && (eState!=1 || (c!='=' && c!='&'))
   124450               && (eState!=2 || c!='&')
   124451           ){
   124452             iIn++;
   124453           }
   124454           continue;
   124455         }
   124456         c = octet;
   124457       }else if( eState==1 && (c=='&' || c=='=') ){
   124458         if( zFile[iOut-1]==0 ){
   124459           /* An empty option name. Ignore this option altogether. */
   124460           while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
   124461           continue;
   124462         }
   124463         if( c=='&' ){
   124464           zFile[iOut++] = '\0';
   124465         }else{
   124466           eState = 2;
   124467         }
   124468         c = 0;
   124469       }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
   124470         c = 0;
   124471         eState = 1;
   124472       }
   124473       zFile[iOut++] = c;
   124474     }
   124475     if( eState==1 ) zFile[iOut++] = '\0';
   124476     zFile[iOut++] = '\0';
   124477     zFile[iOut++] = '\0';
   124478 
   124479     /* Check if there were any options specified that should be interpreted
   124480     ** here. Options that are interpreted here include "vfs" and those that
   124481     ** correspond to flags that may be passed to the sqlite3_open_v2()
   124482     ** method. */
   124483     zOpt = &zFile[sqlite3Strlen30(zFile)+1];
   124484     while( zOpt[0] ){
   124485       int nOpt = sqlite3Strlen30(zOpt);
   124486       char *zVal = &zOpt[nOpt+1];
   124487       int nVal = sqlite3Strlen30(zVal);
   124488 
   124489       if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
   124490         zVfs = zVal;
   124491       }else{
   124492         struct OpenMode {
   124493           const char *z;
   124494           int mode;
   124495         } *aMode = 0;
   124496         char *zModeType = 0;
   124497         int mask = 0;
   124498         int limit = 0;
   124499 
   124500         if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
   124501           static struct OpenMode aCacheMode[] = {
   124502             { "shared",  SQLITE_OPEN_SHAREDCACHE },
   124503             { "private", SQLITE_OPEN_PRIVATECACHE },
   124504             { 0, 0 }
   124505           };
   124506 
   124507           mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
   124508           aMode = aCacheMode;
   124509           limit = mask;
   124510           zModeType = "cache";
   124511         }
   124512         if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
   124513           static struct OpenMode aOpenMode[] = {
   124514             { "ro",  SQLITE_OPEN_READONLY },
   124515             { "rw",  SQLITE_OPEN_READWRITE },
   124516             { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
   124517             { "memory", SQLITE_OPEN_MEMORY },
   124518             { 0, 0 }
   124519           };
   124520 
   124521           mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
   124522                    | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
   124523           aMode = aOpenMode;
   124524           limit = mask & flags;
   124525           zModeType = "access";
   124526         }
   124527 
   124528         if( aMode ){
   124529           int i;
   124530           int mode = 0;
   124531           for(i=0; aMode[i].z; i++){
   124532             const char *z = aMode[i].z;
   124533             if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
   124534               mode = aMode[i].mode;
   124535               break;
   124536             }
   124537           }
   124538           if( mode==0 ){
   124539             *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
   124540             rc = SQLITE_ERROR;
   124541             goto parse_uri_out;
   124542           }
   124543           if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
   124544             *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
   124545                                         zModeType, zVal);
   124546             rc = SQLITE_PERM;
   124547             goto parse_uri_out;
   124548           }
   124549           flags = (flags & ~mask) | mode;
   124550         }
   124551       }
   124552 
   124553       zOpt = &zVal[nVal+1];
   124554     }
   124555 
   124556   }else{
   124557     zFile = sqlite3_malloc(nUri+2);
   124558     if( !zFile ) return SQLITE_NOMEM;
   124559     memcpy(zFile, zUri, nUri);
   124560     zFile[nUri] = '\0';
   124561     zFile[nUri+1] = '\0';
   124562     flags &= ~SQLITE_OPEN_URI;
   124563   }
   124564 
   124565   *ppVfs = sqlite3_vfs_find(zVfs);
   124566   if( *ppVfs==0 ){
   124567     *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
   124568     rc = SQLITE_ERROR;
   124569   }
   124570  parse_uri_out:
   124571   if( rc!=SQLITE_OK ){
   124572     sqlite3_free(zFile);
   124573     zFile = 0;
   124574   }
   124575   *pFlags = flags;
   124576   *pzFile = zFile;
   124577   return rc;
   124578 }
   124579 
   124580 
   124581 /*
   124582 ** This routine does the work of opening a database on behalf of
   124583 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
   124584 ** is UTF-8 encoded.
   124585 */
   124586 static int openDatabase(
   124587   const char *zFilename, /* Database filename UTF-8 encoded */
   124588   sqlite3 **ppDb,        /* OUT: Returned database handle */
   124589   unsigned int flags,    /* Operational flags */
   124590   const char *zVfs       /* Name of the VFS to use */
   124591 ){
   124592   sqlite3 *db;                    /* Store allocated handle here */
   124593   int rc;                         /* Return code */
   124594   int isThreadsafe;               /* True for threadsafe connections */
   124595   char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */
   124596   char *zErrMsg = 0;              /* Error message from sqlite3ParseUri() */
   124597 
   124598   *ppDb = 0;
   124599 #ifndef SQLITE_OMIT_AUTOINIT
   124600   rc = sqlite3_initialize();
   124601   if( rc ) return rc;
   124602 #endif
   124603 
   124604   /* Only allow sensible combinations of bits in the flags argument.
   124605   ** Throw an error if any non-sense combination is used.  If we
   124606   ** do not block illegal combinations here, it could trigger
   124607   ** assert() statements in deeper layers.  Sensible combinations
   124608   ** are:
   124609   **
   124610   **  1:  SQLITE_OPEN_READONLY
   124611   **  2:  SQLITE_OPEN_READWRITE
   124612   **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
   124613   */
   124614   assert( SQLITE_OPEN_READONLY  == 0x01 );
   124615   assert( SQLITE_OPEN_READWRITE == 0x02 );
   124616   assert( SQLITE_OPEN_CREATE    == 0x04 );
   124617   testcase( (1<<(flags&7))==0x02 ); /* READONLY */
   124618   testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
   124619   testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
   124620   if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE_BKPT;
   124621 
   124622   if( sqlite3GlobalConfig.bCoreMutex==0 ){
   124623     isThreadsafe = 0;
   124624   }else if( flags & SQLITE_OPEN_NOMUTEX ){
   124625     isThreadsafe = 0;
   124626   }else if( flags & SQLITE_OPEN_FULLMUTEX ){
   124627     isThreadsafe = 1;
   124628   }else{
   124629     isThreadsafe = sqlite3GlobalConfig.bFullMutex;
   124630   }
   124631   if( flags & SQLITE_OPEN_PRIVATECACHE ){
   124632     flags &= ~SQLITE_OPEN_SHAREDCACHE;
   124633   }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
   124634     flags |= SQLITE_OPEN_SHAREDCACHE;
   124635   }
   124636 
   124637   /* Remove harmful bits from the flags parameter
   124638   **
   124639   ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
   124640   ** dealt with in the previous code block.  Besides these, the only
   124641   ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
   124642   ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
   124643   ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask
   124644   ** off all other flags.
   124645   */
   124646   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
   124647                SQLITE_OPEN_EXCLUSIVE |
   124648                SQLITE_OPEN_MAIN_DB |
   124649                SQLITE_OPEN_TEMP_DB |
   124650                SQLITE_OPEN_TRANSIENT_DB |
   124651                SQLITE_OPEN_MAIN_JOURNAL |
   124652                SQLITE_OPEN_TEMP_JOURNAL |
   124653                SQLITE_OPEN_SUBJOURNAL |
   124654                SQLITE_OPEN_MASTER_JOURNAL |
   124655                SQLITE_OPEN_NOMUTEX |
   124656                SQLITE_OPEN_FULLMUTEX |
   124657                SQLITE_OPEN_WAL
   124658              );
   124659 
   124660   /* Allocate the sqlite data structure */
   124661   db = sqlite3MallocZero( sizeof(sqlite3) );
   124662   if( db==0 ) goto opendb_out;
   124663   if( isThreadsafe ){
   124664     db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
   124665     if( db->mutex==0 ){
   124666       sqlite3_free(db);
   124667       db = 0;
   124668       goto opendb_out;
   124669     }
   124670   }
   124671   sqlite3_mutex_enter(db->mutex);
   124672   db->errMask = 0xff;
   124673   db->nDb = 2;
   124674   db->magic = SQLITE_MAGIC_BUSY;
   124675   db->aDb = db->aDbStatic;
   124676 
   124677   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
   124678   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
   124679   db->autoCommit = 1;
   124680   db->nextAutovac = -1;
   124681   db->szMmap = sqlite3GlobalConfig.szMmap;
   124682   db->nextPagesize = 0;
   124683   db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
   124684 #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
   124685                  | SQLITE_AutoIndex
   124686 #endif
   124687 #if SQLITE_DEFAULT_FILE_FORMAT<4
   124688                  | SQLITE_LegacyFileFmt
   124689 #endif
   124690 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
   124691                  | SQLITE_LoadExtension
   124692 #endif
   124693 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
   124694                  | SQLITE_RecTriggers
   124695 #endif
   124696 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
   124697                  | SQLITE_ForeignKeys
   124698 #endif
   124699       ;
   124700   sqlite3HashInit(&db->aCollSeq);
   124701 #ifndef SQLITE_OMIT_VIRTUALTABLE
   124702   sqlite3HashInit(&db->aModule);
   124703 #endif
   124704 
   124705   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
   124706   ** and UTF-16, so add a version for each to avoid any unnecessary
   124707   ** conversions. The only error that can occur here is a malloc() failure.
   124708   */
   124709   createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
   124710   createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
   124711   createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
   124712   createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
   124713   if( db->mallocFailed ){
   124714     goto opendb_out;
   124715   }
   124716   db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
   124717   assert( db->pDfltColl!=0 );
   124718 
   124719   /* Also add a UTF-8 case-insensitive collation sequence. */
   124720   createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
   124721 
   124722   /* Parse the filename/URI argument. */
   124723   db->openFlags = flags;
   124724   rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
   124725   if( rc!=SQLITE_OK ){
   124726     if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
   124727     sqlite3Error(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
   124728     sqlite3_free(zErrMsg);
   124729     goto opendb_out;
   124730   }
   124731 
   124732   /* Open the backend database driver */
   124733   rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
   124734                         flags | SQLITE_OPEN_MAIN_DB);
   124735   if( rc!=SQLITE_OK ){
   124736     if( rc==SQLITE_IOERR_NOMEM ){
   124737       rc = SQLITE_NOMEM;
   124738     }
   124739     sqlite3Error(db, rc, 0);
   124740     goto opendb_out;
   124741   }
   124742   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
   124743   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
   124744 
   124745 
   124746   /* The default safety_level for the main database is 'full'; for the temp
   124747   ** database it is 'NONE'. This matches the pager layer defaults.
   124748   */
   124749   db->aDb[0].zName = "main";
   124750   db->aDb[0].safety_level = 3;
   124751   db->aDb[1].zName = "temp";
   124752   db->aDb[1].safety_level = 1;
   124753 
   124754   db->magic = SQLITE_MAGIC_OPEN;
   124755   if( db->mallocFailed ){
   124756     goto opendb_out;
   124757   }
   124758 
   124759   /* Register all built-in functions, but do not attempt to read the
   124760   ** database schema yet. This is delayed until the first time the database
   124761   ** is accessed.
   124762   */
   124763   sqlite3Error(db, SQLITE_OK, 0);
   124764   sqlite3RegisterBuiltinFunctions(db);
   124765 
   124766   /* Load automatic extensions - extensions that have been registered
   124767   ** using the sqlite3_automatic_extension() API.
   124768   */
   124769   rc = sqlite3_errcode(db);
   124770   if( rc==SQLITE_OK ){
   124771     sqlite3AutoLoadExtensions(db);
   124772     rc = sqlite3_errcode(db);
   124773     if( rc!=SQLITE_OK ){
   124774       goto opendb_out;
   124775     }
   124776   }
   124777 
   124778 #ifdef SQLITE_ENABLE_FTS1
   124779   if( !db->mallocFailed ){
   124780     extern int sqlite3Fts1Init(sqlite3*);
   124781     rc = sqlite3Fts1Init(db);
   124782   }
   124783 #endif
   124784 
   124785 #ifdef SQLITE_ENABLE_FTS2
   124786   if( !db->mallocFailed && rc==SQLITE_OK ){
   124787     extern int sqlite3Fts2Init(sqlite3*);
   124788     rc = sqlite3Fts2Init(db);
   124789   }
   124790 #endif
   124791 
   124792 #ifdef SQLITE_ENABLE_FTS3
   124793     if( !db->mallocFailed && rc==SQLITE_OK ){
   124794       rc = sqlite3Fts3Init(db);
   124795     }
   124796 #endif
   124797 
   124798 #ifdef SQLITE_ENABLE_ICU
   124799   if( !db->mallocFailed && rc==SQLITE_OK ){
   124800     rc = sqlite3IcuInit(db);
   124801   }
   124802 #endif
   124803 
   124804 #ifdef SQLITE_ENABLE_RTREE
   124805   if( !db->mallocFailed && rc==SQLITE_OK){
   124806     rc = sqlite3RtreeInit(db);
   124807   }
   124808 #endif
   124809 
   124810   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
   124811   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
   124812   ** mode.  Doing nothing at all also makes NORMAL the default.
   124813   */
   124814 #ifdef SQLITE_DEFAULT_LOCKING_MODE
   124815   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
   124816   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
   124817                           SQLITE_DEFAULT_LOCKING_MODE);
   124818 #endif
   124819 
   124820   if( rc ) sqlite3Error(db, rc, 0);
   124821 
   124822   /* Enable the lookaside-malloc subsystem */
   124823   setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
   124824                         sqlite3GlobalConfig.nLookaside);
   124825 
   124826   sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
   124827 
   124828 opendb_out:
   124829   sqlite3_free(zOpen);
   124830   if( db ){
   124831     assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
   124832     sqlite3_mutex_leave(db->mutex);
   124833   }
   124834   rc = sqlite3_errcode(db);
   124835   assert( db!=0 || rc==SQLITE_NOMEM );
   124836   if( rc==SQLITE_NOMEM ){
   124837     sqlite3_close(db);
   124838     db = 0;
   124839   }else if( rc!=SQLITE_OK ){
   124840     db->magic = SQLITE_MAGIC_SICK;
   124841   }
   124842   *ppDb = db;
   124843 #ifdef SQLITE_ENABLE_SQLLOG
   124844   if( sqlite3GlobalConfig.xSqllog ){
   124845     /* Opening a db handle. Fourth parameter is passed 0. */
   124846     void *pArg = sqlite3GlobalConfig.pSqllogArg;
   124847     sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
   124848   }
   124849 #endif
   124850   return sqlite3ApiExit(0, rc);
   124851 }
   124852 
   124853 /*
   124854 ** Open a new database handle.
   124855 */
   124856 SQLITE_API int sqlite3_open(
   124857   const char *zFilename,
   124858   sqlite3 **ppDb
   124859 ){
   124860   return openDatabase(zFilename, ppDb,
   124861                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
   124862 }
   124863 SQLITE_API int sqlite3_open_v2(
   124864   const char *filename,   /* Database filename (UTF-8) */
   124865   sqlite3 **ppDb,         /* OUT: SQLite db handle */
   124866   int flags,              /* Flags */
   124867   const char *zVfs        /* Name of VFS module to use */
   124868 ){
   124869   return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
   124870 }
   124871 
   124872 #ifndef SQLITE_OMIT_UTF16
   124873 /*
   124874 ** Open a new database handle.
   124875 */
   124876 SQLITE_API int sqlite3_open16(
   124877   const void *zFilename,
   124878   sqlite3 **ppDb
   124879 ){
   124880   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
   124881   sqlite3_value *pVal;
   124882   int rc;
   124883 
   124884   assert( zFilename );
   124885   assert( ppDb );
   124886   *ppDb = 0;
   124887 #ifndef SQLITE_OMIT_AUTOINIT
   124888   rc = sqlite3_initialize();
   124889   if( rc ) return rc;
   124890 #endif
   124891   pVal = sqlite3ValueNew(0);
   124892   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
   124893   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
   124894   if( zFilename8 ){
   124895     rc = openDatabase(zFilename8, ppDb,
   124896                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
   124897     assert( *ppDb || rc==SQLITE_NOMEM );
   124898     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
   124899       ENC(*ppDb) = SQLITE_UTF16NATIVE;
   124900     }
   124901   }else{
   124902     rc = SQLITE_NOMEM;
   124903   }
   124904   sqlite3ValueFree(pVal);
   124905 
   124906   return sqlite3ApiExit(0, rc);
   124907 }
   124908 #endif /* SQLITE_OMIT_UTF16 */
   124909 
   124910 /*
   124911 ** Register a new collation sequence with the database handle db.
   124912 */
   124913 SQLITE_API int sqlite3_create_collation(
   124914   sqlite3* db,
   124915   const char *zName,
   124916   int enc,
   124917   void* pCtx,
   124918   int(*xCompare)(void*,int,const void*,int,const void*)
   124919 ){
   124920   int rc;
   124921   sqlite3_mutex_enter(db->mutex);
   124922   assert( !db->mallocFailed );
   124923   rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, 0);
   124924   rc = sqlite3ApiExit(db, rc);
   124925   sqlite3_mutex_leave(db->mutex);
   124926   return rc;
   124927 }
   124928 
   124929 /*
   124930 ** Register a new collation sequence with the database handle db.
   124931 */
   124932 SQLITE_API int sqlite3_create_collation_v2(
   124933   sqlite3* db,
   124934   const char *zName,
   124935   int enc,
   124936   void* pCtx,
   124937   int(*xCompare)(void*,int,const void*,int,const void*),
   124938   void(*xDel)(void*)
   124939 ){
   124940   int rc;
   124941   sqlite3_mutex_enter(db->mutex);
   124942   assert( !db->mallocFailed );
   124943   rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
   124944   rc = sqlite3ApiExit(db, rc);
   124945   sqlite3_mutex_leave(db->mutex);
   124946   return rc;
   124947 }
   124948 
   124949 #ifndef SQLITE_OMIT_UTF16
   124950 /*
   124951 ** Register a new collation sequence with the database handle db.
   124952 */
   124953 SQLITE_API int sqlite3_create_collation16(
   124954   sqlite3* db,
   124955   const void *zName,
   124956   int enc,
   124957   void* pCtx,
   124958   int(*xCompare)(void*,int,const void*,int,const void*)
   124959 ){
   124960   int rc = SQLITE_OK;
   124961   char *zName8;
   124962   sqlite3_mutex_enter(db->mutex);
   124963   assert( !db->mallocFailed );
   124964   zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
   124965   if( zName8 ){
   124966     rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
   124967     sqlite3DbFree(db, zName8);
   124968   }
   124969   rc = sqlite3ApiExit(db, rc);
   124970   sqlite3_mutex_leave(db->mutex);
   124971   return rc;
   124972 }
   124973 #endif /* SQLITE_OMIT_UTF16 */
   124974 
   124975 /*
   124976 ** Register a collation sequence factory callback with the database handle
   124977 ** db. Replace any previously installed collation sequence factory.
   124978 */
   124979 SQLITE_API int sqlite3_collation_needed(
   124980   sqlite3 *db,
   124981   void *pCollNeededArg,
   124982   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
   124983 ){
   124984   sqlite3_mutex_enter(db->mutex);
   124985   db->xCollNeeded = xCollNeeded;
   124986   db->xCollNeeded16 = 0;
   124987   db->pCollNeededArg = pCollNeededArg;
   124988   sqlite3_mutex_leave(db->mutex);
   124989   return SQLITE_OK;
   124990 }
   124991 
   124992 #ifndef SQLITE_OMIT_UTF16
   124993 /*
   124994 ** Register a collation sequence factory callback with the database handle
   124995 ** db. Replace any previously installed collation sequence factory.
   124996 */
   124997 SQLITE_API int sqlite3_collation_needed16(
   124998   sqlite3 *db,
   124999   void *pCollNeededArg,
   125000   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
   125001 ){
   125002   sqlite3_mutex_enter(db->mutex);
   125003   db->xCollNeeded = 0;
   125004   db->xCollNeeded16 = xCollNeeded16;
   125005   db->pCollNeededArg = pCollNeededArg;
   125006   sqlite3_mutex_leave(db->mutex);
   125007   return SQLITE_OK;
   125008 }
   125009 #endif /* SQLITE_OMIT_UTF16 */
   125010 
   125011 #ifndef SQLITE_OMIT_DEPRECATED
   125012 /*
   125013 ** This function is now an anachronism. It used to be used to recover from a
   125014 ** malloc() failure, but SQLite now does this automatically.
   125015 */
   125016 SQLITE_API int sqlite3_global_recover(void){
   125017   return SQLITE_OK;
   125018 }
   125019 #endif
   125020 
   125021 /*
   125022 ** Test to see whether or not the database connection is in autocommit
   125023 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
   125024 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
   125025 ** by the next COMMIT or ROLLBACK.
   125026 */
   125027 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
   125028   return db->autoCommit;
   125029 }
   125030 
   125031 /*
   125032 ** The following routines are subtitutes for constants SQLITE_CORRUPT,
   125033 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
   125034 ** constants.  They server two purposes:
   125035 **
   125036 **   1.  Serve as a convenient place to set a breakpoint in a debugger
   125037 **       to detect when version error conditions occurs.
   125038 **
   125039 **   2.  Invoke sqlite3_log() to provide the source code location where
   125040 **       a low-level error is first detected.
   125041 */
   125042 SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
   125043   testcase( sqlite3GlobalConfig.xLog!=0 );
   125044   sqlite3_log(SQLITE_CORRUPT,
   125045               "database corruption at line %d of [%.10s]",
   125046               lineno, 20+sqlite3_sourceid());
   125047   return SQLITE_CORRUPT;
   125048 }
   125049 SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
   125050   testcase( sqlite3GlobalConfig.xLog!=0 );
   125051   sqlite3_log(SQLITE_MISUSE,
   125052               "misuse at line %d of [%.10s]",
   125053               lineno, 20+sqlite3_sourceid());
   125054   return SQLITE_MISUSE;
   125055 }
   125056 SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
   125057   testcase( sqlite3GlobalConfig.xLog!=0 );
   125058   sqlite3_log(SQLITE_CANTOPEN,
   125059               "cannot open file at line %d of [%.10s]",
   125060               lineno, 20+sqlite3_sourceid());
   125061   return SQLITE_CANTOPEN;
   125062 }
   125063 
   125064 
   125065 #ifndef SQLITE_OMIT_DEPRECATED
   125066 /*
   125067 ** This is a convenience routine that makes sure that all thread-specific
   125068 ** data for this thread has been deallocated.
   125069 **
   125070 ** SQLite no longer uses thread-specific data so this routine is now a
   125071 ** no-op.  It is retained for historical compatibility.
   125072 */
   125073 SQLITE_API void sqlite3_thread_cleanup(void){
   125074 }
   125075 #endif
   125076 
   125077 /*
   125078 ** Return meta information about a specific column of a database table.
   125079 ** See comment in sqlite3.h (sqlite.h.in) for details.
   125080 */
   125081 #ifdef SQLITE_ENABLE_COLUMN_METADATA
   125082 SQLITE_API int sqlite3_table_column_metadata(
   125083   sqlite3 *db,                /* Connection handle */
   125084   const char *zDbName,        /* Database name or NULL */
   125085   const char *zTableName,     /* Table name */
   125086   const char *zColumnName,    /* Column name */
   125087   char const **pzDataType,    /* OUTPUT: Declared data type */
   125088   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
   125089   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
   125090   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
   125091   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
   125092 ){
   125093   int rc;
   125094   char *zErrMsg = 0;
   125095   Table *pTab = 0;
   125096   Column *pCol = 0;
   125097   int iCol;
   125098 
   125099   char const *zDataType = 0;
   125100   char const *zCollSeq = 0;
   125101   int notnull = 0;
   125102   int primarykey = 0;
   125103   int autoinc = 0;
   125104 
   125105   /* Ensure the database schema has been loaded */
   125106   sqlite3_mutex_enter(db->mutex);
   125107   sqlite3BtreeEnterAll(db);
   125108   rc = sqlite3Init(db, &zErrMsg);
   125109   if( SQLITE_OK!=rc ){
   125110     goto error_out;
   125111   }
   125112 
   125113   /* Locate the table in question */
   125114   pTab = sqlite3FindTable(db, zTableName, zDbName);
   125115   if( !pTab || pTab->pSelect ){
   125116     pTab = 0;
   125117     goto error_out;
   125118   }
   125119 
   125120   /* Find the column for which info is requested */
   125121   if( sqlite3IsRowid(zColumnName) ){
   125122     iCol = pTab->iPKey;
   125123     if( iCol>=0 ){
   125124       pCol = &pTab->aCol[iCol];
   125125     }
   125126   }else{
   125127     for(iCol=0; iCol<pTab->nCol; iCol++){
   125128       pCol = &pTab->aCol[iCol];
   125129       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
   125130         break;
   125131       }
   125132     }
   125133     if( iCol==pTab->nCol ){
   125134       pTab = 0;
   125135       goto error_out;
   125136     }
   125137   }
   125138 
   125139   /* The following block stores the meta information that will be returned
   125140   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
   125141   ** and autoinc. At this point there are two possibilities:
   125142   **
   125143   **     1. The specified column name was rowid", "oid" or "_rowid_"
   125144   **        and there is no explicitly declared IPK column.
   125145   **
   125146   **     2. The table is not a view and the column name identified an
   125147   **        explicitly declared column. Copy meta information from *pCol.
   125148   */
   125149   if( pCol ){
   125150     zDataType = pCol->zType;
   125151     zCollSeq = pCol->zColl;
   125152     notnull = pCol->notNull!=0;
   125153     primarykey  = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
   125154     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
   125155   }else{
   125156     zDataType = "INTEGER";
   125157     primarykey = 1;
   125158   }
   125159   if( !zCollSeq ){
   125160     zCollSeq = "BINARY";
   125161   }
   125162 
   125163 error_out:
   125164   sqlite3BtreeLeaveAll(db);
   125165 
   125166   /* Whether the function call succeeded or failed, set the output parameters
   125167   ** to whatever their local counterparts contain. If an error did occur,
   125168   ** this has the effect of zeroing all output parameters.
   125169   */
   125170   if( pzDataType ) *pzDataType = zDataType;
   125171   if( pzCollSeq ) *pzCollSeq = zCollSeq;
   125172   if( pNotNull ) *pNotNull = notnull;
   125173   if( pPrimaryKey ) *pPrimaryKey = primarykey;
   125174   if( pAutoinc ) *pAutoinc = autoinc;
   125175 
   125176   if( SQLITE_OK==rc && !pTab ){
   125177     sqlite3DbFree(db, zErrMsg);
   125178     zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
   125179         zColumnName);
   125180     rc = SQLITE_ERROR;
   125181   }
   125182   sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
   125183   sqlite3DbFree(db, zErrMsg);
   125184   rc = sqlite3ApiExit(db, rc);
   125185   sqlite3_mutex_leave(db->mutex);
   125186   return rc;
   125187 }
   125188 #endif
   125189 
   125190 /*
   125191 ** Sleep for a little while.  Return the amount of time slept.
   125192 */
   125193 SQLITE_API int sqlite3_sleep(int ms){
   125194   sqlite3_vfs *pVfs;
   125195   int rc;
   125196   pVfs = sqlite3_vfs_find(0);
   125197   if( pVfs==0 ) return 0;
   125198 
   125199   /* This function works in milliseconds, but the underlying OsSleep()
   125200   ** API uses microseconds. Hence the 1000's.
   125201   */
   125202   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
   125203   return rc;
   125204 }
   125205 
   125206 /*
   125207 ** Enable or disable the extended result codes.
   125208 */
   125209 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
   125210   sqlite3_mutex_enter(db->mutex);
   125211   db->errMask = onoff ? 0xffffffff : 0xff;
   125212   sqlite3_mutex_leave(db->mutex);
   125213   return SQLITE_OK;
   125214 }
   125215 
   125216 /*
   125217 ** Invoke the xFileControl method on a particular database.
   125218 */
   125219 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
   125220   int rc = SQLITE_ERROR;
   125221   Btree *pBtree;
   125222 
   125223   sqlite3_mutex_enter(db->mutex);
   125224   pBtree = sqlite3DbNameToBtree(db, zDbName);
   125225   if( pBtree ){
   125226     Pager *pPager;
   125227     sqlite3_file *fd;
   125228     sqlite3BtreeEnter(pBtree);
   125229     pPager = sqlite3BtreePager(pBtree);
   125230     assert( pPager!=0 );
   125231     fd = sqlite3PagerFile(pPager);
   125232     assert( fd!=0 );
   125233     if( op==SQLITE_FCNTL_FILE_POINTER ){
   125234       *(sqlite3_file**)pArg = fd;
   125235       rc = SQLITE_OK;
   125236     }else if( fd->pMethods ){
   125237       rc = sqlite3OsFileControl(fd, op, pArg);
   125238     }else{
   125239       rc = SQLITE_NOTFOUND;
   125240     }
   125241     sqlite3BtreeLeave(pBtree);
   125242   }
   125243   sqlite3_mutex_leave(db->mutex);
   125244   return rc;
   125245 }
   125246 
   125247 /*
   125248 ** Interface to the testing logic.
   125249 */
   125250 SQLITE_API int sqlite3_test_control(int op, ...){
   125251   int rc = 0;
   125252 #ifndef SQLITE_OMIT_BUILTIN_TEST
   125253   va_list ap;
   125254   va_start(ap, op);
   125255   switch( op ){
   125256 
   125257     /*
   125258     ** Save the current state of the PRNG.
   125259     */
   125260     case SQLITE_TESTCTRL_PRNG_SAVE: {
   125261       sqlite3PrngSaveState();
   125262       break;
   125263     }
   125264 
   125265     /*
   125266     ** Restore the state of the PRNG to the last state saved using
   125267     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
   125268     ** this verb acts like PRNG_RESET.
   125269     */
   125270     case SQLITE_TESTCTRL_PRNG_RESTORE: {
   125271       sqlite3PrngRestoreState();
   125272       break;
   125273     }
   125274 
   125275     /*
   125276     ** Reset the PRNG back to its uninitialized state.  The next call
   125277     ** to sqlite3_randomness() will reseed the PRNG using a single call
   125278     ** to the xRandomness method of the default VFS.
   125279     */
   125280     case SQLITE_TESTCTRL_PRNG_RESET: {
   125281       sqlite3_randomness(0,0);
   125282       break;
   125283     }
   125284 
   125285     /*
   125286     **  sqlite3_test_control(BITVEC_TEST, size, program)
   125287     **
   125288     ** Run a test against a Bitvec object of size.  The program argument
   125289     ** is an array of integers that defines the test.  Return -1 on a
   125290     ** memory allocation error, 0 on success, or non-zero for an error.
   125291     ** See the sqlite3BitvecBuiltinTest() for additional information.
   125292     */
   125293     case SQLITE_TESTCTRL_BITVEC_TEST: {
   125294       int sz = va_arg(ap, int);
   125295       int *aProg = va_arg(ap, int*);
   125296       rc = sqlite3BitvecBuiltinTest(sz, aProg);
   125297       break;
   125298     }
   125299 
   125300     /*
   125301     **  sqlite3_test_control(FAULT_INSTALL, xCallback)
   125302     **
   125303     ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
   125304     ** if xCallback is not NULL.
   125305     **
   125306     ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
   125307     ** is called immediately after installing the new callback and the return
   125308     ** value from sqlite3FaultSim(0) becomes the return from
   125309     ** sqlite3_test_control().
   125310     */
   125311     case SQLITE_TESTCTRL_FAULT_INSTALL: {
   125312       /* MSVC is picky about pulling func ptrs from va lists.
   125313       ** http://support.microsoft.com/kb/47961
   125314       ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
   125315       */
   125316       typedef int(*TESTCALLBACKFUNC_t)(int);
   125317       sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
   125318       rc = sqlite3FaultSim(0);
   125319       break;
   125320     }
   125321 
   125322     /*
   125323     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
   125324     **
   125325     ** Register hooks to call to indicate which malloc() failures
   125326     ** are benign.
   125327     */
   125328     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
   125329       typedef void (*void_function)(void);
   125330       void_function xBenignBegin;
   125331       void_function xBenignEnd;
   125332       xBenignBegin = va_arg(ap, void_function);
   125333       xBenignEnd = va_arg(ap, void_function);
   125334       sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
   125335       break;
   125336     }
   125337 
   125338     /*
   125339     **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
   125340     **
   125341     ** Set the PENDING byte to the value in the argument, if X>0.
   125342     ** Make no changes if X==0.  Return the value of the pending byte
   125343     ** as it existing before this routine was called.
   125344     **
   125345     ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
   125346     ** an incompatible database file format.  Changing the PENDING byte
   125347     ** while any database connection is open results in undefined and
   125348     ** dileterious behavior.
   125349     */
   125350     case SQLITE_TESTCTRL_PENDING_BYTE: {
   125351       rc = PENDING_BYTE;
   125352 #ifndef SQLITE_OMIT_WSD
   125353       {
   125354         unsigned int newVal = va_arg(ap, unsigned int);
   125355         if( newVal ) sqlite3PendingByte = newVal;
   125356       }
   125357 #endif
   125358       break;
   125359     }
   125360 
   125361     /*
   125362     **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
   125363     **
   125364     ** This action provides a run-time test to see whether or not
   125365     ** assert() was enabled at compile-time.  If X is true and assert()
   125366     ** is enabled, then the return value is true.  If X is true and
   125367     ** assert() is disabled, then the return value is zero.  If X is
   125368     ** false and assert() is enabled, then the assertion fires and the
   125369     ** process aborts.  If X is false and assert() is disabled, then the
   125370     ** return value is zero.
   125371     */
   125372     case SQLITE_TESTCTRL_ASSERT: {
   125373       volatile int x = 0;
   125374       assert( (x = va_arg(ap,int))!=0 );
   125375       rc = x;
   125376       break;
   125377     }
   125378 
   125379 
   125380     /*
   125381     **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
   125382     **
   125383     ** This action provides a run-time test to see how the ALWAYS and
   125384     ** NEVER macros were defined at compile-time.
   125385     **
   125386     ** The return value is ALWAYS(X).
   125387     **
   125388     ** The recommended test is X==2.  If the return value is 2, that means
   125389     ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
   125390     ** default setting.  If the return value is 1, then ALWAYS() is either
   125391     ** hard-coded to true or else it asserts if its argument is false.
   125392     ** The first behavior (hard-coded to true) is the case if
   125393     ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
   125394     ** behavior (assert if the argument to ALWAYS() is false) is the case if
   125395     ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
   125396     **
   125397     ** The run-time test procedure might look something like this:
   125398     **
   125399     **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
   125400     **      // ALWAYS() and NEVER() are no-op pass-through macros
   125401     **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
   125402     **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
   125403     **    }else{
   125404     **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
   125405     **    }
   125406     */
   125407     case SQLITE_TESTCTRL_ALWAYS: {
   125408       int x = va_arg(ap,int);
   125409       rc = ALWAYS(x);
   125410       break;
   125411     }
   125412 
   125413     /*
   125414     **   sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
   125415     **
   125416     ** The integer returned reveals the byte-order of the computer on which
   125417     ** SQLite is running:
   125418     **
   125419     **       1     big-endian,    determined at run-time
   125420     **      10     little-endian, determined at run-time
   125421     **  432101     big-endian,    determined at compile-time
   125422     **  123410     little-endian, determined at compile-time
   125423     */
   125424     case SQLITE_TESTCTRL_BYTEORDER: {
   125425       rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
   125426       break;
   125427     }
   125428 
   125429     /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
   125430     **
   125431     ** Set the nReserve size to N for the main database on the database
   125432     ** connection db.
   125433     */
   125434     case SQLITE_TESTCTRL_RESERVE: {
   125435       sqlite3 *db = va_arg(ap, sqlite3*);
   125436       int x = va_arg(ap,int);
   125437       sqlite3_mutex_enter(db->mutex);
   125438       sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
   125439       sqlite3_mutex_leave(db->mutex);
   125440       break;
   125441     }
   125442 
   125443     /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
   125444     **
   125445     ** Enable or disable various optimizations for testing purposes.  The
   125446     ** argument N is a bitmask of optimizations to be disabled.  For normal
   125447     ** operation N should be 0.  The idea is that a test program (like the
   125448     ** SQL Logic Test or SLT test module) can run the same SQL multiple times
   125449     ** with various optimizations disabled to verify that the same answer
   125450     ** is obtained in every case.
   125451     */
   125452     case SQLITE_TESTCTRL_OPTIMIZATIONS: {
   125453       sqlite3 *db = va_arg(ap, sqlite3*);
   125454       db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
   125455       break;
   125456     }
   125457 
   125458 #ifdef SQLITE_N_KEYWORD
   125459     /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
   125460     **
   125461     ** If zWord is a keyword recognized by the parser, then return the
   125462     ** number of keywords.  Or if zWord is not a keyword, return 0.
   125463     **
   125464     ** This test feature is only available in the amalgamation since
   125465     ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
   125466     ** is built using separate source files.
   125467     */
   125468     case SQLITE_TESTCTRL_ISKEYWORD: {
   125469       const char *zWord = va_arg(ap, const char*);
   125470       int n = sqlite3Strlen30(zWord);
   125471       rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
   125472       break;
   125473     }
   125474 #endif
   125475 
   125476     /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
   125477     **
   125478     ** Pass pFree into sqlite3ScratchFree().
   125479     ** If sz>0 then allocate a scratch buffer into pNew.
   125480     */
   125481     case SQLITE_TESTCTRL_SCRATCHMALLOC: {
   125482       void *pFree, **ppNew;
   125483       int sz;
   125484       sz = va_arg(ap, int);
   125485       ppNew = va_arg(ap, void**);
   125486       pFree = va_arg(ap, void*);
   125487       if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
   125488       sqlite3ScratchFree(pFree);
   125489       break;
   125490     }
   125491 
   125492     /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
   125493     **
   125494     ** If parameter onoff is non-zero, configure the wrappers so that all
   125495     ** subsequent calls to localtime() and variants fail. If onoff is zero,
   125496     ** undo this setting.
   125497     */
   125498     case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
   125499       sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
   125500       break;
   125501     }
   125502 
   125503 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
   125504     /*   sqlite3_test_control(SQLITE_TESTCTRL_EXPLAIN_STMT,
   125505     **                        sqlite3_stmt*,const char**);
   125506     **
   125507     ** If compiled with SQLITE_ENABLE_TREE_EXPLAIN, each sqlite3_stmt holds
   125508     ** a string that describes the optimized parse tree.  This test-control
   125509     ** returns a pointer to that string.
   125510     */
   125511     case SQLITE_TESTCTRL_EXPLAIN_STMT: {
   125512       sqlite3_stmt *pStmt = va_arg(ap, sqlite3_stmt*);
   125513       const char **pzRet = va_arg(ap, const char**);
   125514       *pzRet = sqlite3VdbeExplanation((Vdbe*)pStmt);
   125515       break;
   125516     }
   125517 #endif
   125518 
   125519     /*   sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
   125520     **
   125521     ** Set or clear a flag that indicates that the database file is always well-
   125522     ** formed and never corrupt.  This flag is clear by default, indicating that
   125523     ** database files might have arbitrary corruption.  Setting the flag during
   125524     ** testing causes certain assert() statements in the code to be activated
   125525     ** that demonstrat invariants on well-formed database files.
   125526     */
   125527     case SQLITE_TESTCTRL_NEVER_CORRUPT: {
   125528       sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
   125529       break;
   125530     }
   125531 
   125532 
   125533     /*   sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
   125534     **
   125535     ** Set the VDBE coverage callback function to xCallback with context
   125536     ** pointer ptr.
   125537     */
   125538     case SQLITE_TESTCTRL_VDBE_COVERAGE: {
   125539 #ifdef SQLITE_VDBE_COVERAGE
   125540       typedef void (*branch_callback)(void*,int,u8,u8);
   125541       sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
   125542       sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
   125543 #endif
   125544       break;
   125545     }
   125546 
   125547     /*   sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
   125548     **
   125549     ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
   125550     ** not.
   125551     */
   125552     case SQLITE_TESTCTRL_ISINIT: {
   125553       if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
   125554       break;
   125555     }
   125556 
   125557   }
   125558   va_end(ap);
   125559 #endif /* SQLITE_OMIT_BUILTIN_TEST */
   125560   return rc;
   125561 }
   125562 
   125563 /*
   125564 ** This is a utility routine, useful to VFS implementations, that checks
   125565 ** to see if a database file was a URI that contained a specific query
   125566 ** parameter, and if so obtains the value of the query parameter.
   125567 **
   125568 ** The zFilename argument is the filename pointer passed into the xOpen()
   125569 ** method of a VFS implementation.  The zParam argument is the name of the
   125570 ** query parameter we seek.  This routine returns the value of the zParam
   125571 ** parameter if it exists.  If the parameter does not exist, this routine
   125572 ** returns a NULL pointer.
   125573 */
   125574 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
   125575   if( zFilename==0 ) return 0;
   125576   zFilename += sqlite3Strlen30(zFilename) + 1;
   125577   while( zFilename[0] ){
   125578     int x = strcmp(zFilename, zParam);
   125579     zFilename += sqlite3Strlen30(zFilename) + 1;
   125580     if( x==0 ) return zFilename;
   125581     zFilename += sqlite3Strlen30(zFilename) + 1;
   125582   }
   125583   return 0;
   125584 }
   125585 
   125586 /*
   125587 ** Return a boolean value for a query parameter.
   125588 */
   125589 SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
   125590   const char *z = sqlite3_uri_parameter(zFilename, zParam);
   125591   bDflt = bDflt!=0;
   125592   return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
   125593 }
   125594 
   125595 /*
   125596 ** Return a 64-bit integer value for a query parameter.
   125597 */
   125598 SQLITE_API sqlite3_int64 sqlite3_uri_int64(
   125599   const char *zFilename,    /* Filename as passed to xOpen */
   125600   const char *zParam,       /* URI parameter sought */
   125601   sqlite3_int64 bDflt       /* return if parameter is missing */
   125602 ){
   125603   const char *z = sqlite3_uri_parameter(zFilename, zParam);
   125604   sqlite3_int64 v;
   125605   if( z && sqlite3DecOrHexToI64(z, &v)==SQLITE_OK ){
   125606     bDflt = v;
   125607   }
   125608   return bDflt;
   125609 }
   125610 
   125611 /*
   125612 ** Return the Btree pointer identified by zDbName.  Return NULL if not found.
   125613 */
   125614 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
   125615   int i;
   125616   for(i=0; i<db->nDb; i++){
   125617     if( db->aDb[i].pBt
   125618      && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
   125619     ){
   125620       return db->aDb[i].pBt;
   125621     }
   125622   }
   125623   return 0;
   125624 }
   125625 
   125626 /*
   125627 ** Return the filename of the database associated with a database
   125628 ** connection.
   125629 */
   125630 SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
   125631   Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
   125632   return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
   125633 }
   125634 
   125635 /*
   125636 ** Return 1 if database is read-only or 0 if read/write.  Return -1 if
   125637 ** no such database exists.
   125638 */
   125639 SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
   125640   Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
   125641   return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
   125642 }
   125643 
   125644 /************** End of main.c ************************************************/
   125645 /************** Begin file notify.c ******************************************/
   125646 /*
   125647 ** 2009 March 3
   125648 **
   125649 ** The author disclaims copyright to this source code.  In place of
   125650 ** a legal notice, here is a blessing:
   125651 **
   125652 **    May you do good and not evil.
   125653 **    May you find forgiveness for yourself and forgive others.
   125654 **    May you share freely, never taking more than you give.
   125655 **
   125656 *************************************************************************
   125657 **
   125658 ** This file contains the implementation of the sqlite3_unlock_notify()
   125659 ** API method and its associated functionality.
   125660 */
   125661 
   125662 /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
   125663 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
   125664 
   125665 /*
   125666 ** Public interfaces:
   125667 **
   125668 **   sqlite3ConnectionBlocked()
   125669 **   sqlite3ConnectionUnlocked()
   125670 **   sqlite3ConnectionClosed()
   125671 **   sqlite3_unlock_notify()
   125672 */
   125673 
   125674 #define assertMutexHeld() \
   125675   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
   125676 
   125677 /*
   125678 ** Head of a linked list of all sqlite3 objects created by this process
   125679 ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
   125680 ** is not NULL. This variable may only accessed while the STATIC_MASTER
   125681 ** mutex is held.
   125682 */
   125683 static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
   125684 
   125685 #ifndef NDEBUG
   125686 /*
   125687 ** This function is a complex assert() that verifies the following
   125688 ** properties of the blocked connections list:
   125689 **
   125690 **   1) Each entry in the list has a non-NULL value for either
   125691 **      pUnlockConnection or pBlockingConnection, or both.
   125692 **
   125693 **   2) All entries in the list that share a common value for
   125694 **      xUnlockNotify are grouped together.
   125695 **
   125696 **   3) If the argument db is not NULL, then none of the entries in the
   125697 **      blocked connections list have pUnlockConnection or pBlockingConnection
   125698 **      set to db. This is used when closing connection db.
   125699 */
   125700 static void checkListProperties(sqlite3 *db){
   125701   sqlite3 *p;
   125702   for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
   125703     int seen = 0;
   125704     sqlite3 *p2;
   125705 
   125706     /* Verify property (1) */
   125707     assert( p->pUnlockConnection || p->pBlockingConnection );
   125708 
   125709     /* Verify property (2) */
   125710     for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
   125711       if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
   125712       assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
   125713       assert( db==0 || p->pUnlockConnection!=db );
   125714       assert( db==0 || p->pBlockingConnection!=db );
   125715     }
   125716   }
   125717 }
   125718 #else
   125719 # define checkListProperties(x)
   125720 #endif
   125721 
   125722 /*
   125723 ** Remove connection db from the blocked connections list. If connection
   125724 ** db is not currently a part of the list, this function is a no-op.
   125725 */
   125726 static void removeFromBlockedList(sqlite3 *db){
   125727   sqlite3 **pp;
   125728   assertMutexHeld();
   125729   for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
   125730     if( *pp==db ){
   125731       *pp = (*pp)->pNextBlocked;
   125732       break;
   125733     }
   125734   }
   125735 }
   125736 
   125737 /*
   125738 ** Add connection db to the blocked connections list. It is assumed
   125739 ** that it is not already a part of the list.
   125740 */
   125741 static void addToBlockedList(sqlite3 *db){
   125742   sqlite3 **pp;
   125743   assertMutexHeld();
   125744   for(
   125745     pp=&sqlite3BlockedList;
   125746     *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
   125747     pp=&(*pp)->pNextBlocked
   125748   );
   125749   db->pNextBlocked = *pp;
   125750   *pp = db;
   125751 }
   125752 
   125753 /*
   125754 ** Obtain the STATIC_MASTER mutex.
   125755 */
   125756 static void enterMutex(void){
   125757   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   125758   checkListProperties(0);
   125759 }
   125760 
   125761 /*
   125762 ** Release the STATIC_MASTER mutex.
   125763 */
   125764 static void leaveMutex(void){
   125765   assertMutexHeld();
   125766   checkListProperties(0);
   125767   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   125768 }
   125769 
   125770 /*
   125771 ** Register an unlock-notify callback.
   125772 **
   125773 ** This is called after connection "db" has attempted some operation
   125774 ** but has received an SQLITE_LOCKED error because another connection
   125775 ** (call it pOther) in the same process was busy using the same shared
   125776 ** cache.  pOther is found by looking at db->pBlockingConnection.
   125777 **
   125778 ** If there is no blocking connection, the callback is invoked immediately,
   125779 ** before this routine returns.
   125780 **
   125781 ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
   125782 ** a deadlock.
   125783 **
   125784 ** Otherwise, make arrangements to invoke xNotify when pOther drops
   125785 ** its locks.
   125786 **
   125787 ** Each call to this routine overrides any prior callbacks registered
   125788 ** on the same "db".  If xNotify==0 then any prior callbacks are immediately
   125789 ** cancelled.
   125790 */
   125791 SQLITE_API int sqlite3_unlock_notify(
   125792   sqlite3 *db,
   125793   void (*xNotify)(void **, int),
   125794   void *pArg
   125795 ){
   125796   int rc = SQLITE_OK;
   125797 
   125798   sqlite3_mutex_enter(db->mutex);
   125799   enterMutex();
   125800 
   125801   if( xNotify==0 ){
   125802     removeFromBlockedList(db);
   125803     db->pBlockingConnection = 0;
   125804     db->pUnlockConnection = 0;
   125805     db->xUnlockNotify = 0;
   125806     db->pUnlockArg = 0;
   125807   }else if( 0==db->pBlockingConnection ){
   125808     /* The blocking transaction has been concluded. Or there never was a
   125809     ** blocking transaction. In either case, invoke the notify callback
   125810     ** immediately.
   125811     */
   125812     xNotify(&pArg, 1);
   125813   }else{
   125814     sqlite3 *p;
   125815 
   125816     for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
   125817     if( p ){
   125818       rc = SQLITE_LOCKED;              /* Deadlock detected. */
   125819     }else{
   125820       db->pUnlockConnection = db->pBlockingConnection;
   125821       db->xUnlockNotify = xNotify;
   125822       db->pUnlockArg = pArg;
   125823       removeFromBlockedList(db);
   125824       addToBlockedList(db);
   125825     }
   125826   }
   125827 
   125828   leaveMutex();
   125829   assert( !db->mallocFailed );
   125830   sqlite3Error(db, rc, (rc?"database is deadlocked":0));
   125831   sqlite3_mutex_leave(db->mutex);
   125832   return rc;
   125833 }
   125834 
   125835 /*
   125836 ** This function is called while stepping or preparing a statement
   125837 ** associated with connection db. The operation will return SQLITE_LOCKED
   125838 ** to the user because it requires a lock that will not be available
   125839 ** until connection pBlocker concludes its current transaction.
   125840 */
   125841 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
   125842   enterMutex();
   125843   if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
   125844     addToBlockedList(db);
   125845   }
   125846   db->pBlockingConnection = pBlocker;
   125847   leaveMutex();
   125848 }
   125849 
   125850 /*
   125851 ** This function is called when
   125852 ** the transaction opened by database db has just finished. Locks held
   125853 ** by database connection db have been released.
   125854 **
   125855 ** This function loops through each entry in the blocked connections
   125856 ** list and does the following:
   125857 **
   125858 **   1) If the sqlite3.pBlockingConnection member of a list entry is
   125859 **      set to db, then set pBlockingConnection=0.
   125860 **
   125861 **   2) If the sqlite3.pUnlockConnection member of a list entry is
   125862 **      set to db, then invoke the configured unlock-notify callback and
   125863 **      set pUnlockConnection=0.
   125864 **
   125865 **   3) If the two steps above mean that pBlockingConnection==0 and
   125866 **      pUnlockConnection==0, remove the entry from the blocked connections
   125867 **      list.
   125868 */
   125869 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
   125870   void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
   125871   int nArg = 0;                            /* Number of entries in aArg[] */
   125872   sqlite3 **pp;                            /* Iterator variable */
   125873   void **aArg;               /* Arguments to the unlock callback */
   125874   void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
   125875   void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
   125876 
   125877   aArg = aStatic;
   125878   enterMutex();         /* Enter STATIC_MASTER mutex */
   125879 
   125880   /* This loop runs once for each entry in the blocked-connections list. */
   125881   for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
   125882     sqlite3 *p = *pp;
   125883 
   125884     /* Step 1. */
   125885     if( p->pBlockingConnection==db ){
   125886       p->pBlockingConnection = 0;
   125887     }
   125888 
   125889     /* Step 2. */
   125890     if( p->pUnlockConnection==db ){
   125891       assert( p->xUnlockNotify );
   125892       if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
   125893         xUnlockNotify(aArg, nArg);
   125894         nArg = 0;
   125895       }
   125896 
   125897       sqlite3BeginBenignMalloc();
   125898       assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
   125899       assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
   125900       if( (!aDyn && nArg==(int)ArraySize(aStatic))
   125901        || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
   125902       ){
   125903         /* The aArg[] array needs to grow. */
   125904         void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
   125905         if( pNew ){
   125906           memcpy(pNew, aArg, nArg*sizeof(void *));
   125907           sqlite3_free(aDyn);
   125908           aDyn = aArg = pNew;
   125909         }else{
   125910           /* This occurs when the array of context pointers that need to
   125911           ** be passed to the unlock-notify callback is larger than the
   125912           ** aStatic[] array allocated on the stack and the attempt to
   125913           ** allocate a larger array from the heap has failed.
   125914           **
   125915           ** This is a difficult situation to handle. Returning an error
   125916           ** code to the caller is insufficient, as even if an error code
   125917           ** is returned the transaction on connection db will still be
   125918           ** closed and the unlock-notify callbacks on blocked connections
   125919           ** will go unissued. This might cause the application to wait
   125920           ** indefinitely for an unlock-notify callback that will never
   125921           ** arrive.
   125922           **
   125923           ** Instead, invoke the unlock-notify callback with the context
   125924           ** array already accumulated. We can then clear the array and
   125925           ** begin accumulating any further context pointers without
   125926           ** requiring any dynamic allocation. This is sub-optimal because
   125927           ** it means that instead of one callback with a large array of
   125928           ** context pointers the application will receive two or more
   125929           ** callbacks with smaller arrays of context pointers, which will
   125930           ** reduce the applications ability to prioritize multiple
   125931           ** connections. But it is the best that can be done under the
   125932           ** circumstances.
   125933           */
   125934           xUnlockNotify(aArg, nArg);
   125935           nArg = 0;
   125936         }
   125937       }
   125938       sqlite3EndBenignMalloc();
   125939 
   125940       aArg[nArg++] = p->pUnlockArg;
   125941       xUnlockNotify = p->xUnlockNotify;
   125942       p->pUnlockConnection = 0;
   125943       p->xUnlockNotify = 0;
   125944       p->pUnlockArg = 0;
   125945     }
   125946 
   125947     /* Step 3. */
   125948     if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
   125949       /* Remove connection p from the blocked connections list. */
   125950       *pp = p->pNextBlocked;
   125951       p->pNextBlocked = 0;
   125952     }else{
   125953       pp = &p->pNextBlocked;
   125954     }
   125955   }
   125956 
   125957   if( nArg!=0 ){
   125958     xUnlockNotify(aArg, nArg);
   125959   }
   125960   sqlite3_free(aDyn);
   125961   leaveMutex();         /* Leave STATIC_MASTER mutex */
   125962 }
   125963 
   125964 /*
   125965 ** This is called when the database connection passed as an argument is
   125966 ** being closed. The connection is removed from the blocked list.
   125967 */
   125968 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
   125969   sqlite3ConnectionUnlocked(db);
   125970   enterMutex();
   125971   removeFromBlockedList(db);
   125972   checkListProperties(db);
   125973   leaveMutex();
   125974 }
   125975 #endif
   125976 
   125977 /************** End of notify.c **********************************************/
   125978 /************** Begin file fts3.c ********************************************/
   125979 /*
   125980 ** 2006 Oct 10
   125981 **
   125982 ** The author disclaims copyright to this source code.  In place of
   125983 ** a legal notice, here is a blessing:
   125984 **
   125985 **    May you do good and not evil.
   125986 **    May you find forgiveness for yourself and forgive others.
   125987 **    May you share freely, never taking more than you give.
   125988 **
   125989 ******************************************************************************
   125990 **
   125991 ** This is an SQLite module implementing full-text search.
   125992 */
   125993 
   125994 /*
   125995 ** The code in this file is only compiled if:
   125996 **
   125997 **     * The FTS3 module is being built as an extension
   125998 **       (in which case SQLITE_CORE is not defined), or
   125999 **
   126000 **     * The FTS3 module is being built into the core of
   126001 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
   126002 */
   126003 
   126004 /* The full-text index is stored in a series of b+tree (-like)
   126005 ** structures called segments which map terms to doclists.  The
   126006 ** structures are like b+trees in layout, but are constructed from the
   126007 ** bottom up in optimal fashion and are not updatable.  Since trees
   126008 ** are built from the bottom up, things will be described from the
   126009 ** bottom up.
   126010 **
   126011 **
   126012 **** Varints ****
   126013 ** The basic unit of encoding is a variable-length integer called a
   126014 ** varint.  We encode variable-length integers in little-endian order
   126015 ** using seven bits * per byte as follows:
   126016 **
   126017 ** KEY:
   126018 **         A = 0xxxxxxx    7 bits of data and one flag bit
   126019 **         B = 1xxxxxxx    7 bits of data and one flag bit
   126020 **
   126021 **  7 bits - A
   126022 ** 14 bits - BA
   126023 ** 21 bits - BBA
   126024 ** and so on.
   126025 **
   126026 ** This is similar in concept to how sqlite encodes "varints" but
   126027 ** the encoding is not the same.  SQLite varints are big-endian
   126028 ** are are limited to 9 bytes in length whereas FTS3 varints are
   126029 ** little-endian and can be up to 10 bytes in length (in theory).
   126030 **
   126031 ** Example encodings:
   126032 **
   126033 **     1:    0x01
   126034 **   127:    0x7f
   126035 **   128:    0x81 0x00
   126036 **
   126037 **
   126038 **** Document lists ****
   126039 ** A doclist (document list) holds a docid-sorted list of hits for a
   126040 ** given term.  Doclists hold docids and associated token positions.
   126041 ** A docid is the unique integer identifier for a single document.
   126042 ** A position is the index of a word within the document.  The first
   126043 ** word of the document has a position of 0.
   126044 **
   126045 ** FTS3 used to optionally store character offsets using a compile-time
   126046 ** option.  But that functionality is no longer supported.
   126047 **
   126048 ** A doclist is stored like this:
   126049 **
   126050 ** array {
   126051 **   varint docid;          (delta from previous doclist)
   126052 **   array {                (position list for column 0)
   126053 **     varint position;     (2 more than the delta from previous position)
   126054 **   }
   126055 **   array {
   126056 **     varint POS_COLUMN;   (marks start of position list for new column)
   126057 **     varint column;       (index of new column)
   126058 **     array {
   126059 **       varint position;   (2 more than the delta from previous position)
   126060 **     }
   126061 **   }
   126062 **   varint POS_END;        (marks end of positions for this document.
   126063 ** }
   126064 **
   126065 ** Here, array { X } means zero or more occurrences of X, adjacent in
   126066 ** memory.  A "position" is an index of a token in the token stream
   126067 ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
   126068 ** in the same logical place as the position element, and act as sentinals
   126069 ** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
   126070 ** The positions numbers are not stored literally but rather as two more
   126071 ** than the difference from the prior position, or the just the position plus
   126072 ** 2 for the first position.  Example:
   126073 **
   126074 **   label:       A B C D E  F  G H   I  J K
   126075 **   value:     123 5 9 1 1 14 35 0 234 72 0
   126076 **
   126077 ** The 123 value is the first docid.  For column zero in this document
   126078 ** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
   126079 ** at D signals the start of a new column; the 1 at E indicates that the
   126080 ** new column is column number 1.  There are two positions at 12 and 45
   126081 ** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
   126082 ** 234 at I is the delta to next docid (357).  It has one position 70
   126083 ** (72-2) and then terminates with the 0 at K.
   126084 **
   126085 ** A "position-list" is the list of positions for multiple columns for
   126086 ** a single docid.  A "column-list" is the set of positions for a single
   126087 ** column.  Hence, a position-list consists of one or more column-lists,
   126088 ** a document record consists of a docid followed by a position-list and
   126089 ** a doclist consists of one or more document records.
   126090 **
   126091 ** A bare doclist omits the position information, becoming an
   126092 ** array of varint-encoded docids.
   126093 **
   126094 **** Segment leaf nodes ****
   126095 ** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
   126096 ** nodes are written using LeafWriter, and read using LeafReader (to
   126097 ** iterate through a single leaf node's data) and LeavesReader (to
   126098 ** iterate through a segment's entire leaf layer).  Leaf nodes have
   126099 ** the format:
   126100 **
   126101 ** varint iHeight;             (height from leaf level, always 0)
   126102 ** varint nTerm;               (length of first term)
   126103 ** char pTerm[nTerm];          (content of first term)
   126104 ** varint nDoclist;            (length of term's associated doclist)
   126105 ** char pDoclist[nDoclist];    (content of doclist)
   126106 ** array {
   126107 **                             (further terms are delta-encoded)
   126108 **   varint nPrefix;           (length of prefix shared with previous term)
   126109 **   varint nSuffix;           (length of unshared suffix)
   126110 **   char pTermSuffix[nSuffix];(unshared suffix of next term)
   126111 **   varint nDoclist;          (length of term's associated doclist)
   126112 **   char pDoclist[nDoclist];  (content of doclist)
   126113 ** }
   126114 **
   126115 ** Here, array { X } means zero or more occurrences of X, adjacent in
   126116 ** memory.
   126117 **
   126118 ** Leaf nodes are broken into blocks which are stored contiguously in
   126119 ** the %_segments table in sorted order.  This means that when the end
   126120 ** of a node is reached, the next term is in the node with the next
   126121 ** greater node id.
   126122 **
   126123 ** New data is spilled to a new leaf node when the current node
   126124 ** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
   126125 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
   126126 ** node (a leaf node with a single term and doclist).  The goal of
   126127 ** these settings is to pack together groups of small doclists while
   126128 ** making it efficient to directly access large doclists.  The
   126129 ** assumption is that large doclists represent terms which are more
   126130 ** likely to be query targets.
   126131 **
   126132 ** TODO(shess) It may be useful for blocking decisions to be more
   126133 ** dynamic.  For instance, it may make more sense to have a 2.5k leaf
   126134 ** node rather than splitting into 2k and .5k nodes.  My intuition is
   126135 ** that this might extend through 2x or 4x the pagesize.
   126136 **
   126137 **
   126138 **** Segment interior nodes ****
   126139 ** Segment interior nodes store blockids for subtree nodes and terms
   126140 ** to describe what data is stored by the each subtree.  Interior
   126141 ** nodes are written using InteriorWriter, and read using
   126142 ** InteriorReader.  InteriorWriters are created as needed when
   126143 ** SegmentWriter creates new leaf nodes, or when an interior node
   126144 ** itself grows too big and must be split.  The format of interior
   126145 ** nodes:
   126146 **
   126147 ** varint iHeight;           (height from leaf level, always >0)
   126148 ** varint iBlockid;          (block id of node's leftmost subtree)
   126149 ** optional {
   126150 **   varint nTerm;           (length of first term)
   126151 **   char pTerm[nTerm];      (content of first term)
   126152 **   array {
   126153 **                                (further terms are delta-encoded)
   126154 **     varint nPrefix;            (length of shared prefix with previous term)
   126155 **     varint nSuffix;            (length of unshared suffix)
   126156 **     char pTermSuffix[nSuffix]; (unshared suffix of next term)
   126157 **   }
   126158 ** }
   126159 **
   126160 ** Here, optional { X } means an optional element, while array { X }
   126161 ** means zero or more occurrences of X, adjacent in memory.
   126162 **
   126163 ** An interior node encodes n terms separating n+1 subtrees.  The
   126164 ** subtree blocks are contiguous, so only the first subtree's blockid
   126165 ** is encoded.  The subtree at iBlockid will contain all terms less
   126166 ** than the first term encoded (or all terms if no term is encoded).
   126167 ** Otherwise, for terms greater than or equal to pTerm[i] but less
   126168 ** than pTerm[i+1], the subtree for that term will be rooted at
   126169 ** iBlockid+i.  Interior nodes only store enough term data to
   126170 ** distinguish adjacent children (if the rightmost term of the left
   126171 ** child is "something", and the leftmost term of the right child is
   126172 ** "wicked", only "w" is stored).
   126173 **
   126174 ** New data is spilled to a new interior node at the same height when
   126175 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
   126176 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
   126177 ** interior nodes and making the tree too skinny.  The interior nodes
   126178 ** at a given height are naturally tracked by interior nodes at
   126179 ** height+1, and so on.
   126180 **
   126181 **
   126182 **** Segment directory ****
   126183 ** The segment directory in table %_segdir stores meta-information for
   126184 ** merging and deleting segments, and also the root node of the
   126185 ** segment's tree.
   126186 **
   126187 ** The root node is the top node of the segment's tree after encoding
   126188 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
   126189 ** This could be either a leaf node or an interior node.  If the top
   126190 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
   126191 ** and a new root interior node is generated (which should always fit
   126192 ** within ROOT_MAX because it only needs space for 2 varints, the
   126193 ** height and the blockid of the previous root).
   126194 **
   126195 ** The meta-information in the segment directory is:
   126196 **   level               - segment level (see below)
   126197 **   idx                 - index within level
   126198 **                       - (level,idx uniquely identify a segment)
   126199 **   start_block         - first leaf node
   126200 **   leaves_end_block    - last leaf node
   126201 **   end_block           - last block (including interior nodes)
   126202 **   root                - contents of root node
   126203 **
   126204 ** If the root node is a leaf node, then start_block,
   126205 ** leaves_end_block, and end_block are all 0.
   126206 **
   126207 **
   126208 **** Segment merging ****
   126209 ** To amortize update costs, segments are grouped into levels and
   126210 ** merged in batches.  Each increase in level represents exponentially
   126211 ** more documents.
   126212 **
   126213 ** New documents (actually, document updates) are tokenized and
   126214 ** written individually (using LeafWriter) to a level 0 segment, with
   126215 ** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
   126216 ** level 0 segments are merged into a single level 1 segment.  Level 1
   126217 ** is populated like level 0, and eventually MERGE_COUNT level 1
   126218 ** segments are merged to a single level 2 segment (representing
   126219 ** MERGE_COUNT^2 updates), and so on.
   126220 **
   126221 ** A segment merge traverses all segments at a given level in
   126222 ** parallel, performing a straightforward sorted merge.  Since segment
   126223 ** leaf nodes are written in to the %_segments table in order, this
   126224 ** merge traverses the underlying sqlite disk structures efficiently.
   126225 ** After the merge, all segment blocks from the merged level are
   126226 ** deleted.
   126227 **
   126228 ** MERGE_COUNT controls how often we merge segments.  16 seems to be
   126229 ** somewhat of a sweet spot for insertion performance.  32 and 64 show
   126230 ** very similar performance numbers to 16 on insertion, though they're
   126231 ** a tiny bit slower (perhaps due to more overhead in merge-time
   126232 ** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
   126233 ** 16, 2 about 66% slower than 16.
   126234 **
   126235 ** At query time, high MERGE_COUNT increases the number of segments
   126236 ** which need to be scanned and merged.  For instance, with 100k docs
   126237 ** inserted:
   126238 **
   126239 **    MERGE_COUNT   segments
   126240 **       16           25
   126241 **        8           12
   126242 **        4           10
   126243 **        2            6
   126244 **
   126245 ** This appears to have only a moderate impact on queries for very
   126246 ** frequent terms (which are somewhat dominated by segment merge
   126247 ** costs), and infrequent and non-existent terms still seem to be fast
   126248 ** even with many segments.
   126249 **
   126250 ** TODO(shess) That said, it would be nice to have a better query-side
   126251 ** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
   126252 ** optimizations to things like doclist merging will swing the sweet
   126253 ** spot around.
   126254 **
   126255 **
   126256 **
   126257 **** Handling of deletions and updates ****
   126258 ** Since we're using a segmented structure, with no docid-oriented
   126259 ** index into the term index, we clearly cannot simply update the term
   126260 ** index when a document is deleted or updated.  For deletions, we
   126261 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
   126262 ** we simply write the new doclist.  Segment merges overwrite older
   126263 ** data for a particular docid with newer data, so deletes or updates
   126264 ** will eventually overtake the earlier data and knock it out.  The
   126265 ** query logic likewise merges doclists so that newer data knocks out
   126266 ** older data.
   126267 */
   126268 
   126269 /************** Include fts3Int.h in the middle of fts3.c ********************/
   126270 /************** Begin file fts3Int.h *****************************************/
   126271 /*
   126272 ** 2009 Nov 12
   126273 **
   126274 ** The author disclaims copyright to this source code.  In place of
   126275 ** a legal notice, here is a blessing:
   126276 **
   126277 **    May you do good and not evil.
   126278 **    May you find forgiveness for yourself and forgive others.
   126279 **    May you share freely, never taking more than you give.
   126280 **
   126281 ******************************************************************************
   126282 **
   126283 */
   126284 #ifndef _FTSINT_H
   126285 #define _FTSINT_H
   126286 
   126287 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
   126288 # define NDEBUG 1
   126289 #endif
   126290 
   126291 /*
   126292 ** FTS4 is really an extension for FTS3.  It is enabled using the
   126293 ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
   126294 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
   126295 */
   126296 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
   126297 # define SQLITE_ENABLE_FTS3
   126298 #endif
   126299 
   126300 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   126301 
   126302 /* If not building as part of the core, include sqlite3ext.h. */
   126303 #ifndef SQLITE_CORE
   126304 SQLITE_EXTENSION_INIT3
   126305 #endif
   126306 
   126307 /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
   126308 /************** Begin file fts3_tokenizer.h **********************************/
   126309 /*
   126310 ** 2006 July 10
   126311 **
   126312 ** The author disclaims copyright to this source code.
   126313 **
   126314 *************************************************************************
   126315 ** Defines the interface to tokenizers used by fulltext-search.  There
   126316 ** are three basic components:
   126317 **
   126318 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
   126319 ** interface functions.  This is essentially the class structure for
   126320 ** tokenizers.
   126321 **
   126322 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
   126323 ** including customization information defined at creation time.
   126324 **
   126325 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
   126326 ** tokens from a particular input.
   126327 */
   126328 #ifndef _FTS3_TOKENIZER_H_
   126329 #define _FTS3_TOKENIZER_H_
   126330 
   126331 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
   126332 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
   126333 ** we will need a way to register the API consistently.
   126334 */
   126335 
   126336 /*
   126337 ** Structures used by the tokenizer interface. When a new tokenizer
   126338 ** implementation is registered, the caller provides a pointer to
   126339 ** an sqlite3_tokenizer_module containing pointers to the callback
   126340 ** functions that make up an implementation.
   126341 **
   126342 ** When an fts3 table is created, it passes any arguments passed to
   126343 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
   126344 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
   126345 ** implementation. The xCreate() function in turn returns an
   126346 ** sqlite3_tokenizer structure representing the specific tokenizer to
   126347 ** be used for the fts3 table (customized by the tokenizer clause arguments).
   126348 **
   126349 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
   126350 ** method is called. It returns an sqlite3_tokenizer_cursor object
   126351 ** that may be used to tokenize a specific input buffer based on
   126352 ** the tokenization rules supplied by a specific sqlite3_tokenizer
   126353 ** object.
   126354 */
   126355 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
   126356 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
   126357 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
   126358 
   126359 struct sqlite3_tokenizer_module {
   126360 
   126361   /*
   126362   ** Structure version. Should always be set to 0 or 1.
   126363   */
   126364   int iVersion;
   126365 
   126366   /*
   126367   ** Create a new tokenizer. The values in the argv[] array are the
   126368   ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
   126369   ** TABLE statement that created the fts3 table. For example, if
   126370   ** the following SQL is executed:
   126371   **
   126372   **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
   126373   **
   126374   ** then argc is set to 2, and the argv[] array contains pointers
   126375   ** to the strings "arg1" and "arg2".
   126376   **
   126377   ** This method should return either SQLITE_OK (0), or an SQLite error
   126378   ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
   126379   ** to point at the newly created tokenizer structure. The generic
   126380   ** sqlite3_tokenizer.pModule variable should not be initialized by
   126381   ** this callback. The caller will do so.
   126382   */
   126383   int (*xCreate)(
   126384     int argc,                           /* Size of argv array */
   126385     const char *const*argv,             /* Tokenizer argument strings */
   126386     sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
   126387   );
   126388 
   126389   /*
   126390   ** Destroy an existing tokenizer. The fts3 module calls this method
   126391   ** exactly once for each successful call to xCreate().
   126392   */
   126393   int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
   126394 
   126395   /*
   126396   ** Create a tokenizer cursor to tokenize an input buffer. The caller
   126397   ** is responsible for ensuring that the input buffer remains valid
   126398   ** until the cursor is closed (using the xClose() method).
   126399   */
   126400   int (*xOpen)(
   126401     sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
   126402     const char *pInput, int nBytes,      /* Input buffer */
   126403     sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
   126404   );
   126405 
   126406   /*
   126407   ** Destroy an existing tokenizer cursor. The fts3 module calls this
   126408   ** method exactly once for each successful call to xOpen().
   126409   */
   126410   int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
   126411 
   126412   /*
   126413   ** Retrieve the next token from the tokenizer cursor pCursor. This
   126414   ** method should either return SQLITE_OK and set the values of the
   126415   ** "OUT" variables identified below, or SQLITE_DONE to indicate that
   126416   ** the end of the buffer has been reached, or an SQLite error code.
   126417   **
   126418   ** *ppToken should be set to point at a buffer containing the
   126419   ** normalized version of the token (i.e. after any case-folding and/or
   126420   ** stemming has been performed). *pnBytes should be set to the length
   126421   ** of this buffer in bytes. The input text that generated the token is
   126422   ** identified by the byte offsets returned in *piStartOffset and
   126423   ** *piEndOffset. *piStartOffset should be set to the index of the first
   126424   ** byte of the token in the input buffer. *piEndOffset should be set
   126425   ** to the index of the first byte just past the end of the token in
   126426   ** the input buffer.
   126427   **
   126428   ** The buffer *ppToken is set to point at is managed by the tokenizer
   126429   ** implementation. It is only required to be valid until the next call
   126430   ** to xNext() or xClose().
   126431   */
   126432   /* TODO(shess) current implementation requires pInput to be
   126433   ** nul-terminated.  This should either be fixed, or pInput/nBytes
   126434   ** should be converted to zInput.
   126435   */
   126436   int (*xNext)(
   126437     sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
   126438     const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
   126439     int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
   126440     int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
   126441     int *piPosition      /* OUT: Number of tokens returned before this one */
   126442   );
   126443 
   126444   /***********************************************************************
   126445   ** Methods below this point are only available if iVersion>=1.
   126446   */
   126447 
   126448   /*
   126449   ** Configure the language id of a tokenizer cursor.
   126450   */
   126451   int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
   126452 };
   126453 
   126454 struct sqlite3_tokenizer {
   126455   const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
   126456   /* Tokenizer implementations will typically add additional fields */
   126457 };
   126458 
   126459 struct sqlite3_tokenizer_cursor {
   126460   sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
   126461   /* Tokenizer implementations will typically add additional fields */
   126462 };
   126463 
   126464 int fts3_global_term_cnt(int iTerm, int iCol);
   126465 int fts3_term_cnt(int iTerm, int iCol);
   126466 
   126467 
   126468 #endif /* _FTS3_TOKENIZER_H_ */
   126469 
   126470 /************** End of fts3_tokenizer.h **************************************/
   126471 /************** Continuing where we left off in fts3Int.h ********************/
   126472 /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
   126473 /************** Begin file fts3_hash.h ***************************************/
   126474 /*
   126475 ** 2001 September 22
   126476 **
   126477 ** The author disclaims copyright to this source code.  In place of
   126478 ** a legal notice, here is a blessing:
   126479 **
   126480 **    May you do good and not evil.
   126481 **    May you find forgiveness for yourself and forgive others.
   126482 **    May you share freely, never taking more than you give.
   126483 **
   126484 *************************************************************************
   126485 ** This is the header file for the generic hash-table implementation
   126486 ** used in SQLite.  We've modified it slightly to serve as a standalone
   126487 ** hash table implementation for the full-text indexing module.
   126488 **
   126489 */
   126490 #ifndef _FTS3_HASH_H_
   126491 #define _FTS3_HASH_H_
   126492 
   126493 /* Forward declarations of structures. */
   126494 typedef struct Fts3Hash Fts3Hash;
   126495 typedef struct Fts3HashElem Fts3HashElem;
   126496 
   126497 /* A complete hash table is an instance of the following structure.
   126498 ** The internals of this structure are intended to be opaque -- client
   126499 ** code should not attempt to access or modify the fields of this structure
   126500 ** directly.  Change this structure only by using the routines below.
   126501 ** However, many of the "procedures" and "functions" for modifying and
   126502 ** accessing this structure are really macros, so we can't really make
   126503 ** this structure opaque.
   126504 */
   126505 struct Fts3Hash {
   126506   char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
   126507   char copyKey;           /* True if copy of key made on insert */
   126508   int count;              /* Number of entries in this table */
   126509   Fts3HashElem *first;    /* The first element of the array */
   126510   int htsize;             /* Number of buckets in the hash table */
   126511   struct _fts3ht {        /* the hash table */
   126512     int count;               /* Number of entries with this hash */
   126513     Fts3HashElem *chain;     /* Pointer to first entry with this hash */
   126514   } *ht;
   126515 };
   126516 
   126517 /* Each element in the hash table is an instance of the following
   126518 ** structure.  All elements are stored on a single doubly-linked list.
   126519 **
   126520 ** Again, this structure is intended to be opaque, but it can't really
   126521 ** be opaque because it is used by macros.
   126522 */
   126523 struct Fts3HashElem {
   126524   Fts3HashElem *next, *prev; /* Next and previous elements in the table */
   126525   void *data;                /* Data associated with this element */
   126526   void *pKey; int nKey;      /* Key associated with this element */
   126527 };
   126528 
   126529 /*
   126530 ** There are 2 different modes of operation for a hash table:
   126531 **
   126532 **   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
   126533 **                           (including the null-terminator, if any).  Case
   126534 **                           is respected in comparisons.
   126535 **
   126536 **   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long.
   126537 **                           memcmp() is used to compare keys.
   126538 **
   126539 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
   126540 */
   126541 #define FTS3_HASH_STRING    1
   126542 #define FTS3_HASH_BINARY    2
   126543 
   126544 /*
   126545 ** Access routines.  To delete, insert a NULL pointer.
   126546 */
   126547 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
   126548 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
   126549 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
   126550 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
   126551 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
   126552 
   126553 /*
   126554 ** Shorthand for the functions above
   126555 */
   126556 #define fts3HashInit     sqlite3Fts3HashInit
   126557 #define fts3HashInsert   sqlite3Fts3HashInsert
   126558 #define fts3HashFind     sqlite3Fts3HashFind
   126559 #define fts3HashClear    sqlite3Fts3HashClear
   126560 #define fts3HashFindElem sqlite3Fts3HashFindElem
   126561 
   126562 /*
   126563 ** Macros for looping over all elements of a hash table.  The idiom is
   126564 ** like this:
   126565 **
   126566 **   Fts3Hash h;
   126567 **   Fts3HashElem *p;
   126568 **   ...
   126569 **   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
   126570 **     SomeStructure *pData = fts3HashData(p);
   126571 **     // do something with pData
   126572 **   }
   126573 */
   126574 #define fts3HashFirst(H)  ((H)->first)
   126575 #define fts3HashNext(E)   ((E)->next)
   126576 #define fts3HashData(E)   ((E)->data)
   126577 #define fts3HashKey(E)    ((E)->pKey)
   126578 #define fts3HashKeysize(E) ((E)->nKey)
   126579 
   126580 /*
   126581 ** Number of entries in a hash table
   126582 */
   126583 #define fts3HashCount(H)  ((H)->count)
   126584 
   126585 #endif /* _FTS3_HASH_H_ */
   126586 
   126587 /************** End of fts3_hash.h *******************************************/
   126588 /************** Continuing where we left off in fts3Int.h ********************/
   126589 
   126590 /*
   126591 ** This constant determines the maximum depth of an FTS expression tree
   126592 ** that the library will create and use. FTS uses recursion to perform
   126593 ** various operations on the query tree, so the disadvantage of a large
   126594 ** limit is that it may allow very large queries to use large amounts
   126595 ** of stack space (perhaps causing a stack overflow).
   126596 */
   126597 #ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
   126598 # define SQLITE_FTS3_MAX_EXPR_DEPTH 12
   126599 #endif
   126600 
   126601 
   126602 /*
   126603 ** This constant controls how often segments are merged. Once there are
   126604 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
   126605 ** segment of level N+1.
   126606 */
   126607 #define FTS3_MERGE_COUNT 16
   126608 
   126609 /*
   126610 ** This is the maximum amount of data (in bytes) to store in the
   126611 ** Fts3Table.pendingTerms hash table. Normally, the hash table is
   126612 ** populated as documents are inserted/updated/deleted in a transaction
   126613 ** and used to create a new segment when the transaction is committed.
   126614 ** However if this limit is reached midway through a transaction, a new
   126615 ** segment is created and the hash table cleared immediately.
   126616 */
   126617 #define FTS3_MAX_PENDING_DATA (1*1024*1024)
   126618 
   126619 /*
   126620 ** Macro to return the number of elements in an array. SQLite has a
   126621 ** similar macro called ArraySize(). Use a different name to avoid
   126622 ** a collision when building an amalgamation with built-in FTS3.
   126623 */
   126624 #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
   126625 
   126626 
   126627 #ifndef MIN
   126628 # define MIN(x,y) ((x)<(y)?(x):(y))
   126629 #endif
   126630 #ifndef MAX
   126631 # define MAX(x,y) ((x)>(y)?(x):(y))
   126632 #endif
   126633 
   126634 /*
   126635 ** Maximum length of a varint encoded integer. The varint format is different
   126636 ** from that used by SQLite, so the maximum length is 10, not 9.
   126637 */
   126638 #define FTS3_VARINT_MAX 10
   126639 
   126640 /*
   126641 ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
   126642 ** in the document set and zero or more prefix indexes. All indexes are stored
   126643 ** as one or more b+-trees in the %_segments and %_segdir tables.
   126644 **
   126645 ** It is possible to determine which index a b+-tree belongs to based on the
   126646 ** value stored in the "%_segdir.level" column. Given this value L, the index
   126647 ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
   126648 ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
   126649 ** between 1024 and 2047 to index 1, and so on.
   126650 **
   126651 ** It is considered impossible for an index to use more than 1024 levels. In
   126652 ** theory though this may happen, but only after at least
   126653 ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
   126654 */
   126655 #define FTS3_SEGDIR_MAXLEVEL      1024
   126656 #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
   126657 
   126658 /*
   126659 ** The testcase() macro is only used by the amalgamation.  If undefined,
   126660 ** make it a no-op.
   126661 */
   126662 #ifndef testcase
   126663 # define testcase(X)
   126664 #endif
   126665 
   126666 /*
   126667 ** Terminator values for position-lists and column-lists.
   126668 */
   126669 #define POS_COLUMN  (1)     /* Column-list terminator */
   126670 #define POS_END     (0)     /* Position-list terminator */
   126671 
   126672 /*
   126673 ** This section provides definitions to allow the
   126674 ** FTS3 extension to be compiled outside of the
   126675 ** amalgamation.
   126676 */
   126677 #ifndef SQLITE_AMALGAMATION
   126678 /*
   126679 ** Macros indicating that conditional expressions are always true or
   126680 ** false.
   126681 */
   126682 #ifdef SQLITE_COVERAGE_TEST
   126683 # define ALWAYS(x) (1)
   126684 # define NEVER(X)  (0)
   126685 #else
   126686 # define ALWAYS(x) (x)
   126687 # define NEVER(x)  (x)
   126688 #endif
   126689 
   126690 /*
   126691 ** Internal types used by SQLite.
   126692 */
   126693 typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
   126694 typedef short int i16;            /* 2-byte (or larger) signed integer */
   126695 typedef unsigned int u32;         /* 4-byte unsigned integer */
   126696 typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
   126697 typedef sqlite3_int64 i64;        /* 8-byte signed integer */
   126698 
   126699 /*
   126700 ** Macro used to suppress compiler warnings for unused parameters.
   126701 */
   126702 #define UNUSED_PARAMETER(x) (void)(x)
   126703 
   126704 /*
   126705 ** Activate assert() only if SQLITE_TEST is enabled.
   126706 */
   126707 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
   126708 # define NDEBUG 1
   126709 #endif
   126710 
   126711 /*
   126712 ** The TESTONLY macro is used to enclose variable declarations or
   126713 ** other bits of code that are needed to support the arguments
   126714 ** within testcase() and assert() macros.
   126715 */
   126716 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
   126717 # define TESTONLY(X)  X
   126718 #else
   126719 # define TESTONLY(X)
   126720 #endif
   126721 
   126722 #endif /* SQLITE_AMALGAMATION */
   126723 
   126724 #ifdef SQLITE_DEBUG
   126725 SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
   126726 # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
   126727 #else
   126728 # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
   126729 #endif
   126730 
   126731 typedef struct Fts3Table Fts3Table;
   126732 typedef struct Fts3Cursor Fts3Cursor;
   126733 typedef struct Fts3Expr Fts3Expr;
   126734 typedef struct Fts3Phrase Fts3Phrase;
   126735 typedef struct Fts3PhraseToken Fts3PhraseToken;
   126736 
   126737 typedef struct Fts3Doclist Fts3Doclist;
   126738 typedef struct Fts3SegFilter Fts3SegFilter;
   126739 typedef struct Fts3DeferredToken Fts3DeferredToken;
   126740 typedef struct Fts3SegReader Fts3SegReader;
   126741 typedef struct Fts3MultiSegReader Fts3MultiSegReader;
   126742 
   126743 /*
   126744 ** A connection to a fulltext index is an instance of the following
   126745 ** structure. The xCreate and xConnect methods create an instance
   126746 ** of this structure and xDestroy and xDisconnect free that instance.
   126747 ** All other methods receive a pointer to the structure as one of their
   126748 ** arguments.
   126749 */
   126750 struct Fts3Table {
   126751   sqlite3_vtab base;              /* Base class used by SQLite core */
   126752   sqlite3 *db;                    /* The database connection */
   126753   const char *zDb;                /* logical database name */
   126754   const char *zName;              /* virtual table name */
   126755   int nColumn;                    /* number of named columns in virtual table */
   126756   char **azColumn;                /* column names.  malloced */
   126757   u8 *abNotindexed;               /* True for 'notindexed' columns */
   126758   sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
   126759   char *zContentTbl;              /* content=xxx option, or NULL */
   126760   char *zLanguageid;              /* languageid=xxx option, or NULL */
   126761   int nAutoincrmerge;             /* Value configured by 'automerge' */
   126762   u32 nLeafAdd;                   /* Number of leaf blocks added this trans */
   126763 
   126764   /* Precompiled statements used by the implementation. Each of these
   126765   ** statements is run and reset within a single virtual table API call.
   126766   */
   126767   sqlite3_stmt *aStmt[40];
   126768 
   126769   char *zReadExprlist;
   126770   char *zWriteExprlist;
   126771 
   126772   int nNodeSize;                  /* Soft limit for node size */
   126773   u8 bFts4;                       /* True for FTS4, false for FTS3 */
   126774   u8 bHasStat;                    /* True if %_stat table exists (2==unknown) */
   126775   u8 bHasDocsize;                 /* True if %_docsize table exists */
   126776   u8 bDescIdx;                    /* True if doclists are in reverse order */
   126777   u8 bIgnoreSavepoint;            /* True to ignore xSavepoint invocations */
   126778   int nPgsz;                      /* Page size for host database */
   126779   char *zSegmentsTbl;             /* Name of %_segments table */
   126780   sqlite3_blob *pSegments;        /* Blob handle open on %_segments table */
   126781 
   126782   /*
   126783   ** The following array of hash tables is used to buffer pending index
   126784   ** updates during transactions. All pending updates buffered at any one
   126785   ** time must share a common language-id (see the FTS4 langid= feature).
   126786   ** The current language id is stored in variable iPrevLangid.
   126787   **
   126788   ** A single FTS4 table may have multiple full-text indexes. For each index
   126789   ** there is an entry in the aIndex[] array. Index 0 is an index of all the
   126790   ** terms that appear in the document set. Each subsequent index in aIndex[]
   126791   ** is an index of prefixes of a specific length.
   126792   **
   126793   ** Variable nPendingData contains an estimate the memory consumed by the
   126794   ** pending data structures, including hash table overhead, but not including
   126795   ** malloc overhead.  When nPendingData exceeds nMaxPendingData, all hash
   126796   ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
   126797   ** recently inserted record.
   126798   */
   126799   int nIndex;                     /* Size of aIndex[] */
   126800   struct Fts3Index {
   126801     int nPrefix;                  /* Prefix length (0 for main terms index) */
   126802     Fts3Hash hPending;            /* Pending terms table for this index */
   126803   } *aIndex;
   126804   int nMaxPendingData;            /* Max pending data before flush to disk */
   126805   int nPendingData;               /* Current bytes of pending data */
   126806   sqlite_int64 iPrevDocid;        /* Docid of most recently inserted document */
   126807   int iPrevLangid;                /* Langid of recently inserted document */
   126808 
   126809 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
   126810   /* State variables used for validating that the transaction control
   126811   ** methods of the virtual table are called at appropriate times.  These
   126812   ** values do not contribute to FTS functionality; they are used for
   126813   ** verifying the operation of the SQLite core.
   126814   */
   126815   int inTransaction;     /* True after xBegin but before xCommit/xRollback */
   126816   int mxSavepoint;       /* Largest valid xSavepoint integer */
   126817 #endif
   126818 
   126819 #ifdef SQLITE_TEST
   126820   /* True to disable the incremental doclist optimization. This is controled
   126821   ** by special insert command 'test-no-incr-doclist'.  */
   126822   int bNoIncrDoclist;
   126823 #endif
   126824 };
   126825 
   126826 /*
   126827 ** When the core wants to read from the virtual table, it creates a
   126828 ** virtual table cursor (an instance of the following structure) using
   126829 ** the xOpen method. Cursors are destroyed using the xClose method.
   126830 */
   126831 struct Fts3Cursor {
   126832   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
   126833   i16 eSearch;                    /* Search strategy (see below) */
   126834   u8 isEof;                       /* True if at End Of Results */
   126835   u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
   126836   sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
   126837   Fts3Expr *pExpr;                /* Parsed MATCH query string */
   126838   int iLangid;                    /* Language being queried for */
   126839   int nPhrase;                    /* Number of matchable phrases in query */
   126840   Fts3DeferredToken *pDeferred;   /* Deferred search tokens, if any */
   126841   sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
   126842   char *pNextId;                  /* Pointer into the body of aDoclist */
   126843   char *aDoclist;                 /* List of docids for full-text queries */
   126844   int nDoclist;                   /* Size of buffer at aDoclist */
   126845   u8 bDesc;                       /* True to sort in descending order */
   126846   int eEvalmode;                  /* An FTS3_EVAL_XX constant */
   126847   int nRowAvg;                    /* Average size of database rows, in pages */
   126848   sqlite3_int64 nDoc;             /* Documents in table */
   126849   i64 iMinDocid;                  /* Minimum docid to return */
   126850   i64 iMaxDocid;                  /* Maximum docid to return */
   126851   int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
   126852   u32 *aMatchinfo;                /* Information about most recent match */
   126853   int nMatchinfo;                 /* Number of elements in aMatchinfo[] */
   126854   char *zMatchinfo;               /* Matchinfo specification */
   126855 };
   126856 
   126857 #define FTS3_EVAL_FILTER    0
   126858 #define FTS3_EVAL_NEXT      1
   126859 #define FTS3_EVAL_MATCHINFO 2
   126860 
   126861 /*
   126862 ** The Fts3Cursor.eSearch member is always set to one of the following.
   126863 ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
   126864 ** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
   126865 ** of the column to be searched.  For example, in
   126866 **
   126867 **     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
   126868 **     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
   126869 **
   126870 ** Because the LHS of the MATCH operator is 2nd column "b",
   126871 ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
   126872 ** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1"
   126873 ** indicating that all columns should be searched,
   126874 ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
   126875 */
   126876 #define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
   126877 #define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
   126878 #define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
   126879 
   126880 /*
   126881 ** The lower 16-bits of the sqlite3_index_info.idxNum value set by
   126882 ** the xBestIndex() method contains the Fts3Cursor.eSearch value described
   126883 ** above. The upper 16-bits contain a combination of the following
   126884 ** bits, used to describe extra constraints on full-text searches.
   126885 */
   126886 #define FTS3_HAVE_LANGID    0x00010000      /* languageid=? */
   126887 #define FTS3_HAVE_DOCID_GE  0x00020000      /* docid>=? */
   126888 #define FTS3_HAVE_DOCID_LE  0x00040000      /* docid<=? */
   126889 
   126890 struct Fts3Doclist {
   126891   char *aAll;                    /* Array containing doclist (or NULL) */
   126892   int nAll;                      /* Size of a[] in bytes */
   126893   char *pNextDocid;              /* Pointer to next docid */
   126894 
   126895   sqlite3_int64 iDocid;          /* Current docid (if pList!=0) */
   126896   int bFreeList;                 /* True if pList should be sqlite3_free()d */
   126897   char *pList;                   /* Pointer to position list following iDocid */
   126898   int nList;                     /* Length of position list */
   126899 };
   126900 
   126901 /*
   126902 ** A "phrase" is a sequence of one or more tokens that must match in
   126903 ** sequence.  A single token is the base case and the most common case.
   126904 ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
   126905 ** nToken will be the number of tokens in the string.
   126906 */
   126907 struct Fts3PhraseToken {
   126908   char *z;                        /* Text of the token */
   126909   int n;                          /* Number of bytes in buffer z */
   126910   int isPrefix;                   /* True if token ends with a "*" character */
   126911   int bFirst;                     /* True if token must appear at position 0 */
   126912 
   126913   /* Variables above this point are populated when the expression is
   126914   ** parsed (by code in fts3_expr.c). Below this point the variables are
   126915   ** used when evaluating the expression. */
   126916   Fts3DeferredToken *pDeferred;   /* Deferred token object for this token */
   126917   Fts3MultiSegReader *pSegcsr;    /* Segment-reader for this token */
   126918 };
   126919 
   126920 struct Fts3Phrase {
   126921   /* Cache of doclist for this phrase. */
   126922   Fts3Doclist doclist;
   126923   int bIncr;                 /* True if doclist is loaded incrementally */
   126924   int iDoclistToken;
   126925 
   126926   /* Variables below this point are populated by fts3_expr.c when parsing
   126927   ** a MATCH expression. Everything above is part of the evaluation phase.
   126928   */
   126929   int nToken;                /* Number of tokens in the phrase */
   126930   int iColumn;               /* Index of column this phrase must match */
   126931   Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
   126932 };
   126933 
   126934 /*
   126935 ** A tree of these objects forms the RHS of a MATCH operator.
   126936 **
   126937 ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
   126938 ** points to a malloced buffer, size nDoclist bytes, containing the results
   126939 ** of this phrase query in FTS3 doclist format. As usual, the initial
   126940 ** "Length" field found in doclists stored on disk is omitted from this
   126941 ** buffer.
   126942 **
   126943 ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
   126944 ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
   126945 ** where nCol is the number of columns in the queried FTS table. The array
   126946 ** is populated as follows:
   126947 **
   126948 **   aMI[iCol*3 + 0] = Undefined
   126949 **   aMI[iCol*3 + 1] = Number of occurrences
   126950 **   aMI[iCol*3 + 2] = Number of rows containing at least one instance
   126951 **
   126952 ** The aMI array is allocated using sqlite3_malloc(). It should be freed
   126953 ** when the expression node is.
   126954 */
   126955 struct Fts3Expr {
   126956   int eType;                 /* One of the FTSQUERY_XXX values defined below */
   126957   int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
   126958   Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
   126959   Fts3Expr *pLeft;           /* Left operand */
   126960   Fts3Expr *pRight;          /* Right operand */
   126961   Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
   126962 
   126963   /* The following are used by the fts3_eval.c module. */
   126964   sqlite3_int64 iDocid;      /* Current docid */
   126965   u8 bEof;                   /* True this expression is at EOF already */
   126966   u8 bStart;                 /* True if iDocid is valid */
   126967   u8 bDeferred;              /* True if this expression is entirely deferred */
   126968 
   126969   u32 *aMI;
   126970 };
   126971 
   126972 /*
   126973 ** Candidate values for Fts3Query.eType. Note that the order of the first
   126974 ** four values is in order of precedence when parsing expressions. For
   126975 ** example, the following:
   126976 **
   126977 **   "a OR b AND c NOT d NEAR e"
   126978 **
   126979 ** is equivalent to:
   126980 **
   126981 **   "a OR (b AND (c NOT (d NEAR e)))"
   126982 */
   126983 #define FTSQUERY_NEAR   1
   126984 #define FTSQUERY_NOT    2
   126985 #define FTSQUERY_AND    3
   126986 #define FTSQUERY_OR     4
   126987 #define FTSQUERY_PHRASE 5
   126988 
   126989 
   126990 /* fts3_write.c */
   126991 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
   126992 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
   126993 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
   126994 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
   126995 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
   126996   sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
   126997 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
   126998   Fts3Table*,int,const char*,int,int,Fts3SegReader**);
   126999 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
   127000 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
   127001 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
   127002 
   127003 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
   127004 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
   127005 
   127006 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
   127007 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
   127008 SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
   127009 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
   127010 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
   127011 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
   127012 #else
   127013 # define sqlite3Fts3FreeDeferredTokens(x)
   127014 # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
   127015 # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
   127016 # define sqlite3Fts3FreeDeferredDoclists(x)
   127017 # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
   127018 #endif
   127019 
   127020 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
   127021 SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
   127022 
   127023 /* Special values interpreted by sqlite3SegReaderCursor() */
   127024 #define FTS3_SEGCURSOR_PENDING        -1
   127025 #define FTS3_SEGCURSOR_ALL            -2
   127026 
   127027 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
   127028 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
   127029 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
   127030 
   127031 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
   127032     int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
   127033 
   127034 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
   127035 #define FTS3_SEGMENT_REQUIRE_POS   0x00000001
   127036 #define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
   127037 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
   127038 #define FTS3_SEGMENT_PREFIX        0x00000008
   127039 #define FTS3_SEGMENT_SCAN          0x00000010
   127040 #define FTS3_SEGMENT_FIRST         0x00000020
   127041 
   127042 /* Type passed as 4th argument to SegmentReaderIterate() */
   127043 struct Fts3SegFilter {
   127044   const char *zTerm;
   127045   int nTerm;
   127046   int iCol;
   127047   int flags;
   127048 };
   127049 
   127050 struct Fts3MultiSegReader {
   127051   /* Used internally by sqlite3Fts3SegReaderXXX() calls */
   127052   Fts3SegReader **apSegment;      /* Array of Fts3SegReader objects */
   127053   int nSegment;                   /* Size of apSegment array */
   127054   int nAdvance;                   /* How many seg-readers to advance */
   127055   Fts3SegFilter *pFilter;         /* Pointer to filter object */
   127056   char *aBuffer;                  /* Buffer to merge doclists in */
   127057   int nBuffer;                    /* Allocated size of aBuffer[] in bytes */
   127058 
   127059   int iColFilter;                 /* If >=0, filter for this column */
   127060   int bRestart;
   127061 
   127062   /* Used by fts3.c only. */
   127063   int nCost;                      /* Cost of running iterator */
   127064   int bLookup;                    /* True if a lookup of a single entry. */
   127065 
   127066   /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
   127067   char *zTerm;                    /* Pointer to term buffer */
   127068   int nTerm;                      /* Size of zTerm in bytes */
   127069   char *aDoclist;                 /* Pointer to doclist buffer */
   127070   int nDoclist;                   /* Size of aDoclist[] in bytes */
   127071 };
   127072 
   127073 SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
   127074 
   127075 #define fts3GetVarint32(p, piVal) (                                           \
   127076   (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \
   127077 )
   127078 
   127079 /* fts3.c */
   127080 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
   127081 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
   127082 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
   127083 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
   127084 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
   127085 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
   127086 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
   127087 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
   127088 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
   127089 
   127090 /* fts3_tokenizer.c */
   127091 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
   127092 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
   127093 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
   127094     sqlite3_tokenizer **, char **
   127095 );
   127096 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
   127097 
   127098 /* fts3_snippet.c */
   127099 SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
   127100 SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
   127101   const char *, const char *, int, int
   127102 );
   127103 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
   127104 
   127105 /* fts3_expr.c */
   127106 SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
   127107   char **, int, int, int, const char *, int, Fts3Expr **, char **
   127108 );
   127109 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
   127110 #ifdef SQLITE_TEST
   127111 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
   127112 SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
   127113 #endif
   127114 
   127115 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
   127116   sqlite3_tokenizer_cursor **
   127117 );
   127118 
   127119 /* fts3_aux.c */
   127120 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
   127121 
   127122 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
   127123 
   127124 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
   127125     Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
   127126 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
   127127     Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
   127128 SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
   127129 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
   127130 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
   127131 
   127132 /* fts3_tokenize_vtab.c */
   127133 SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
   127134 
   127135 /* fts3_unicode2.c (functions generated by parsing unicode text files) */
   127136 #ifndef SQLITE_DISABLE_FTS3_UNICODE
   127137 SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
   127138 SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
   127139 SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
   127140 #endif
   127141 
   127142 #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
   127143 #endif /* _FTSINT_H */
   127144 
   127145 /************** End of fts3Int.h *********************************************/
   127146 /************** Continuing where we left off in fts3.c ***********************/
   127147 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   127148 
   127149 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
   127150 # define SQLITE_CORE 1
   127151 #endif
   127152 
   127153 /* #include <assert.h> */
   127154 /* #include <stdlib.h> */
   127155 /* #include <stddef.h> */
   127156 /* #include <stdio.h> */
   127157 /* #include <string.h> */
   127158 /* #include <stdarg.h> */
   127159 
   127160 #ifndef SQLITE_CORE
   127161   SQLITE_EXTENSION_INIT1
   127162 #endif
   127163 
   127164 static int fts3EvalNext(Fts3Cursor *pCsr);
   127165 static int fts3EvalStart(Fts3Cursor *pCsr);
   127166 static int fts3TermSegReaderCursor(
   127167     Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
   127168 
   127169 /*
   127170 ** Write a 64-bit variable-length integer to memory starting at p[0].
   127171 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
   127172 ** The number of bytes written is returned.
   127173 */
   127174 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
   127175   unsigned char *q = (unsigned char *) p;
   127176   sqlite_uint64 vu = v;
   127177   do{
   127178     *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
   127179     vu >>= 7;
   127180   }while( vu!=0 );
   127181   q[-1] &= 0x7f;  /* turn off high bit in final byte */
   127182   assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
   127183   return (int) (q - (unsigned char *)p);
   127184 }
   127185 
   127186 #define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
   127187   v = (v & mask1) | ( (*ptr++) << shift );                    \
   127188   if( (v & mask2)==0 ){ var = v; return ret; }
   127189 #define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
   127190   v = (*ptr++);                                               \
   127191   if( (v & mask2)==0 ){ var = v; return ret; }
   127192 
   127193 /*
   127194 ** Read a 64-bit variable-length integer from memory starting at p[0].
   127195 ** Return the number of bytes read, or 0 on error.
   127196 ** The value is stored in *v.
   127197 */
   127198 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
   127199   const char *pStart = p;
   127200   u32 a;
   127201   u64 b;
   127202   int shift;
   127203 
   127204   GETVARINT_INIT(a, p, 0,  0x00,     0x80, *v, 1);
   127205   GETVARINT_STEP(a, p, 7,  0x7F,     0x4000, *v, 2);
   127206   GETVARINT_STEP(a, p, 14, 0x3FFF,   0x200000, *v, 3);
   127207   GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);
   127208   b = (a & 0x0FFFFFFF );
   127209 
   127210   for(shift=28; shift<=63; shift+=7){
   127211     u64 c = *p++;
   127212     b += (c&0x7F) << shift;
   127213     if( (c & 0x80)==0 ) break;
   127214   }
   127215   *v = b;
   127216   return (int)(p - pStart);
   127217 }
   127218 
   127219 /*
   127220 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
   127221 ** 32-bit integer before it is returned.
   127222 */
   127223 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
   127224   u32 a;
   127225 
   127226 #ifndef fts3GetVarint32
   127227   GETVARINT_INIT(a, p, 0,  0x00,     0x80, *pi, 1);
   127228 #else
   127229   a = (*p++);
   127230   assert( a & 0x80 );
   127231 #endif
   127232 
   127233   GETVARINT_STEP(a, p, 7,  0x7F,     0x4000, *pi, 2);
   127234   GETVARINT_STEP(a, p, 14, 0x3FFF,   0x200000, *pi, 3);
   127235   GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *pi, 4);
   127236   a = (a & 0x0FFFFFFF );
   127237   *pi = (int)(a | ((u32)(*p & 0x0F) << 28));
   127238   return 5;
   127239 }
   127240 
   127241 /*
   127242 ** Return the number of bytes required to encode v as a varint
   127243 */
   127244 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
   127245   int i = 0;
   127246   do{
   127247     i++;
   127248     v >>= 7;
   127249   }while( v!=0 );
   127250   return i;
   127251 }
   127252 
   127253 /*
   127254 ** Convert an SQL-style quoted string into a normal string by removing
   127255 ** the quote characters.  The conversion is done in-place.  If the
   127256 ** input does not begin with a quote character, then this routine
   127257 ** is a no-op.
   127258 **
   127259 ** Examples:
   127260 **
   127261 **     "abc"   becomes   abc
   127262 **     'xyz'   becomes   xyz
   127263 **     [pqr]   becomes   pqr
   127264 **     `mno`   becomes   mno
   127265 **
   127266 */
   127267 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
   127268   char quote;                     /* Quote character (if any ) */
   127269 
   127270   quote = z[0];
   127271   if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
   127272     int iIn = 1;                  /* Index of next byte to read from input */
   127273     int iOut = 0;                 /* Index of next byte to write to output */
   127274 
   127275     /* If the first byte was a '[', then the close-quote character is a ']' */
   127276     if( quote=='[' ) quote = ']';
   127277 
   127278     while( ALWAYS(z[iIn]) ){
   127279       if( z[iIn]==quote ){
   127280         if( z[iIn+1]!=quote ) break;
   127281         z[iOut++] = quote;
   127282         iIn += 2;
   127283       }else{
   127284         z[iOut++] = z[iIn++];
   127285       }
   127286     }
   127287     z[iOut] = '\0';
   127288   }
   127289 }
   127290 
   127291 /*
   127292 ** Read a single varint from the doclist at *pp and advance *pp to point
   127293 ** to the first byte past the end of the varint.  Add the value of the varint
   127294 ** to *pVal.
   127295 */
   127296 static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
   127297   sqlite3_int64 iVal;
   127298   *pp += sqlite3Fts3GetVarint(*pp, &iVal);
   127299   *pVal += iVal;
   127300 }
   127301 
   127302 /*
   127303 ** When this function is called, *pp points to the first byte following a
   127304 ** varint that is part of a doclist (or position-list, or any other list
   127305 ** of varints). This function moves *pp to point to the start of that varint,
   127306 ** and sets *pVal by the varint value.
   127307 **
   127308 ** Argument pStart points to the first byte of the doclist that the
   127309 ** varint is part of.
   127310 */
   127311 static void fts3GetReverseVarint(
   127312   char **pp,
   127313   char *pStart,
   127314   sqlite3_int64 *pVal
   127315 ){
   127316   sqlite3_int64 iVal;
   127317   char *p;
   127318 
   127319   /* Pointer p now points at the first byte past the varint we are
   127320   ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
   127321   ** clear on character p[-1]. */
   127322   for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
   127323   p++;
   127324   *pp = p;
   127325 
   127326   sqlite3Fts3GetVarint(p, &iVal);
   127327   *pVal = iVal;
   127328 }
   127329 
   127330 /*
   127331 ** The xDisconnect() virtual table method.
   127332 */
   127333 static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
   127334   Fts3Table *p = (Fts3Table *)pVtab;
   127335   int i;
   127336 
   127337   assert( p->nPendingData==0 );
   127338   assert( p->pSegments==0 );
   127339 
   127340   /* Free any prepared statements held */
   127341   for(i=0; i<SizeofArray(p->aStmt); i++){
   127342     sqlite3_finalize(p->aStmt[i]);
   127343   }
   127344   sqlite3_free(p->zSegmentsTbl);
   127345   sqlite3_free(p->zReadExprlist);
   127346   sqlite3_free(p->zWriteExprlist);
   127347   sqlite3_free(p->zContentTbl);
   127348   sqlite3_free(p->zLanguageid);
   127349 
   127350   /* Invoke the tokenizer destructor to free the tokenizer. */
   127351   p->pTokenizer->pModule->xDestroy(p->pTokenizer);
   127352 
   127353   sqlite3_free(p);
   127354   return SQLITE_OK;
   127355 }
   127356 
   127357 /*
   127358 ** Construct one or more SQL statements from the format string given
   127359 ** and then evaluate those statements. The success code is written
   127360 ** into *pRc.
   127361 **
   127362 ** If *pRc is initially non-zero then this routine is a no-op.
   127363 */
   127364 static void fts3DbExec(
   127365   int *pRc,              /* Success code */
   127366   sqlite3 *db,           /* Database in which to run SQL */
   127367   const char *zFormat,   /* Format string for SQL */
   127368   ...                    /* Arguments to the format string */
   127369 ){
   127370   va_list ap;
   127371   char *zSql;
   127372   if( *pRc ) return;
   127373   va_start(ap, zFormat);
   127374   zSql = sqlite3_vmprintf(zFormat, ap);
   127375   va_end(ap);
   127376   if( zSql==0 ){
   127377     *pRc = SQLITE_NOMEM;
   127378   }else{
   127379     *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
   127380     sqlite3_free(zSql);
   127381   }
   127382 }
   127383 
   127384 /*
   127385 ** The xDestroy() virtual table method.
   127386 */
   127387 static int fts3DestroyMethod(sqlite3_vtab *pVtab){
   127388   Fts3Table *p = (Fts3Table *)pVtab;
   127389   int rc = SQLITE_OK;              /* Return code */
   127390   const char *zDb = p->zDb;        /* Name of database (e.g. "main", "temp") */
   127391   sqlite3 *db = p->db;             /* Database handle */
   127392 
   127393   /* Drop the shadow tables */
   127394   if( p->zContentTbl==0 ){
   127395     fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
   127396   }
   127397   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
   127398   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
   127399   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
   127400   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
   127401 
   127402   /* If everything has worked, invoke fts3DisconnectMethod() to free the
   127403   ** memory associated with the Fts3Table structure and return SQLITE_OK.
   127404   ** Otherwise, return an SQLite error code.
   127405   */
   127406   return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
   127407 }
   127408 
   127409 
   127410 /*
   127411 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
   127412 ** passed as the first argument. This is done as part of the xConnect()
   127413 ** and xCreate() methods.
   127414 **
   127415 ** If *pRc is non-zero when this function is called, it is a no-op.
   127416 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
   127417 ** before returning.
   127418 */
   127419 static void fts3DeclareVtab(int *pRc, Fts3Table *p){
   127420   if( *pRc==SQLITE_OK ){
   127421     int i;                        /* Iterator variable */
   127422     int rc;                       /* Return code */
   127423     char *zSql;                   /* SQL statement passed to declare_vtab() */
   127424     char *zCols;                  /* List of user defined columns */
   127425     const char *zLanguageid;
   127426 
   127427     zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
   127428     sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
   127429 
   127430     /* Create a list of user columns for the virtual table */
   127431     zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
   127432     for(i=1; zCols && i<p->nColumn; i++){
   127433       zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
   127434     }
   127435 
   127436     /* Create the whole "CREATE TABLE" statement to pass to SQLite */
   127437     zSql = sqlite3_mprintf(
   127438         "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
   127439         zCols, p->zName, zLanguageid
   127440     );
   127441     if( !zCols || !zSql ){
   127442       rc = SQLITE_NOMEM;
   127443     }else{
   127444       rc = sqlite3_declare_vtab(p->db, zSql);
   127445     }
   127446 
   127447     sqlite3_free(zSql);
   127448     sqlite3_free(zCols);
   127449     *pRc = rc;
   127450   }
   127451 }
   127452 
   127453 /*
   127454 ** Create the %_stat table if it does not already exist.
   127455 */
   127456 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
   127457   fts3DbExec(pRc, p->db,
   127458       "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
   127459           "(id INTEGER PRIMARY KEY, value BLOB);",
   127460       p->zDb, p->zName
   127461   );
   127462   if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
   127463 }
   127464 
   127465 /*
   127466 ** Create the backing store tables (%_content, %_segments and %_segdir)
   127467 ** required by the FTS3 table passed as the only argument. This is done
   127468 ** as part of the vtab xCreate() method.
   127469 **
   127470 ** If the p->bHasDocsize boolean is true (indicating that this is an
   127471 ** FTS4 table, not an FTS3 table) then also create the %_docsize and
   127472 ** %_stat tables required by FTS4.
   127473 */
   127474 static int fts3CreateTables(Fts3Table *p){
   127475   int rc = SQLITE_OK;             /* Return code */
   127476   int i;                          /* Iterator variable */
   127477   sqlite3 *db = p->db;            /* The database connection */
   127478 
   127479   if( p->zContentTbl==0 ){
   127480     const char *zLanguageid = p->zLanguageid;
   127481     char *zContentCols;           /* Columns of %_content table */
   127482 
   127483     /* Create a list of user columns for the content table */
   127484     zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
   127485     for(i=0; zContentCols && i<p->nColumn; i++){
   127486       char *z = p->azColumn[i];
   127487       zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
   127488     }
   127489     if( zLanguageid && zContentCols ){
   127490       zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
   127491     }
   127492     if( zContentCols==0 ) rc = SQLITE_NOMEM;
   127493 
   127494     /* Create the content table */
   127495     fts3DbExec(&rc, db,
   127496        "CREATE TABLE %Q.'%q_content'(%s)",
   127497        p->zDb, p->zName, zContentCols
   127498     );
   127499     sqlite3_free(zContentCols);
   127500   }
   127501 
   127502   /* Create other tables */
   127503   fts3DbExec(&rc, db,
   127504       "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
   127505       p->zDb, p->zName
   127506   );
   127507   fts3DbExec(&rc, db,
   127508       "CREATE TABLE %Q.'%q_segdir'("
   127509         "level INTEGER,"
   127510         "idx INTEGER,"
   127511         "start_block INTEGER,"
   127512         "leaves_end_block INTEGER,"
   127513         "end_block INTEGER,"
   127514         "root BLOB,"
   127515         "PRIMARY KEY(level, idx)"
   127516       ");",
   127517       p->zDb, p->zName
   127518   );
   127519   if( p->bHasDocsize ){
   127520     fts3DbExec(&rc, db,
   127521         "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
   127522         p->zDb, p->zName
   127523     );
   127524   }
   127525   assert( p->bHasStat==p->bFts4 );
   127526   if( p->bHasStat ){
   127527     sqlite3Fts3CreateStatTable(&rc, p);
   127528   }
   127529   return rc;
   127530 }
   127531 
   127532 /*
   127533 ** Store the current database page-size in bytes in p->nPgsz.
   127534 **
   127535 ** If *pRc is non-zero when this function is called, it is a no-op.
   127536 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
   127537 ** before returning.
   127538 */
   127539 static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
   127540   if( *pRc==SQLITE_OK ){
   127541     int rc;                       /* Return code */
   127542     char *zSql;                   /* SQL text "PRAGMA %Q.page_size" */
   127543     sqlite3_stmt *pStmt;          /* Compiled "PRAGMA %Q.page_size" statement */
   127544 
   127545     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
   127546     if( !zSql ){
   127547       rc = SQLITE_NOMEM;
   127548     }else{
   127549       rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
   127550       if( rc==SQLITE_OK ){
   127551         sqlite3_step(pStmt);
   127552         p->nPgsz = sqlite3_column_int(pStmt, 0);
   127553         rc = sqlite3_finalize(pStmt);
   127554       }else if( rc==SQLITE_AUTH ){
   127555         p->nPgsz = 1024;
   127556         rc = SQLITE_OK;
   127557       }
   127558     }
   127559     assert( p->nPgsz>0 || rc!=SQLITE_OK );
   127560     sqlite3_free(zSql);
   127561     *pRc = rc;
   127562   }
   127563 }
   127564 
   127565 /*
   127566 ** "Special" FTS4 arguments are column specifications of the following form:
   127567 **
   127568 **   <key> = <value>
   127569 **
   127570 ** There may not be whitespace surrounding the "=" character. The <value>
   127571 ** term may be quoted, but the <key> may not.
   127572 */
   127573 static int fts3IsSpecialColumn(
   127574   const char *z,
   127575   int *pnKey,
   127576   char **pzValue
   127577 ){
   127578   char *zValue;
   127579   const char *zCsr = z;
   127580 
   127581   while( *zCsr!='=' ){
   127582     if( *zCsr=='\0' ) return 0;
   127583     zCsr++;
   127584   }
   127585 
   127586   *pnKey = (int)(zCsr-z);
   127587   zValue = sqlite3_mprintf("%s", &zCsr[1]);
   127588   if( zValue ){
   127589     sqlite3Fts3Dequote(zValue);
   127590   }
   127591   *pzValue = zValue;
   127592   return 1;
   127593 }
   127594 
   127595 /*
   127596 ** Append the output of a printf() style formatting to an existing string.
   127597 */
   127598 static void fts3Appendf(
   127599   int *pRc,                       /* IN/OUT: Error code */
   127600   char **pz,                      /* IN/OUT: Pointer to string buffer */
   127601   const char *zFormat,            /* Printf format string to append */
   127602   ...                             /* Arguments for printf format string */
   127603 ){
   127604   if( *pRc==SQLITE_OK ){
   127605     va_list ap;
   127606     char *z;
   127607     va_start(ap, zFormat);
   127608     z = sqlite3_vmprintf(zFormat, ap);
   127609     va_end(ap);
   127610     if( z && *pz ){
   127611       char *z2 = sqlite3_mprintf("%s%s", *pz, z);
   127612       sqlite3_free(z);
   127613       z = z2;
   127614     }
   127615     if( z==0 ) *pRc = SQLITE_NOMEM;
   127616     sqlite3_free(*pz);
   127617     *pz = z;
   127618   }
   127619 }
   127620 
   127621 /*
   127622 ** Return a copy of input string zInput enclosed in double-quotes (") and
   127623 ** with all double quote characters escaped. For example:
   127624 **
   127625 **     fts3QuoteId("un \"zip\"")   ->    "un \"\"zip\"\""
   127626 **
   127627 ** The pointer returned points to memory obtained from sqlite3_malloc(). It
   127628 ** is the callers responsibility to call sqlite3_free() to release this
   127629 ** memory.
   127630 */
   127631 static char *fts3QuoteId(char const *zInput){
   127632   int nRet;
   127633   char *zRet;
   127634   nRet = 2 + (int)strlen(zInput)*2 + 1;
   127635   zRet = sqlite3_malloc(nRet);
   127636   if( zRet ){
   127637     int i;
   127638     char *z = zRet;
   127639     *(z++) = '"';
   127640     for(i=0; zInput[i]; i++){
   127641       if( zInput[i]=='"' ) *(z++) = '"';
   127642       *(z++) = zInput[i];
   127643     }
   127644     *(z++) = '"';
   127645     *(z++) = '\0';
   127646   }
   127647   return zRet;
   127648 }
   127649 
   127650 /*
   127651 ** Return a list of comma separated SQL expressions and a FROM clause that
   127652 ** could be used in a SELECT statement such as the following:
   127653 **
   127654 **     SELECT <list of expressions> FROM %_content AS x ...
   127655 **
   127656 ** to return the docid, followed by each column of text data in order
   127657 ** from left to write. If parameter zFunc is not NULL, then instead of
   127658 ** being returned directly each column of text data is passed to an SQL
   127659 ** function named zFunc first. For example, if zFunc is "unzip" and the
   127660 ** table has the three user-defined columns "a", "b", and "c", the following
   127661 ** string is returned:
   127662 **
   127663 **     "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
   127664 **
   127665 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
   127666 ** is the responsibility of the caller to eventually free it.
   127667 **
   127668 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
   127669 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
   127670 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
   127671 ** no error occurs, *pRc is left unmodified.
   127672 */
   127673 static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
   127674   char *zRet = 0;
   127675   char *zFree = 0;
   127676   char *zFunction;
   127677   int i;
   127678 
   127679   if( p->zContentTbl==0 ){
   127680     if( !zFunc ){
   127681       zFunction = "";
   127682     }else{
   127683       zFree = zFunction = fts3QuoteId(zFunc);
   127684     }
   127685     fts3Appendf(pRc, &zRet, "docid");
   127686     for(i=0; i<p->nColumn; i++){
   127687       fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
   127688     }
   127689     if( p->zLanguageid ){
   127690       fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
   127691     }
   127692     sqlite3_free(zFree);
   127693   }else{
   127694     fts3Appendf(pRc, &zRet, "rowid");
   127695     for(i=0; i<p->nColumn; i++){
   127696       fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
   127697     }
   127698     if( p->zLanguageid ){
   127699       fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
   127700     }
   127701   }
   127702   fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
   127703       p->zDb,
   127704       (p->zContentTbl ? p->zContentTbl : p->zName),
   127705       (p->zContentTbl ? "" : "_content")
   127706   );
   127707   return zRet;
   127708 }
   127709 
   127710 /*
   127711 ** Return a list of N comma separated question marks, where N is the number
   127712 ** of columns in the %_content table (one for the docid plus one for each
   127713 ** user-defined text column).
   127714 **
   127715 ** If argument zFunc is not NULL, then all but the first question mark
   127716 ** is preceded by zFunc and an open bracket, and followed by a closed
   127717 ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
   127718 ** user-defined text columns, the following string is returned:
   127719 **
   127720 **     "?, zip(?), zip(?), zip(?)"
   127721 **
   127722 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
   127723 ** is the responsibility of the caller to eventually free it.
   127724 **
   127725 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
   127726 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
   127727 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
   127728 ** no error occurs, *pRc is left unmodified.
   127729 */
   127730 static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
   127731   char *zRet = 0;
   127732   char *zFree = 0;
   127733   char *zFunction;
   127734   int i;
   127735 
   127736   if( !zFunc ){
   127737     zFunction = "";
   127738   }else{
   127739     zFree = zFunction = fts3QuoteId(zFunc);
   127740   }
   127741   fts3Appendf(pRc, &zRet, "?");
   127742   for(i=0; i<p->nColumn; i++){
   127743     fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
   127744   }
   127745   if( p->zLanguageid ){
   127746     fts3Appendf(pRc, &zRet, ", ?");
   127747   }
   127748   sqlite3_free(zFree);
   127749   return zRet;
   127750 }
   127751 
   127752 /*
   127753 ** This function interprets the string at (*pp) as a non-negative integer
   127754 ** value. It reads the integer and sets *pnOut to the value read, then
   127755 ** sets *pp to point to the byte immediately following the last byte of
   127756 ** the integer value.
   127757 **
   127758 ** Only decimal digits ('0'..'9') may be part of an integer value.
   127759 **
   127760 ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
   127761 ** the output value undefined. Otherwise SQLITE_OK is returned.
   127762 **
   127763 ** This function is used when parsing the "prefix=" FTS4 parameter.
   127764 */
   127765 static int fts3GobbleInt(const char **pp, int *pnOut){
   127766   const char *p;                  /* Iterator pointer */
   127767   int nInt = 0;                   /* Output value */
   127768 
   127769   for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
   127770     nInt = nInt * 10 + (p[0] - '0');
   127771   }
   127772   if( p==*pp ) return SQLITE_ERROR;
   127773   *pnOut = nInt;
   127774   *pp = p;
   127775   return SQLITE_OK;
   127776 }
   127777 
   127778 /*
   127779 ** This function is called to allocate an array of Fts3Index structures
   127780 ** representing the indexes maintained by the current FTS table. FTS tables
   127781 ** always maintain the main "terms" index, but may also maintain one or
   127782 ** more "prefix" indexes, depending on the value of the "prefix=" parameter
   127783 ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
   127784 **
   127785 ** Argument zParam is passed the value of the "prefix=" option if one was
   127786 ** specified, or NULL otherwise.
   127787 **
   127788 ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
   127789 ** the allocated array. *pnIndex is set to the number of elements in the
   127790 ** array. If an error does occur, an SQLite error code is returned.
   127791 **
   127792 ** Regardless of whether or not an error is returned, it is the responsibility
   127793 ** of the caller to call sqlite3_free() on the output array to free it.
   127794 */
   127795 static int fts3PrefixParameter(
   127796   const char *zParam,             /* ABC in prefix=ABC parameter to parse */
   127797   int *pnIndex,                   /* OUT: size of *apIndex[] array */
   127798   struct Fts3Index **apIndex      /* OUT: Array of indexes for this table */
   127799 ){
   127800   struct Fts3Index *aIndex;       /* Allocated array */
   127801   int nIndex = 1;                 /* Number of entries in array */
   127802 
   127803   if( zParam && zParam[0] ){
   127804     const char *p;
   127805     nIndex++;
   127806     for(p=zParam; *p; p++){
   127807       if( *p==',' ) nIndex++;
   127808     }
   127809   }
   127810 
   127811   aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
   127812   *apIndex = aIndex;
   127813   *pnIndex = nIndex;
   127814   if( !aIndex ){
   127815     return SQLITE_NOMEM;
   127816   }
   127817 
   127818   memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
   127819   if( zParam ){
   127820     const char *p = zParam;
   127821     int i;
   127822     for(i=1; i<nIndex; i++){
   127823       int nPrefix;
   127824       if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
   127825       aIndex[i].nPrefix = nPrefix;
   127826       p++;
   127827     }
   127828   }
   127829 
   127830   return SQLITE_OK;
   127831 }
   127832 
   127833 /*
   127834 ** This function is called when initializing an FTS4 table that uses the
   127835 ** content=xxx option. It determines the number of and names of the columns
   127836 ** of the new FTS4 table.
   127837 **
   127838 ** The third argument passed to this function is the value passed to the
   127839 ** config=xxx option (i.e. "xxx"). This function queries the database for
   127840 ** a table of that name. If found, the output variables are populated
   127841 ** as follows:
   127842 **
   127843 **   *pnCol:   Set to the number of columns table xxx has,
   127844 **
   127845 **   *pnStr:   Set to the total amount of space required to store a copy
   127846 **             of each columns name, including the nul-terminator.
   127847 **
   127848 **   *pazCol:  Set to point to an array of *pnCol strings. Each string is
   127849 **             the name of the corresponding column in table xxx. The array
   127850 **             and its contents are allocated using a single allocation. It
   127851 **             is the responsibility of the caller to free this allocation
   127852 **             by eventually passing the *pazCol value to sqlite3_free().
   127853 **
   127854 ** If the table cannot be found, an error code is returned and the output
   127855 ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
   127856 ** returned (and the output variables are undefined).
   127857 */
   127858 static int fts3ContentColumns(
   127859   sqlite3 *db,                    /* Database handle */
   127860   const char *zDb,                /* Name of db (i.e. "main", "temp" etc.) */
   127861   const char *zTbl,               /* Name of content table */
   127862   const char ***pazCol,           /* OUT: Malloc'd array of column names */
   127863   int *pnCol,                     /* OUT: Size of array *pazCol */
   127864   int *pnStr                      /* OUT: Bytes of string content */
   127865 ){
   127866   int rc = SQLITE_OK;             /* Return code */
   127867   char *zSql;                     /* "SELECT *" statement on zTbl */
   127868   sqlite3_stmt *pStmt = 0;        /* Compiled version of zSql */
   127869 
   127870   zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
   127871   if( !zSql ){
   127872     rc = SQLITE_NOMEM;
   127873   }else{
   127874     rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
   127875   }
   127876   sqlite3_free(zSql);
   127877 
   127878   if( rc==SQLITE_OK ){
   127879     const char **azCol;           /* Output array */
   127880     int nStr = 0;                 /* Size of all column names (incl. 0x00) */
   127881     int nCol;                     /* Number of table columns */
   127882     int i;                        /* Used to iterate through columns */
   127883 
   127884     /* Loop through the returned columns. Set nStr to the number of bytes of
   127885     ** space required to store a copy of each column name, including the
   127886     ** nul-terminator byte.  */
   127887     nCol = sqlite3_column_count(pStmt);
   127888     for(i=0; i<nCol; i++){
   127889       const char *zCol = sqlite3_column_name(pStmt, i);
   127890       nStr += (int)strlen(zCol) + 1;
   127891     }
   127892 
   127893     /* Allocate and populate the array to return. */
   127894     azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
   127895     if( azCol==0 ){
   127896       rc = SQLITE_NOMEM;
   127897     }else{
   127898       char *p = (char *)&azCol[nCol];
   127899       for(i=0; i<nCol; i++){
   127900         const char *zCol = sqlite3_column_name(pStmt, i);
   127901         int n = (int)strlen(zCol)+1;
   127902         memcpy(p, zCol, n);
   127903         azCol[i] = p;
   127904         p += n;
   127905       }
   127906     }
   127907     sqlite3_finalize(pStmt);
   127908 
   127909     /* Set the output variables. */
   127910     *pnCol = nCol;
   127911     *pnStr = nStr;
   127912     *pazCol = azCol;
   127913   }
   127914 
   127915   return rc;
   127916 }
   127917 
   127918 /*
   127919 ** This function is the implementation of both the xConnect and xCreate
   127920 ** methods of the FTS3 virtual table.
   127921 **
   127922 ** The argv[] array contains the following:
   127923 **
   127924 **   argv[0]   -> module name  ("fts3" or "fts4")
   127925 **   argv[1]   -> database name
   127926 **   argv[2]   -> table name
   127927 **   argv[...] -> "column name" and other module argument fields.
   127928 */
   127929 static int fts3InitVtab(
   127930   int isCreate,                   /* True for xCreate, false for xConnect */
   127931   sqlite3 *db,                    /* The SQLite database connection */
   127932   void *pAux,                     /* Hash table containing tokenizers */
   127933   int argc,                       /* Number of elements in argv array */
   127934   const char * const *argv,       /* xCreate/xConnect argument array */
   127935   sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
   127936   char **pzErr                    /* Write any error message here */
   127937 ){
   127938   Fts3Hash *pHash = (Fts3Hash *)pAux;
   127939   Fts3Table *p = 0;               /* Pointer to allocated vtab */
   127940   int rc = SQLITE_OK;             /* Return code */
   127941   int i;                          /* Iterator variable */
   127942   int nByte;                      /* Size of allocation used for *p */
   127943   int iCol;                       /* Column index */
   127944   int nString = 0;                /* Bytes required to hold all column names */
   127945   int nCol = 0;                   /* Number of columns in the FTS table */
   127946   char *zCsr;                     /* Space for holding column names */
   127947   int nDb;                        /* Bytes required to hold database name */
   127948   int nName;                      /* Bytes required to hold table name */
   127949   int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
   127950   const char **aCol;              /* Array of column names */
   127951   sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
   127952 
   127953   int nIndex;                     /* Size of aIndex[] array */
   127954   struct Fts3Index *aIndex = 0;   /* Array of indexes for this table */
   127955 
   127956   /* The results of parsing supported FTS4 key=value options: */
   127957   int bNoDocsize = 0;             /* True to omit %_docsize table */
   127958   int bDescIdx = 0;               /* True to store descending indexes */
   127959   char *zPrefix = 0;              /* Prefix parameter value (or NULL) */
   127960   char *zCompress = 0;            /* compress=? parameter (or NULL) */
   127961   char *zUncompress = 0;          /* uncompress=? parameter (or NULL) */
   127962   char *zContent = 0;             /* content=? parameter (or NULL) */
   127963   char *zLanguageid = 0;          /* languageid=? parameter (or NULL) */
   127964   char **azNotindexed = 0;        /* The set of notindexed= columns */
   127965   int nNotindexed = 0;            /* Size of azNotindexed[] array */
   127966 
   127967   assert( strlen(argv[0])==4 );
   127968   assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
   127969        || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
   127970   );
   127971 
   127972   nDb = (int)strlen(argv[1]) + 1;
   127973   nName = (int)strlen(argv[2]) + 1;
   127974 
   127975   nByte = sizeof(const char *) * (argc-2);
   127976   aCol = (const char **)sqlite3_malloc(nByte);
   127977   if( aCol ){
   127978     memset((void*)aCol, 0, nByte);
   127979     azNotindexed = (char **)sqlite3_malloc(nByte);
   127980   }
   127981   if( azNotindexed ){
   127982     memset(azNotindexed, 0, nByte);
   127983   }
   127984   if( !aCol || !azNotindexed ){
   127985     rc = SQLITE_NOMEM;
   127986     goto fts3_init_out;
   127987   }
   127988 
   127989   /* Loop through all of the arguments passed by the user to the FTS3/4
   127990   ** module (i.e. all the column names and special arguments). This loop
   127991   ** does the following:
   127992   **
   127993   **   + Figures out the number of columns the FTSX table will have, and
   127994   **     the number of bytes of space that must be allocated to store copies
   127995   **     of the column names.
   127996   **
   127997   **   + If there is a tokenizer specification included in the arguments,
   127998   **     initializes the tokenizer pTokenizer.
   127999   */
   128000   for(i=3; rc==SQLITE_OK && i<argc; i++){
   128001     char const *z = argv[i];
   128002     int nKey;
   128003     char *zVal;
   128004 
   128005     /* Check if this is a tokenizer specification */
   128006     if( !pTokenizer
   128007      && strlen(z)>8
   128008      && 0==sqlite3_strnicmp(z, "tokenize", 8)
   128009      && 0==sqlite3Fts3IsIdChar(z[8])
   128010     ){
   128011       rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
   128012     }
   128013 
   128014     /* Check if it is an FTS4 special argument. */
   128015     else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
   128016       struct Fts4Option {
   128017         const char *zOpt;
   128018         int nOpt;
   128019       } aFts4Opt[] = {
   128020         { "matchinfo",   9 },     /* 0 -> MATCHINFO */
   128021         { "prefix",      6 },     /* 1 -> PREFIX */
   128022         { "compress",    8 },     /* 2 -> COMPRESS */
   128023         { "uncompress", 10 },     /* 3 -> UNCOMPRESS */
   128024         { "order",       5 },     /* 4 -> ORDER */
   128025         { "content",     7 },     /* 5 -> CONTENT */
   128026         { "languageid", 10 },     /* 6 -> LANGUAGEID */
   128027         { "notindexed", 10 }      /* 7 -> NOTINDEXED */
   128028       };
   128029 
   128030       int iOpt;
   128031       if( !zVal ){
   128032         rc = SQLITE_NOMEM;
   128033       }else{
   128034         for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
   128035           struct Fts4Option *pOp = &aFts4Opt[iOpt];
   128036           if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
   128037             break;
   128038           }
   128039         }
   128040         if( iOpt==SizeofArray(aFts4Opt) ){
   128041           *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z);
   128042           rc = SQLITE_ERROR;
   128043         }else{
   128044           switch( iOpt ){
   128045             case 0:               /* MATCHINFO */
   128046               if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
   128047                 *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal);
   128048                 rc = SQLITE_ERROR;
   128049               }
   128050               bNoDocsize = 1;
   128051               break;
   128052 
   128053             case 1:               /* PREFIX */
   128054               sqlite3_free(zPrefix);
   128055               zPrefix = zVal;
   128056               zVal = 0;
   128057               break;
   128058 
   128059             case 2:               /* COMPRESS */
   128060               sqlite3_free(zCompress);
   128061               zCompress = zVal;
   128062               zVal = 0;
   128063               break;
   128064 
   128065             case 3:               /* UNCOMPRESS */
   128066               sqlite3_free(zUncompress);
   128067               zUncompress = zVal;
   128068               zVal = 0;
   128069               break;
   128070 
   128071             case 4:               /* ORDER */
   128072               if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
   128073                && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
   128074               ){
   128075                 *pzErr = sqlite3_mprintf("unrecognized order: %s", zVal);
   128076                 rc = SQLITE_ERROR;
   128077               }
   128078               bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
   128079               break;
   128080 
   128081             case 5:              /* CONTENT */
   128082               sqlite3_free(zContent);
   128083               zContent = zVal;
   128084               zVal = 0;
   128085               break;
   128086 
   128087             case 6:              /* LANGUAGEID */
   128088               assert( iOpt==6 );
   128089               sqlite3_free(zLanguageid);
   128090               zLanguageid = zVal;
   128091               zVal = 0;
   128092               break;
   128093 
   128094             case 7:              /* NOTINDEXED */
   128095               azNotindexed[nNotindexed++] = zVal;
   128096               zVal = 0;
   128097               break;
   128098           }
   128099         }
   128100         sqlite3_free(zVal);
   128101       }
   128102     }
   128103 
   128104     /* Otherwise, the argument is a column name. */
   128105     else {
   128106       nString += (int)(strlen(z) + 1);
   128107       aCol[nCol++] = z;
   128108     }
   128109   }
   128110 
   128111   /* If a content=xxx option was specified, the following:
   128112   **
   128113   **   1. Ignore any compress= and uncompress= options.
   128114   **
   128115   **   2. If no column names were specified as part of the CREATE VIRTUAL
   128116   **      TABLE statement, use all columns from the content table.
   128117   */
   128118   if( rc==SQLITE_OK && zContent ){
   128119     sqlite3_free(zCompress);
   128120     sqlite3_free(zUncompress);
   128121     zCompress = 0;
   128122     zUncompress = 0;
   128123     if( nCol==0 ){
   128124       sqlite3_free((void*)aCol);
   128125       aCol = 0;
   128126       rc = fts3ContentColumns(db, argv[1], zContent, &aCol, &nCol, &nString);
   128127 
   128128       /* If a languageid= option was specified, remove the language id
   128129       ** column from the aCol[] array. */
   128130       if( rc==SQLITE_OK && zLanguageid ){
   128131         int j;
   128132         for(j=0; j<nCol; j++){
   128133           if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
   128134             int k;
   128135             for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
   128136             nCol--;
   128137             break;
   128138           }
   128139         }
   128140       }
   128141     }
   128142   }
   128143   if( rc!=SQLITE_OK ) goto fts3_init_out;
   128144 
   128145   if( nCol==0 ){
   128146     assert( nString==0 );
   128147     aCol[0] = "content";
   128148     nString = 8;
   128149     nCol = 1;
   128150   }
   128151 
   128152   if( pTokenizer==0 ){
   128153     rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
   128154     if( rc!=SQLITE_OK ) goto fts3_init_out;
   128155   }
   128156   assert( pTokenizer );
   128157 
   128158   rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
   128159   if( rc==SQLITE_ERROR ){
   128160     assert( zPrefix );
   128161     *pzErr = sqlite3_mprintf("error parsing prefix parameter: %s", zPrefix);
   128162   }
   128163   if( rc!=SQLITE_OK ) goto fts3_init_out;
   128164 
   128165   /* Allocate and populate the Fts3Table structure. */
   128166   nByte = sizeof(Fts3Table) +                  /* Fts3Table */
   128167           nCol * sizeof(char *) +              /* azColumn */
   128168           nIndex * sizeof(struct Fts3Index) +  /* aIndex */
   128169           nCol * sizeof(u8) +                  /* abNotindexed */
   128170           nName +                              /* zName */
   128171           nDb +                                /* zDb */
   128172           nString;                             /* Space for azColumn strings */
   128173   p = (Fts3Table*)sqlite3_malloc(nByte);
   128174   if( p==0 ){
   128175     rc = SQLITE_NOMEM;
   128176     goto fts3_init_out;
   128177   }
   128178   memset(p, 0, nByte);
   128179   p->db = db;
   128180   p->nColumn = nCol;
   128181   p->nPendingData = 0;
   128182   p->azColumn = (char **)&p[1];
   128183   p->pTokenizer = pTokenizer;
   128184   p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
   128185   p->bHasDocsize = (isFts4 && bNoDocsize==0);
   128186   p->bHasStat = isFts4;
   128187   p->bFts4 = isFts4;
   128188   p->bDescIdx = bDescIdx;
   128189   p->nAutoincrmerge = 0xff;   /* 0xff means setting unknown */
   128190   p->zContentTbl = zContent;
   128191   p->zLanguageid = zLanguageid;
   128192   zContent = 0;
   128193   zLanguageid = 0;
   128194   TESTONLY( p->inTransaction = -1 );
   128195   TESTONLY( p->mxSavepoint = -1 );
   128196 
   128197   p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
   128198   memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
   128199   p->nIndex = nIndex;
   128200   for(i=0; i<nIndex; i++){
   128201     fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
   128202   }
   128203   p->abNotindexed = (u8 *)&p->aIndex[nIndex];
   128204 
   128205   /* Fill in the zName and zDb fields of the vtab structure. */
   128206   zCsr = (char *)&p->abNotindexed[nCol];
   128207   p->zName = zCsr;
   128208   memcpy(zCsr, argv[2], nName);
   128209   zCsr += nName;
   128210   p->zDb = zCsr;
   128211   memcpy(zCsr, argv[1], nDb);
   128212   zCsr += nDb;
   128213 
   128214   /* Fill in the azColumn array */
   128215   for(iCol=0; iCol<nCol; iCol++){
   128216     char *z;
   128217     int n = 0;
   128218     z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
   128219     memcpy(zCsr, z, n);
   128220     zCsr[n] = '\0';
   128221     sqlite3Fts3Dequote(zCsr);
   128222     p->azColumn[iCol] = zCsr;
   128223     zCsr += n+1;
   128224     assert( zCsr <= &((char *)p)[nByte] );
   128225   }
   128226 
   128227   /* Fill in the abNotindexed array */
   128228   for(iCol=0; iCol<nCol; iCol++){
   128229     int n = (int)strlen(p->azColumn[iCol]);
   128230     for(i=0; i<nNotindexed; i++){
   128231       char *zNot = azNotindexed[i];
   128232       if( zNot && n==(int)strlen(zNot)
   128233        && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n)
   128234       ){
   128235         p->abNotindexed[iCol] = 1;
   128236         sqlite3_free(zNot);
   128237         azNotindexed[i] = 0;
   128238       }
   128239     }
   128240   }
   128241   for(i=0; i<nNotindexed; i++){
   128242     if( azNotindexed[i] ){
   128243       *pzErr = sqlite3_mprintf("no such column: %s", azNotindexed[i]);
   128244       rc = SQLITE_ERROR;
   128245     }
   128246   }
   128247 
   128248   if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
   128249     char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
   128250     rc = SQLITE_ERROR;
   128251     *pzErr = sqlite3_mprintf("missing %s parameter in fts4 constructor", zMiss);
   128252   }
   128253   p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
   128254   p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
   128255   if( rc!=SQLITE_OK ) goto fts3_init_out;
   128256 
   128257   /* If this is an xCreate call, create the underlying tables in the
   128258   ** database. TODO: For xConnect(), it could verify that said tables exist.
   128259   */
   128260   if( isCreate ){
   128261     rc = fts3CreateTables(p);
   128262   }
   128263 
   128264   /* Check to see if a legacy fts3 table has been "upgraded" by the
   128265   ** addition of a %_stat table so that it can use incremental merge.
   128266   */
   128267   if( !isFts4 && !isCreate ){
   128268     p->bHasStat = 2;
   128269   }
   128270 
   128271   /* Figure out the page-size for the database. This is required in order to
   128272   ** estimate the cost of loading large doclists from the database.  */
   128273   fts3DatabasePageSize(&rc, p);
   128274   p->nNodeSize = p->nPgsz-35;
   128275 
   128276   /* Declare the table schema to SQLite. */
   128277   fts3DeclareVtab(&rc, p);
   128278 
   128279 fts3_init_out:
   128280   sqlite3_free(zPrefix);
   128281   sqlite3_free(aIndex);
   128282   sqlite3_free(zCompress);
   128283   sqlite3_free(zUncompress);
   128284   sqlite3_free(zContent);
   128285   sqlite3_free(zLanguageid);
   128286   for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
   128287   sqlite3_free((void *)aCol);
   128288   sqlite3_free((void *)azNotindexed);
   128289   if( rc!=SQLITE_OK ){
   128290     if( p ){
   128291       fts3DisconnectMethod((sqlite3_vtab *)p);
   128292     }else if( pTokenizer ){
   128293       pTokenizer->pModule->xDestroy(pTokenizer);
   128294     }
   128295   }else{
   128296     assert( p->pSegments==0 );
   128297     *ppVTab = &p->base;
   128298   }
   128299   return rc;
   128300 }
   128301 
   128302 /*
   128303 ** The xConnect() and xCreate() methods for the virtual table. All the
   128304 ** work is done in function fts3InitVtab().
   128305 */
   128306 static int fts3ConnectMethod(
   128307   sqlite3 *db,                    /* Database connection */
   128308   void *pAux,                     /* Pointer to tokenizer hash table */
   128309   int argc,                       /* Number of elements in argv array */
   128310   const char * const *argv,       /* xCreate/xConnect argument array */
   128311   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
   128312   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
   128313 ){
   128314   return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
   128315 }
   128316 static int fts3CreateMethod(
   128317   sqlite3 *db,                    /* Database connection */
   128318   void *pAux,                     /* Pointer to tokenizer hash table */
   128319   int argc,                       /* Number of elements in argv array */
   128320   const char * const *argv,       /* xCreate/xConnect argument array */
   128321   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
   128322   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
   128323 ){
   128324   return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
   128325 }
   128326 
   128327 /*
   128328 ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
   128329 ** extension is currently being used by a version of SQLite too old to
   128330 ** support estimatedRows. In that case this function is a no-op.
   128331 */
   128332 static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
   128333 #if SQLITE_VERSION_NUMBER>=3008002
   128334   if( sqlite3_libversion_number()>=3008002 ){
   128335     pIdxInfo->estimatedRows = nRow;
   128336   }
   128337 #endif
   128338 }
   128339 
   128340 /*
   128341 ** Implementation of the xBestIndex method for FTS3 tables. There
   128342 ** are three possible strategies, in order of preference:
   128343 **
   128344 **   1. Direct lookup by rowid or docid.
   128345 **   2. Full-text search using a MATCH operator on a non-docid column.
   128346 **   3. Linear scan of %_content table.
   128347 */
   128348 static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
   128349   Fts3Table *p = (Fts3Table *)pVTab;
   128350   int i;                          /* Iterator variable */
   128351   int iCons = -1;                 /* Index of constraint to use */
   128352 
   128353   int iLangidCons = -1;           /* Index of langid=x constraint, if present */
   128354   int iDocidGe = -1;              /* Index of docid>=x constraint, if present */
   128355   int iDocidLe = -1;              /* Index of docid<=x constraint, if present */
   128356   int iIdx;
   128357 
   128358   /* By default use a full table scan. This is an expensive option,
   128359   ** so search through the constraints to see if a more efficient
   128360   ** strategy is possible.
   128361   */
   128362   pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
   128363   pInfo->estimatedCost = 5000000;
   128364   for(i=0; i<pInfo->nConstraint; i++){
   128365     int bDocid;                 /* True if this constraint is on docid */
   128366     struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
   128367     if( pCons->usable==0 ){
   128368       if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
   128369         /* There exists an unusable MATCH constraint. This means that if
   128370         ** the planner does elect to use the results of this call as part
   128371         ** of the overall query plan the user will see an "unable to use
   128372         ** function MATCH in the requested context" error. To discourage
   128373         ** this, return a very high cost here.  */
   128374         pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
   128375         pInfo->estimatedCost = 1e50;
   128376         fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
   128377         return SQLITE_OK;
   128378       }
   128379       continue;
   128380     }
   128381 
   128382     bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
   128383 
   128384     /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
   128385     if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
   128386       pInfo->idxNum = FTS3_DOCID_SEARCH;
   128387       pInfo->estimatedCost = 1.0;
   128388       iCons = i;
   128389     }
   128390 
   128391     /* A MATCH constraint. Use a full-text search.
   128392     **
   128393     ** If there is more than one MATCH constraint available, use the first
   128394     ** one encountered. If there is both a MATCH constraint and a direct
   128395     ** rowid/docid lookup, prefer the MATCH strategy. This is done even
   128396     ** though the rowid/docid lookup is faster than a MATCH query, selecting
   128397     ** it would lead to an "unable to use function MATCH in the requested
   128398     ** context" error.
   128399     */
   128400     if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
   128401      && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
   128402     ){
   128403       pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
   128404       pInfo->estimatedCost = 2.0;
   128405       iCons = i;
   128406     }
   128407 
   128408     /* Equality constraint on the langid column */
   128409     if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
   128410      && pCons->iColumn==p->nColumn + 2
   128411     ){
   128412       iLangidCons = i;
   128413     }
   128414 
   128415     if( bDocid ){
   128416       switch( pCons->op ){
   128417         case SQLITE_INDEX_CONSTRAINT_GE:
   128418         case SQLITE_INDEX_CONSTRAINT_GT:
   128419           iDocidGe = i;
   128420           break;
   128421 
   128422         case SQLITE_INDEX_CONSTRAINT_LE:
   128423         case SQLITE_INDEX_CONSTRAINT_LT:
   128424           iDocidLe = i;
   128425           break;
   128426       }
   128427     }
   128428   }
   128429 
   128430   iIdx = 1;
   128431   if( iCons>=0 ){
   128432     pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
   128433     pInfo->aConstraintUsage[iCons].omit = 1;
   128434   }
   128435   if( iLangidCons>=0 ){
   128436     pInfo->idxNum |= FTS3_HAVE_LANGID;
   128437     pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
   128438   }
   128439   if( iDocidGe>=0 ){
   128440     pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
   128441     pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
   128442   }
   128443   if( iDocidLe>=0 ){
   128444     pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
   128445     pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
   128446   }
   128447 
   128448   /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
   128449   ** docid) order. Both ascending and descending are possible.
   128450   */
   128451   if( pInfo->nOrderBy==1 ){
   128452     struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
   128453     if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
   128454       if( pOrder->desc ){
   128455         pInfo->idxStr = "DESC";
   128456       }else{
   128457         pInfo->idxStr = "ASC";
   128458       }
   128459       pInfo->orderByConsumed = 1;
   128460     }
   128461   }
   128462 
   128463   assert( p->pSegments==0 );
   128464   return SQLITE_OK;
   128465 }
   128466 
   128467 /*
   128468 ** Implementation of xOpen method.
   128469 */
   128470 static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
   128471   sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
   128472 
   128473   UNUSED_PARAMETER(pVTab);
   128474 
   128475   /* Allocate a buffer large enough for an Fts3Cursor structure. If the
   128476   ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
   128477   ** if the allocation fails, return SQLITE_NOMEM.
   128478   */
   128479   *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
   128480   if( !pCsr ){
   128481     return SQLITE_NOMEM;
   128482   }
   128483   memset(pCsr, 0, sizeof(Fts3Cursor));
   128484   return SQLITE_OK;
   128485 }
   128486 
   128487 /*
   128488 ** Close the cursor.  For additional information see the documentation
   128489 ** on the xClose method of the virtual table interface.
   128490 */
   128491 static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
   128492   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
   128493   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
   128494   sqlite3_finalize(pCsr->pStmt);
   128495   sqlite3Fts3ExprFree(pCsr->pExpr);
   128496   sqlite3Fts3FreeDeferredTokens(pCsr);
   128497   sqlite3_free(pCsr->aDoclist);
   128498   sqlite3_free(pCsr->aMatchinfo);
   128499   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
   128500   sqlite3_free(pCsr);
   128501   return SQLITE_OK;
   128502 }
   128503 
   128504 /*
   128505 ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
   128506 ** compose and prepare an SQL statement of the form:
   128507 **
   128508 **    "SELECT <columns> FROM %_content WHERE rowid = ?"
   128509 **
   128510 ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
   128511 ** it. If an error occurs, return an SQLite error code.
   128512 **
   128513 ** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
   128514 */
   128515 static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
   128516   int rc = SQLITE_OK;
   128517   if( pCsr->pStmt==0 ){
   128518     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
   128519     char *zSql;
   128520     zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
   128521     if( !zSql ) return SQLITE_NOMEM;
   128522     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
   128523     sqlite3_free(zSql);
   128524   }
   128525   *ppStmt = pCsr->pStmt;
   128526   return rc;
   128527 }
   128528 
   128529 /*
   128530 ** Position the pCsr->pStmt statement so that it is on the row
   128531 ** of the %_content table that contains the last match.  Return
   128532 ** SQLITE_OK on success.
   128533 */
   128534 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
   128535   int rc = SQLITE_OK;
   128536   if( pCsr->isRequireSeek ){
   128537     sqlite3_stmt *pStmt = 0;
   128538 
   128539     rc = fts3CursorSeekStmt(pCsr, &pStmt);
   128540     if( rc==SQLITE_OK ){
   128541       sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
   128542       pCsr->isRequireSeek = 0;
   128543       if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
   128544         return SQLITE_OK;
   128545       }else{
   128546         rc = sqlite3_reset(pCsr->pStmt);
   128547         if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
   128548           /* If no row was found and no error has occurred, then the %_content
   128549           ** table is missing a row that is present in the full-text index.
   128550           ** The data structures are corrupt.  */
   128551           rc = FTS_CORRUPT_VTAB;
   128552           pCsr->isEof = 1;
   128553         }
   128554       }
   128555     }
   128556   }
   128557 
   128558   if( rc!=SQLITE_OK && pContext ){
   128559     sqlite3_result_error_code(pContext, rc);
   128560   }
   128561   return rc;
   128562 }
   128563 
   128564 /*
   128565 ** This function is used to process a single interior node when searching
   128566 ** a b-tree for a term or term prefix. The node data is passed to this
   128567 ** function via the zNode/nNode parameters. The term to search for is
   128568 ** passed in zTerm/nTerm.
   128569 **
   128570 ** If piFirst is not NULL, then this function sets *piFirst to the blockid
   128571 ** of the child node that heads the sub-tree that may contain the term.
   128572 **
   128573 ** If piLast is not NULL, then *piLast is set to the right-most child node
   128574 ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
   128575 ** a prefix.
   128576 **
   128577 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
   128578 */
   128579 static int fts3ScanInteriorNode(
   128580   const char *zTerm,              /* Term to select leaves for */
   128581   int nTerm,                      /* Size of term zTerm in bytes */
   128582   const char *zNode,              /* Buffer containing segment interior node */
   128583   int nNode,                      /* Size of buffer at zNode */
   128584   sqlite3_int64 *piFirst,         /* OUT: Selected child node */
   128585   sqlite3_int64 *piLast           /* OUT: Selected child node */
   128586 ){
   128587   int rc = SQLITE_OK;             /* Return code */
   128588   const char *zCsr = zNode;       /* Cursor to iterate through node */
   128589   const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
   128590   char *zBuffer = 0;              /* Buffer to load terms into */
   128591   int nAlloc = 0;                 /* Size of allocated buffer */
   128592   int isFirstTerm = 1;            /* True when processing first term on page */
   128593   sqlite3_int64 iChild;           /* Block id of child node to descend to */
   128594 
   128595   /* Skip over the 'height' varint that occurs at the start of every
   128596   ** interior node. Then load the blockid of the left-child of the b-tree
   128597   ** node into variable iChild.
   128598   **
   128599   ** Even if the data structure on disk is corrupted, this (reading two
   128600   ** varints from the buffer) does not risk an overread. If zNode is a
   128601   ** root node, then the buffer comes from a SELECT statement. SQLite does
   128602   ** not make this guarantee explicitly, but in practice there are always
   128603   ** either more than 20 bytes of allocated space following the nNode bytes of
   128604   ** contents, or two zero bytes. Or, if the node is read from the %_segments
   128605   ** table, then there are always 20 bytes of zeroed padding following the
   128606   ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
   128607   */
   128608   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
   128609   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
   128610   if( zCsr>zEnd ){
   128611     return FTS_CORRUPT_VTAB;
   128612   }
   128613 
   128614   while( zCsr<zEnd && (piFirst || piLast) ){
   128615     int cmp;                      /* memcmp() result */
   128616     int nSuffix;                  /* Size of term suffix */
   128617     int nPrefix = 0;              /* Size of term prefix */
   128618     int nBuffer;                  /* Total term size */
   128619 
   128620     /* Load the next term on the node into zBuffer. Use realloc() to expand
   128621     ** the size of zBuffer if required.  */
   128622     if( !isFirstTerm ){
   128623       zCsr += fts3GetVarint32(zCsr, &nPrefix);
   128624     }
   128625     isFirstTerm = 0;
   128626     zCsr += fts3GetVarint32(zCsr, &nSuffix);
   128627 
   128628     if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
   128629       rc = FTS_CORRUPT_VTAB;
   128630       goto finish_scan;
   128631     }
   128632     if( nPrefix+nSuffix>nAlloc ){
   128633       char *zNew;
   128634       nAlloc = (nPrefix+nSuffix) * 2;
   128635       zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
   128636       if( !zNew ){
   128637         rc = SQLITE_NOMEM;
   128638         goto finish_scan;
   128639       }
   128640       zBuffer = zNew;
   128641     }
   128642     assert( zBuffer );
   128643     memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
   128644     nBuffer = nPrefix + nSuffix;
   128645     zCsr += nSuffix;
   128646 
   128647     /* Compare the term we are searching for with the term just loaded from
   128648     ** the interior node. If the specified term is greater than or equal
   128649     ** to the term from the interior node, then all terms on the sub-tree
   128650     ** headed by node iChild are smaller than zTerm. No need to search
   128651     ** iChild.
   128652     **
   128653     ** If the interior node term is larger than the specified term, then
   128654     ** the tree headed by iChild may contain the specified term.
   128655     */
   128656     cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
   128657     if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
   128658       *piFirst = iChild;
   128659       piFirst = 0;
   128660     }
   128661 
   128662     if( piLast && cmp<0 ){
   128663       *piLast = iChild;
   128664       piLast = 0;
   128665     }
   128666 
   128667     iChild++;
   128668   };
   128669 
   128670   if( piFirst ) *piFirst = iChild;
   128671   if( piLast ) *piLast = iChild;
   128672 
   128673  finish_scan:
   128674   sqlite3_free(zBuffer);
   128675   return rc;
   128676 }
   128677 
   128678 
   128679 /*
   128680 ** The buffer pointed to by argument zNode (size nNode bytes) contains an
   128681 ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
   128682 ** contains a term. This function searches the sub-tree headed by the zNode
   128683 ** node for the range of leaf nodes that may contain the specified term
   128684 ** or terms for which the specified term is a prefix.
   128685 **
   128686 ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
   128687 ** left-most leaf node in the tree that may contain the specified term.
   128688 ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
   128689 ** right-most leaf node that may contain a term for which the specified
   128690 ** term is a prefix.
   128691 **
   128692 ** It is possible that the range of returned leaf nodes does not contain
   128693 ** the specified term or any terms for which it is a prefix. However, if the
   128694 ** segment does contain any such terms, they are stored within the identified
   128695 ** range. Because this function only inspects interior segment nodes (and
   128696 ** never loads leaf nodes into memory), it is not possible to be sure.
   128697 **
   128698 ** If an error occurs, an error code other than SQLITE_OK is returned.
   128699 */
   128700 static int fts3SelectLeaf(
   128701   Fts3Table *p,                   /* Virtual table handle */
   128702   const char *zTerm,              /* Term to select leaves for */
   128703   int nTerm,                      /* Size of term zTerm in bytes */
   128704   const char *zNode,              /* Buffer containing segment interior node */
   128705   int nNode,                      /* Size of buffer at zNode */
   128706   sqlite3_int64 *piLeaf,          /* Selected leaf node */
   128707   sqlite3_int64 *piLeaf2          /* Selected leaf node */
   128708 ){
   128709   int rc;                         /* Return code */
   128710   int iHeight;                    /* Height of this node in tree */
   128711 
   128712   assert( piLeaf || piLeaf2 );
   128713 
   128714   fts3GetVarint32(zNode, &iHeight);
   128715   rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
   128716   assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
   128717 
   128718   if( rc==SQLITE_OK && iHeight>1 ){
   128719     char *zBlob = 0;              /* Blob read from %_segments table */
   128720     int nBlob;                    /* Size of zBlob in bytes */
   128721 
   128722     if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
   128723       rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
   128724       if( rc==SQLITE_OK ){
   128725         rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
   128726       }
   128727       sqlite3_free(zBlob);
   128728       piLeaf = 0;
   128729       zBlob = 0;
   128730     }
   128731 
   128732     if( rc==SQLITE_OK ){
   128733       rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
   128734     }
   128735     if( rc==SQLITE_OK ){
   128736       rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
   128737     }
   128738     sqlite3_free(zBlob);
   128739   }
   128740 
   128741   return rc;
   128742 }
   128743 
   128744 /*
   128745 ** This function is used to create delta-encoded serialized lists of FTS3
   128746 ** varints. Each call to this function appends a single varint to a list.
   128747 */
   128748 static void fts3PutDeltaVarint(
   128749   char **pp,                      /* IN/OUT: Output pointer */
   128750   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
   128751   sqlite3_int64 iVal              /* Write this value to the list */
   128752 ){
   128753   assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
   128754   *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
   128755   *piPrev = iVal;
   128756 }
   128757 
   128758 /*
   128759 ** When this function is called, *ppPoslist is assumed to point to the
   128760 ** start of a position-list. After it returns, *ppPoslist points to the
   128761 ** first byte after the position-list.
   128762 **
   128763 ** A position list is list of positions (delta encoded) and columns for
   128764 ** a single document record of a doclist.  So, in other words, this
   128765 ** routine advances *ppPoslist so that it points to the next docid in
   128766 ** the doclist, or to the first byte past the end of the doclist.
   128767 **
   128768 ** If pp is not NULL, then the contents of the position list are copied
   128769 ** to *pp. *pp is set to point to the first byte past the last byte copied
   128770 ** before this function returns.
   128771 */
   128772 static void fts3PoslistCopy(char **pp, char **ppPoslist){
   128773   char *pEnd = *ppPoslist;
   128774   char c = 0;
   128775 
   128776   /* The end of a position list is marked by a zero encoded as an FTS3
   128777   ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
   128778   ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
   128779   ** of some other, multi-byte, value.
   128780   **
   128781   ** The following while-loop moves pEnd to point to the first byte that is not
   128782   ** immediately preceded by a byte with the 0x80 bit set. Then increments
   128783   ** pEnd once more so that it points to the byte immediately following the
   128784   ** last byte in the position-list.
   128785   */
   128786   while( *pEnd | c ){
   128787     c = *pEnd++ & 0x80;
   128788     testcase( c!=0 && (*pEnd)==0 );
   128789   }
   128790   pEnd++;  /* Advance past the POS_END terminator byte */
   128791 
   128792   if( pp ){
   128793     int n = (int)(pEnd - *ppPoslist);
   128794     char *p = *pp;
   128795     memcpy(p, *ppPoslist, n);
   128796     p += n;
   128797     *pp = p;
   128798   }
   128799   *ppPoslist = pEnd;
   128800 }
   128801 
   128802 /*
   128803 ** When this function is called, *ppPoslist is assumed to point to the
   128804 ** start of a column-list. After it returns, *ppPoslist points to the
   128805 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
   128806 **
   128807 ** A column-list is list of delta-encoded positions for a single column
   128808 ** within a single document within a doclist.
   128809 **
   128810 ** The column-list is terminated either by a POS_COLUMN varint (1) or
   128811 ** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
   128812 ** the POS_COLUMN or POS_END that terminates the column-list.
   128813 **
   128814 ** If pp is not NULL, then the contents of the column-list are copied
   128815 ** to *pp. *pp is set to point to the first byte past the last byte copied
   128816 ** before this function returns.  The POS_COLUMN or POS_END terminator
   128817 ** is not copied into *pp.
   128818 */
   128819 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
   128820   char *pEnd = *ppPoslist;
   128821   char c = 0;
   128822 
   128823   /* A column-list is terminated by either a 0x01 or 0x00 byte that is
   128824   ** not part of a multi-byte varint.
   128825   */
   128826   while( 0xFE & (*pEnd | c) ){
   128827     c = *pEnd++ & 0x80;
   128828     testcase( c!=0 && ((*pEnd)&0xfe)==0 );
   128829   }
   128830   if( pp ){
   128831     int n = (int)(pEnd - *ppPoslist);
   128832     char *p = *pp;
   128833     memcpy(p, *ppPoslist, n);
   128834     p += n;
   128835     *pp = p;
   128836   }
   128837   *ppPoslist = pEnd;
   128838 }
   128839 
   128840 /*
   128841 ** Value used to signify the end of an position-list. This is safe because
   128842 ** it is not possible to have a document with 2^31 terms.
   128843 */
   128844 #define POSITION_LIST_END 0x7fffffff
   128845 
   128846 /*
   128847 ** This function is used to help parse position-lists. When this function is
   128848 ** called, *pp may point to the start of the next varint in the position-list
   128849 ** being parsed, or it may point to 1 byte past the end of the position-list
   128850 ** (in which case **pp will be a terminator bytes POS_END (0) or
   128851 ** (1)).
   128852 **
   128853 ** If *pp points past the end of the current position-list, set *pi to
   128854 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
   128855 ** increment the current value of *pi by the value read, and set *pp to
   128856 ** point to the next value before returning.
   128857 **
   128858 ** Before calling this routine *pi must be initialized to the value of
   128859 ** the previous position, or zero if we are reading the first position
   128860 ** in the position-list.  Because positions are delta-encoded, the value
   128861 ** of the previous position is needed in order to compute the value of
   128862 ** the next position.
   128863 */
   128864 static void fts3ReadNextPos(
   128865   char **pp,                    /* IN/OUT: Pointer into position-list buffer */
   128866   sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
   128867 ){
   128868   if( (**pp)&0xFE ){
   128869     fts3GetDeltaVarint(pp, pi);
   128870     *pi -= 2;
   128871   }else{
   128872     *pi = POSITION_LIST_END;
   128873   }
   128874 }
   128875 
   128876 /*
   128877 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
   128878 ** the value of iCol encoded as a varint to *pp.   This will start a new
   128879 ** column list.
   128880 **
   128881 ** Set *pp to point to the byte just after the last byte written before
   128882 ** returning (do not modify it if iCol==0). Return the total number of bytes
   128883 ** written (0 if iCol==0).
   128884 */
   128885 static int fts3PutColNumber(char **pp, int iCol){
   128886   int n = 0;                      /* Number of bytes written */
   128887   if( iCol ){
   128888     char *p = *pp;                /* Output pointer */
   128889     n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
   128890     *p = 0x01;
   128891     *pp = &p[n];
   128892   }
   128893   return n;
   128894 }
   128895 
   128896 /*
   128897 ** Compute the union of two position lists.  The output written
   128898 ** into *pp contains all positions of both *pp1 and *pp2 in sorted
   128899 ** order and with any duplicates removed.  All pointers are
   128900 ** updated appropriately.   The caller is responsible for insuring
   128901 ** that there is enough space in *pp to hold the complete output.
   128902 */
   128903 static void fts3PoslistMerge(
   128904   char **pp,                      /* Output buffer */
   128905   char **pp1,                     /* Left input list */
   128906   char **pp2                      /* Right input list */
   128907 ){
   128908   char *p = *pp;
   128909   char *p1 = *pp1;
   128910   char *p2 = *pp2;
   128911 
   128912   while( *p1 || *p2 ){
   128913     int iCol1;         /* The current column index in pp1 */
   128914     int iCol2;         /* The current column index in pp2 */
   128915 
   128916     if( *p1==POS_COLUMN ) fts3GetVarint32(&p1[1], &iCol1);
   128917     else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
   128918     else iCol1 = 0;
   128919 
   128920     if( *p2==POS_COLUMN ) fts3GetVarint32(&p2[1], &iCol2);
   128921     else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
   128922     else iCol2 = 0;
   128923 
   128924     if( iCol1==iCol2 ){
   128925       sqlite3_int64 i1 = 0;       /* Last position from pp1 */
   128926       sqlite3_int64 i2 = 0;       /* Last position from pp2 */
   128927       sqlite3_int64 iPrev = 0;
   128928       int n = fts3PutColNumber(&p, iCol1);
   128929       p1 += n;
   128930       p2 += n;
   128931 
   128932       /* At this point, both p1 and p2 point to the start of column-lists
   128933       ** for the same column (the column with index iCol1 and iCol2).
   128934       ** A column-list is a list of non-negative delta-encoded varints, each
   128935       ** incremented by 2 before being stored. Each list is terminated by a
   128936       ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
   128937       ** and writes the results to buffer p. p is left pointing to the byte
   128938       ** after the list written. No terminator (POS_END or POS_COLUMN) is
   128939       ** written to the output.
   128940       */
   128941       fts3GetDeltaVarint(&p1, &i1);
   128942       fts3GetDeltaVarint(&p2, &i2);
   128943       do {
   128944         fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
   128945         iPrev -= 2;
   128946         if( i1==i2 ){
   128947           fts3ReadNextPos(&p1, &i1);
   128948           fts3ReadNextPos(&p2, &i2);
   128949         }else if( i1<i2 ){
   128950           fts3ReadNextPos(&p1, &i1);
   128951         }else{
   128952           fts3ReadNextPos(&p2, &i2);
   128953         }
   128954       }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
   128955     }else if( iCol1<iCol2 ){
   128956       p1 += fts3PutColNumber(&p, iCol1);
   128957       fts3ColumnlistCopy(&p, &p1);
   128958     }else{
   128959       p2 += fts3PutColNumber(&p, iCol2);
   128960       fts3ColumnlistCopy(&p, &p2);
   128961     }
   128962   }
   128963 
   128964   *p++ = POS_END;
   128965   *pp = p;
   128966   *pp1 = p1 + 1;
   128967   *pp2 = p2 + 1;
   128968 }
   128969 
   128970 /*
   128971 ** This function is used to merge two position lists into one. When it is
   128972 ** called, *pp1 and *pp2 must both point to position lists. A position-list is
   128973 ** the part of a doclist that follows each document id. For example, if a row
   128974 ** contains:
   128975 **
   128976 **     'a b c'|'x y z'|'a b b a'
   128977 **
   128978 ** Then the position list for this row for token 'b' would consist of:
   128979 **
   128980 **     0x02 0x01 0x02 0x03 0x03 0x00
   128981 **
   128982 ** When this function returns, both *pp1 and *pp2 are left pointing to the
   128983 ** byte following the 0x00 terminator of their respective position lists.
   128984 **
   128985 ** If isSaveLeft is 0, an entry is added to the output position list for
   128986 ** each position in *pp2 for which there exists one or more positions in
   128987 ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
   128988 ** when the *pp1 token appears before the *pp2 token, but not more than nToken
   128989 ** slots before it.
   128990 **
   128991 ** e.g. nToken==1 searches for adjacent positions.
   128992 */
   128993 static int fts3PoslistPhraseMerge(
   128994   char **pp,                      /* IN/OUT: Preallocated output buffer */
   128995   int nToken,                     /* Maximum difference in token positions */
   128996   int isSaveLeft,                 /* Save the left position */
   128997   int isExact,                    /* If *pp1 is exactly nTokens before *pp2 */
   128998   char **pp1,                     /* IN/OUT: Left input list */
   128999   char **pp2                      /* IN/OUT: Right input list */
   129000 ){
   129001   char *p = *pp;
   129002   char *p1 = *pp1;
   129003   char *p2 = *pp2;
   129004   int iCol1 = 0;
   129005   int iCol2 = 0;
   129006 
   129007   /* Never set both isSaveLeft and isExact for the same invocation. */
   129008   assert( isSaveLeft==0 || isExact==0 );
   129009 
   129010   assert( p!=0 && *p1!=0 && *p2!=0 );
   129011   if( *p1==POS_COLUMN ){
   129012     p1++;
   129013     p1 += fts3GetVarint32(p1, &iCol1);
   129014   }
   129015   if( *p2==POS_COLUMN ){
   129016     p2++;
   129017     p2 += fts3GetVarint32(p2, &iCol2);
   129018   }
   129019 
   129020   while( 1 ){
   129021     if( iCol1==iCol2 ){
   129022       char *pSave = p;
   129023       sqlite3_int64 iPrev = 0;
   129024       sqlite3_int64 iPos1 = 0;
   129025       sqlite3_int64 iPos2 = 0;
   129026 
   129027       if( iCol1 ){
   129028         *p++ = POS_COLUMN;
   129029         p += sqlite3Fts3PutVarint(p, iCol1);
   129030       }
   129031 
   129032       assert( *p1!=POS_END && *p1!=POS_COLUMN );
   129033       assert( *p2!=POS_END && *p2!=POS_COLUMN );
   129034       fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
   129035       fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
   129036 
   129037       while( 1 ){
   129038         if( iPos2==iPos1+nToken
   129039          || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
   129040         ){
   129041           sqlite3_int64 iSave;
   129042           iSave = isSaveLeft ? iPos1 : iPos2;
   129043           fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
   129044           pSave = 0;
   129045           assert( p );
   129046         }
   129047         if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
   129048           if( (*p2&0xFE)==0 ) break;
   129049           fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
   129050         }else{
   129051           if( (*p1&0xFE)==0 ) break;
   129052           fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
   129053         }
   129054       }
   129055 
   129056       if( pSave ){
   129057         assert( pp && p );
   129058         p = pSave;
   129059       }
   129060 
   129061       fts3ColumnlistCopy(0, &p1);
   129062       fts3ColumnlistCopy(0, &p2);
   129063       assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
   129064       if( 0==*p1 || 0==*p2 ) break;
   129065 
   129066       p1++;
   129067       p1 += fts3GetVarint32(p1, &iCol1);
   129068       p2++;
   129069       p2 += fts3GetVarint32(p2, &iCol2);
   129070     }
   129071 
   129072     /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
   129073     ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
   129074     ** end of the position list, or the 0x01 that precedes the next
   129075     ** column-number in the position list.
   129076     */
   129077     else if( iCol1<iCol2 ){
   129078       fts3ColumnlistCopy(0, &p1);
   129079       if( 0==*p1 ) break;
   129080       p1++;
   129081       p1 += fts3GetVarint32(p1, &iCol1);
   129082     }else{
   129083       fts3ColumnlistCopy(0, &p2);
   129084       if( 0==*p2 ) break;
   129085       p2++;
   129086       p2 += fts3GetVarint32(p2, &iCol2);
   129087     }
   129088   }
   129089 
   129090   fts3PoslistCopy(0, &p2);
   129091   fts3PoslistCopy(0, &p1);
   129092   *pp1 = p1;
   129093   *pp2 = p2;
   129094   if( *pp==p ){
   129095     return 0;
   129096   }
   129097   *p++ = 0x00;
   129098   *pp = p;
   129099   return 1;
   129100 }
   129101 
   129102 /*
   129103 ** Merge two position-lists as required by the NEAR operator. The argument
   129104 ** position lists correspond to the left and right phrases of an expression
   129105 ** like:
   129106 **
   129107 **     "phrase 1" NEAR "phrase number 2"
   129108 **
   129109 ** Position list *pp1 corresponds to the left-hand side of the NEAR
   129110 ** expression and *pp2 to the right. As usual, the indexes in the position
   129111 ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
   129112 ** in the example above).
   129113 **
   129114 ** The output position list - written to *pp - is a copy of *pp2 with those
   129115 ** entries that are not sufficiently NEAR entries in *pp1 removed.
   129116 */
   129117 static int fts3PoslistNearMerge(
   129118   char **pp,                      /* Output buffer */
   129119   char *aTmp,                     /* Temporary buffer space */
   129120   int nRight,                     /* Maximum difference in token positions */
   129121   int nLeft,                      /* Maximum difference in token positions */
   129122   char **pp1,                     /* IN/OUT: Left input list */
   129123   char **pp2                      /* IN/OUT: Right input list */
   129124 ){
   129125   char *p1 = *pp1;
   129126   char *p2 = *pp2;
   129127 
   129128   char *pTmp1 = aTmp;
   129129   char *pTmp2;
   129130   char *aTmp2;
   129131   int res = 1;
   129132 
   129133   fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
   129134   aTmp2 = pTmp2 = pTmp1;
   129135   *pp1 = p1;
   129136   *pp2 = p2;
   129137   fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
   129138   if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
   129139     fts3PoslistMerge(pp, &aTmp, &aTmp2);
   129140   }else if( pTmp1!=aTmp ){
   129141     fts3PoslistCopy(pp, &aTmp);
   129142   }else if( pTmp2!=aTmp2 ){
   129143     fts3PoslistCopy(pp, &aTmp2);
   129144   }else{
   129145     res = 0;
   129146   }
   129147 
   129148   return res;
   129149 }
   129150 
   129151 /*
   129152 ** An instance of this function is used to merge together the (potentially
   129153 ** large number of) doclists for each term that matches a prefix query.
   129154 ** See function fts3TermSelectMerge() for details.
   129155 */
   129156 typedef struct TermSelect TermSelect;
   129157 struct TermSelect {
   129158   char *aaOutput[16];             /* Malloc'd output buffers */
   129159   int anOutput[16];               /* Size each output buffer in bytes */
   129160 };
   129161 
   129162 /*
   129163 ** This function is used to read a single varint from a buffer. Parameter
   129164 ** pEnd points 1 byte past the end of the buffer. When this function is
   129165 ** called, if *pp points to pEnd or greater, then the end of the buffer
   129166 ** has been reached. In this case *pp is set to 0 and the function returns.
   129167 **
   129168 ** If *pp does not point to or past pEnd, then a single varint is read
   129169 ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
   129170 **
   129171 ** If bDescIdx is false, the value read is added to *pVal before returning.
   129172 ** If it is true, the value read is subtracted from *pVal before this
   129173 ** function returns.
   129174 */
   129175 static void fts3GetDeltaVarint3(
   129176   char **pp,                      /* IN/OUT: Point to read varint from */
   129177   char *pEnd,                     /* End of buffer */
   129178   int bDescIdx,                   /* True if docids are descending */
   129179   sqlite3_int64 *pVal             /* IN/OUT: Integer value */
   129180 ){
   129181   if( *pp>=pEnd ){
   129182     *pp = 0;
   129183   }else{
   129184     sqlite3_int64 iVal;
   129185     *pp += sqlite3Fts3GetVarint(*pp, &iVal);
   129186     if( bDescIdx ){
   129187       *pVal -= iVal;
   129188     }else{
   129189       *pVal += iVal;
   129190     }
   129191   }
   129192 }
   129193 
   129194 /*
   129195 ** This function is used to write a single varint to a buffer. The varint
   129196 ** is written to *pp. Before returning, *pp is set to point 1 byte past the
   129197 ** end of the value written.
   129198 **
   129199 ** If *pbFirst is zero when this function is called, the value written to
   129200 ** the buffer is that of parameter iVal.
   129201 **
   129202 ** If *pbFirst is non-zero when this function is called, then the value
   129203 ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
   129204 ** (if bDescIdx is non-zero).
   129205 **
   129206 ** Before returning, this function always sets *pbFirst to 1 and *piPrev
   129207 ** to the value of parameter iVal.
   129208 */
   129209 static void fts3PutDeltaVarint3(
   129210   char **pp,                      /* IN/OUT: Output pointer */
   129211   int bDescIdx,                   /* True for descending docids */
   129212   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
   129213   int *pbFirst,                   /* IN/OUT: True after first int written */
   129214   sqlite3_int64 iVal              /* Write this value to the list */
   129215 ){
   129216   sqlite3_int64 iWrite;
   129217   if( bDescIdx==0 || *pbFirst==0 ){
   129218     iWrite = iVal - *piPrev;
   129219   }else{
   129220     iWrite = *piPrev - iVal;
   129221   }
   129222   assert( *pbFirst || *piPrev==0 );
   129223   assert( *pbFirst==0 || iWrite>0 );
   129224   *pp += sqlite3Fts3PutVarint(*pp, iWrite);
   129225   *piPrev = iVal;
   129226   *pbFirst = 1;
   129227 }
   129228 
   129229 
   129230 /*
   129231 ** This macro is used by various functions that merge doclists. The two
   129232 ** arguments are 64-bit docid values. If the value of the stack variable
   129233 ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
   129234 ** Otherwise, (i2-i1).
   129235 **
   129236 ** Using this makes it easier to write code that can merge doclists that are
   129237 ** sorted in either ascending or descending order.
   129238 */
   129239 #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
   129240 
   129241 /*
   129242 ** This function does an "OR" merge of two doclists (output contains all
   129243 ** positions contained in either argument doclist). If the docids in the
   129244 ** input doclists are sorted in ascending order, parameter bDescDoclist
   129245 ** should be false. If they are sorted in ascending order, it should be
   129246 ** passed a non-zero value.
   129247 **
   129248 ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
   129249 ** containing the output doclist and SQLITE_OK is returned. In this case
   129250 ** *pnOut is set to the number of bytes in the output doclist.
   129251 **
   129252 ** If an error occurs, an SQLite error code is returned. The output values
   129253 ** are undefined in this case.
   129254 */
   129255 static int fts3DoclistOrMerge(
   129256   int bDescDoclist,               /* True if arguments are desc */
   129257   char *a1, int n1,               /* First doclist */
   129258   char *a2, int n2,               /* Second doclist */
   129259   char **paOut, int *pnOut        /* OUT: Malloc'd doclist */
   129260 ){
   129261   sqlite3_int64 i1 = 0;
   129262   sqlite3_int64 i2 = 0;
   129263   sqlite3_int64 iPrev = 0;
   129264   char *pEnd1 = &a1[n1];
   129265   char *pEnd2 = &a2[n2];
   129266   char *p1 = a1;
   129267   char *p2 = a2;
   129268   char *p;
   129269   char *aOut;
   129270   int bFirstOut = 0;
   129271 
   129272   *paOut = 0;
   129273   *pnOut = 0;
   129274 
   129275   /* Allocate space for the output. Both the input and output doclists
   129276   ** are delta encoded. If they are in ascending order (bDescDoclist==0),
   129277   ** then the first docid in each list is simply encoded as a varint. For
   129278   ** each subsequent docid, the varint stored is the difference between the
   129279   ** current and previous docid (a positive number - since the list is in
   129280   ** ascending order).
   129281   **
   129282   ** The first docid written to the output is therefore encoded using the
   129283   ** same number of bytes as it is in whichever of the input lists it is
   129284   ** read from. And each subsequent docid read from the same input list
   129285   ** consumes either the same or less bytes as it did in the input (since
   129286   ** the difference between it and the previous value in the output must
   129287   ** be a positive value less than or equal to the delta value read from
   129288   ** the input list). The same argument applies to all but the first docid
   129289   ** read from the 'other' list. And to the contents of all position lists
   129290   ** that will be copied and merged from the input to the output.
   129291   **
   129292   ** However, if the first docid copied to the output is a negative number,
   129293   ** then the encoding of the first docid from the 'other' input list may
   129294   ** be larger in the output than it was in the input (since the delta value
   129295   ** may be a larger positive integer than the actual docid).
   129296   **
   129297   ** The space required to store the output is therefore the sum of the
   129298   ** sizes of the two inputs, plus enough space for exactly one of the input
   129299   ** docids to grow.
   129300   **
   129301   ** A symetric argument may be made if the doclists are in descending
   129302   ** order.
   129303   */
   129304   aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
   129305   if( !aOut ) return SQLITE_NOMEM;
   129306 
   129307   p = aOut;
   129308   fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
   129309   fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
   129310   while( p1 || p2 ){
   129311     sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
   129312 
   129313     if( p2 && p1 && iDiff==0 ){
   129314       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
   129315       fts3PoslistMerge(&p, &p1, &p2);
   129316       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
   129317       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
   129318     }else if( !p2 || (p1 && iDiff<0) ){
   129319       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
   129320       fts3PoslistCopy(&p, &p1);
   129321       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
   129322     }else{
   129323       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
   129324       fts3PoslistCopy(&p, &p2);
   129325       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
   129326     }
   129327   }
   129328 
   129329   *paOut = aOut;
   129330   *pnOut = (int)(p-aOut);
   129331   assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
   129332   return SQLITE_OK;
   129333 }
   129334 
   129335 /*
   129336 ** This function does a "phrase" merge of two doclists. In a phrase merge,
   129337 ** the output contains a copy of each position from the right-hand input
   129338 ** doclist for which there is a position in the left-hand input doclist
   129339 ** exactly nDist tokens before it.
   129340 **
   129341 ** If the docids in the input doclists are sorted in ascending order,
   129342 ** parameter bDescDoclist should be false. If they are sorted in ascending
   129343 ** order, it should be passed a non-zero value.
   129344 **
   129345 ** The right-hand input doclist is overwritten by this function.
   129346 */
   129347 static void fts3DoclistPhraseMerge(
   129348   int bDescDoclist,               /* True if arguments are desc */
   129349   int nDist,                      /* Distance from left to right (1=adjacent) */
   129350   char *aLeft, int nLeft,         /* Left doclist */
   129351   char *aRight, int *pnRight      /* IN/OUT: Right/output doclist */
   129352 ){
   129353   sqlite3_int64 i1 = 0;
   129354   sqlite3_int64 i2 = 0;
   129355   sqlite3_int64 iPrev = 0;
   129356   char *pEnd1 = &aLeft[nLeft];
   129357   char *pEnd2 = &aRight[*pnRight];
   129358   char *p1 = aLeft;
   129359   char *p2 = aRight;
   129360   char *p;
   129361   int bFirstOut = 0;
   129362   char *aOut = aRight;
   129363 
   129364   assert( nDist>0 );
   129365 
   129366   p = aOut;
   129367   fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
   129368   fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
   129369 
   129370   while( p1 && p2 ){
   129371     sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
   129372     if( iDiff==0 ){
   129373       char *pSave = p;
   129374       sqlite3_int64 iPrevSave = iPrev;
   129375       int bFirstOutSave = bFirstOut;
   129376 
   129377       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
   129378       if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
   129379         p = pSave;
   129380         iPrev = iPrevSave;
   129381         bFirstOut = bFirstOutSave;
   129382       }
   129383       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
   129384       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
   129385     }else if( iDiff<0 ){
   129386       fts3PoslistCopy(0, &p1);
   129387       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
   129388     }else{
   129389       fts3PoslistCopy(0, &p2);
   129390       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
   129391     }
   129392   }
   129393 
   129394   *pnRight = (int)(p - aOut);
   129395 }
   129396 
   129397 /*
   129398 ** Argument pList points to a position list nList bytes in size. This
   129399 ** function checks to see if the position list contains any entries for
   129400 ** a token in position 0 (of any column). If so, it writes argument iDelta
   129401 ** to the output buffer pOut, followed by a position list consisting only
   129402 ** of the entries from pList at position 0, and terminated by an 0x00 byte.
   129403 ** The value returned is the number of bytes written to pOut (if any).
   129404 */
   129405 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
   129406   sqlite3_int64 iDelta,           /* Varint that may be written to pOut */
   129407   char *pList,                    /* Position list (no 0x00 term) */
   129408   int nList,                      /* Size of pList in bytes */
   129409   char *pOut                      /* Write output here */
   129410 ){
   129411   int nOut = 0;
   129412   int bWritten = 0;               /* True once iDelta has been written */
   129413   char *p = pList;
   129414   char *pEnd = &pList[nList];
   129415 
   129416   if( *p!=0x01 ){
   129417     if( *p==0x02 ){
   129418       nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
   129419       pOut[nOut++] = 0x02;
   129420       bWritten = 1;
   129421     }
   129422     fts3ColumnlistCopy(0, &p);
   129423   }
   129424 
   129425   while( p<pEnd && *p==0x01 ){
   129426     sqlite3_int64 iCol;
   129427     p++;
   129428     p += sqlite3Fts3GetVarint(p, &iCol);
   129429     if( *p==0x02 ){
   129430       if( bWritten==0 ){
   129431         nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
   129432         bWritten = 1;
   129433       }
   129434       pOut[nOut++] = 0x01;
   129435       nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
   129436       pOut[nOut++] = 0x02;
   129437     }
   129438     fts3ColumnlistCopy(0, &p);
   129439   }
   129440   if( bWritten ){
   129441     pOut[nOut++] = 0x00;
   129442   }
   129443 
   129444   return nOut;
   129445 }
   129446 
   129447 
   129448 /*
   129449 ** Merge all doclists in the TermSelect.aaOutput[] array into a single
   129450 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
   129451 ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
   129452 **
   129453 ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
   129454 ** the responsibility of the caller to free any doclists left in the
   129455 ** TermSelect.aaOutput[] array.
   129456 */
   129457 static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
   129458   char *aOut = 0;
   129459   int nOut = 0;
   129460   int i;
   129461 
   129462   /* Loop through the doclists in the aaOutput[] array. Merge them all
   129463   ** into a single doclist.
   129464   */
   129465   for(i=0; i<SizeofArray(pTS->aaOutput); i++){
   129466     if( pTS->aaOutput[i] ){
   129467       if( !aOut ){
   129468         aOut = pTS->aaOutput[i];
   129469         nOut = pTS->anOutput[i];
   129470         pTS->aaOutput[i] = 0;
   129471       }else{
   129472         int nNew;
   129473         char *aNew;
   129474 
   129475         int rc = fts3DoclistOrMerge(p->bDescIdx,
   129476             pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
   129477         );
   129478         if( rc!=SQLITE_OK ){
   129479           sqlite3_free(aOut);
   129480           return rc;
   129481         }
   129482 
   129483         sqlite3_free(pTS->aaOutput[i]);
   129484         sqlite3_free(aOut);
   129485         pTS->aaOutput[i] = 0;
   129486         aOut = aNew;
   129487         nOut = nNew;
   129488       }
   129489     }
   129490   }
   129491 
   129492   pTS->aaOutput[0] = aOut;
   129493   pTS->anOutput[0] = nOut;
   129494   return SQLITE_OK;
   129495 }
   129496 
   129497 /*
   129498 ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
   129499 ** as the first argument. The merge is an "OR" merge (see function
   129500 ** fts3DoclistOrMerge() for details).
   129501 **
   129502 ** This function is called with the doclist for each term that matches
   129503 ** a queried prefix. It merges all these doclists into one, the doclist
   129504 ** for the specified prefix. Since there can be a very large number of
   129505 ** doclists to merge, the merging is done pair-wise using the TermSelect
   129506 ** object.
   129507 **
   129508 ** This function returns SQLITE_OK if the merge is successful, or an
   129509 ** SQLite error code (SQLITE_NOMEM) if an error occurs.
   129510 */
   129511 static int fts3TermSelectMerge(
   129512   Fts3Table *p,                   /* FTS table handle */
   129513   TermSelect *pTS,                /* TermSelect object to merge into */
   129514   char *aDoclist,                 /* Pointer to doclist */
   129515   int nDoclist                    /* Size of aDoclist in bytes */
   129516 ){
   129517   if( pTS->aaOutput[0]==0 ){
   129518     /* If this is the first term selected, copy the doclist to the output
   129519     ** buffer using memcpy(). */
   129520     pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
   129521     pTS->anOutput[0] = nDoclist;
   129522     if( pTS->aaOutput[0] ){
   129523       memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
   129524     }else{
   129525       return SQLITE_NOMEM;
   129526     }
   129527   }else{
   129528     char *aMerge = aDoclist;
   129529     int nMerge = nDoclist;
   129530     int iOut;
   129531 
   129532     for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
   129533       if( pTS->aaOutput[iOut]==0 ){
   129534         assert( iOut>0 );
   129535         pTS->aaOutput[iOut] = aMerge;
   129536         pTS->anOutput[iOut] = nMerge;
   129537         break;
   129538       }else{
   129539         char *aNew;
   129540         int nNew;
   129541 
   129542         int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
   129543             pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
   129544         );
   129545         if( rc!=SQLITE_OK ){
   129546           if( aMerge!=aDoclist ) sqlite3_free(aMerge);
   129547           return rc;
   129548         }
   129549 
   129550         if( aMerge!=aDoclist ) sqlite3_free(aMerge);
   129551         sqlite3_free(pTS->aaOutput[iOut]);
   129552         pTS->aaOutput[iOut] = 0;
   129553 
   129554         aMerge = aNew;
   129555         nMerge = nNew;
   129556         if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
   129557           pTS->aaOutput[iOut] = aMerge;
   129558           pTS->anOutput[iOut] = nMerge;
   129559         }
   129560       }
   129561     }
   129562   }
   129563   return SQLITE_OK;
   129564 }
   129565 
   129566 /*
   129567 ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
   129568 */
   129569 static int fts3SegReaderCursorAppend(
   129570   Fts3MultiSegReader *pCsr,
   129571   Fts3SegReader *pNew
   129572 ){
   129573   if( (pCsr->nSegment%16)==0 ){
   129574     Fts3SegReader **apNew;
   129575     int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
   129576     apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
   129577     if( !apNew ){
   129578       sqlite3Fts3SegReaderFree(pNew);
   129579       return SQLITE_NOMEM;
   129580     }
   129581     pCsr->apSegment = apNew;
   129582   }
   129583   pCsr->apSegment[pCsr->nSegment++] = pNew;
   129584   return SQLITE_OK;
   129585 }
   129586 
   129587 /*
   129588 ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
   129589 ** 8th argument.
   129590 **
   129591 ** This function returns SQLITE_OK if successful, or an SQLite error code
   129592 ** otherwise.
   129593 */
   129594 static int fts3SegReaderCursor(
   129595   Fts3Table *p,                   /* FTS3 table handle */
   129596   int iLangid,                    /* Language id */
   129597   int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
   129598   int iLevel,                     /* Level of segments to scan */
   129599   const char *zTerm,              /* Term to query for */
   129600   int nTerm,                      /* Size of zTerm in bytes */
   129601   int isPrefix,                   /* True for a prefix search */
   129602   int isScan,                     /* True to scan from zTerm to EOF */
   129603   Fts3MultiSegReader *pCsr        /* Cursor object to populate */
   129604 ){
   129605   int rc = SQLITE_OK;             /* Error code */
   129606   sqlite3_stmt *pStmt = 0;        /* Statement to iterate through segments */
   129607   int rc2;                        /* Result of sqlite3_reset() */
   129608 
   129609   /* If iLevel is less than 0 and this is not a scan, include a seg-reader
   129610   ** for the pending-terms. If this is a scan, then this call must be being
   129611   ** made by an fts4aux module, not an FTS table. In this case calling
   129612   ** Fts3SegReaderPending might segfault, as the data structures used by
   129613   ** fts4aux are not completely populated. So it's easiest to filter these
   129614   ** calls out here.  */
   129615   if( iLevel<0 && p->aIndex ){
   129616     Fts3SegReader *pSeg = 0;
   129617     rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix, &pSeg);
   129618     if( rc==SQLITE_OK && pSeg ){
   129619       rc = fts3SegReaderCursorAppend(pCsr, pSeg);
   129620     }
   129621   }
   129622 
   129623   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
   129624     if( rc==SQLITE_OK ){
   129625       rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
   129626     }
   129627 
   129628     while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
   129629       Fts3SegReader *pSeg = 0;
   129630 
   129631       /* Read the values returned by the SELECT into local variables. */
   129632       sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
   129633       sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
   129634       sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
   129635       int nRoot = sqlite3_column_bytes(pStmt, 4);
   129636       char const *zRoot = sqlite3_column_blob(pStmt, 4);
   129637 
   129638       /* If zTerm is not NULL, and this segment is not stored entirely on its
   129639       ** root node, the range of leaves scanned can be reduced. Do this. */
   129640       if( iStartBlock && zTerm ){
   129641         sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
   129642         rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
   129643         if( rc!=SQLITE_OK ) goto finished;
   129644         if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
   129645       }
   129646 
   129647       rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
   129648           (isPrefix==0 && isScan==0),
   129649           iStartBlock, iLeavesEndBlock,
   129650           iEndBlock, zRoot, nRoot, &pSeg
   129651       );
   129652       if( rc!=SQLITE_OK ) goto finished;
   129653       rc = fts3SegReaderCursorAppend(pCsr, pSeg);
   129654     }
   129655   }
   129656 
   129657  finished:
   129658   rc2 = sqlite3_reset(pStmt);
   129659   if( rc==SQLITE_DONE ) rc = rc2;
   129660 
   129661   return rc;
   129662 }
   129663 
   129664 /*
   129665 ** Set up a cursor object for iterating through a full-text index or a
   129666 ** single level therein.
   129667 */
   129668 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
   129669   Fts3Table *p,                   /* FTS3 table handle */
   129670   int iLangid,                    /* Language-id to search */
   129671   int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
   129672   int iLevel,                     /* Level of segments to scan */
   129673   const char *zTerm,              /* Term to query for */
   129674   int nTerm,                      /* Size of zTerm in bytes */
   129675   int isPrefix,                   /* True for a prefix search */
   129676   int isScan,                     /* True to scan from zTerm to EOF */
   129677   Fts3MultiSegReader *pCsr       /* Cursor object to populate */
   129678 ){
   129679   assert( iIndex>=0 && iIndex<p->nIndex );
   129680   assert( iLevel==FTS3_SEGCURSOR_ALL
   129681       ||  iLevel==FTS3_SEGCURSOR_PENDING
   129682       ||  iLevel>=0
   129683   );
   129684   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
   129685   assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
   129686   assert( isPrefix==0 || isScan==0 );
   129687 
   129688   memset(pCsr, 0, sizeof(Fts3MultiSegReader));
   129689   return fts3SegReaderCursor(
   129690       p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
   129691   );
   129692 }
   129693 
   129694 /*
   129695 ** In addition to its current configuration, have the Fts3MultiSegReader
   129696 ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
   129697 **
   129698 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
   129699 */
   129700 static int fts3SegReaderCursorAddZero(
   129701   Fts3Table *p,                   /* FTS virtual table handle */
   129702   int iLangid,
   129703   const char *zTerm,              /* Term to scan doclist of */
   129704   int nTerm,                      /* Number of bytes in zTerm */
   129705   Fts3MultiSegReader *pCsr        /* Fts3MultiSegReader to modify */
   129706 ){
   129707   return fts3SegReaderCursor(p,
   129708       iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
   129709   );
   129710 }
   129711 
   129712 /*
   129713 ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
   129714 ** if isPrefix is true, to scan the doclist for all terms for which
   129715 ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
   129716 ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
   129717 ** an SQLite error code.
   129718 **
   129719 ** It is the responsibility of the caller to free this object by eventually
   129720 ** passing it to fts3SegReaderCursorFree()
   129721 **
   129722 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
   129723 ** Output parameter *ppSegcsr is set to 0 if an error occurs.
   129724 */
   129725 static int fts3TermSegReaderCursor(
   129726   Fts3Cursor *pCsr,               /* Virtual table cursor handle */
   129727   const char *zTerm,              /* Term to query for */
   129728   int nTerm,                      /* Size of zTerm in bytes */
   129729   int isPrefix,                   /* True for a prefix search */
   129730   Fts3MultiSegReader **ppSegcsr   /* OUT: Allocated seg-reader cursor */
   129731 ){
   129732   Fts3MultiSegReader *pSegcsr;    /* Object to allocate and return */
   129733   int rc = SQLITE_NOMEM;          /* Return code */
   129734 
   129735   pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
   129736   if( pSegcsr ){
   129737     int i;
   129738     int bFound = 0;               /* True once an index has been found */
   129739     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
   129740 
   129741     if( isPrefix ){
   129742       for(i=1; bFound==0 && i<p->nIndex; i++){
   129743         if( p->aIndex[i].nPrefix==nTerm ){
   129744           bFound = 1;
   129745           rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
   129746               i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
   129747           );
   129748           pSegcsr->bLookup = 1;
   129749         }
   129750       }
   129751 
   129752       for(i=1; bFound==0 && i<p->nIndex; i++){
   129753         if( p->aIndex[i].nPrefix==nTerm+1 ){
   129754           bFound = 1;
   129755           rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
   129756               i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
   129757           );
   129758           if( rc==SQLITE_OK ){
   129759             rc = fts3SegReaderCursorAddZero(
   129760                 p, pCsr->iLangid, zTerm, nTerm, pSegcsr
   129761             );
   129762           }
   129763         }
   129764       }
   129765     }
   129766 
   129767     if( bFound==0 ){
   129768       rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
   129769           0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
   129770       );
   129771       pSegcsr->bLookup = !isPrefix;
   129772     }
   129773   }
   129774 
   129775   *ppSegcsr = pSegcsr;
   129776   return rc;
   129777 }
   129778 
   129779 /*
   129780 ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
   129781 */
   129782 static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
   129783   sqlite3Fts3SegReaderFinish(pSegcsr);
   129784   sqlite3_free(pSegcsr);
   129785 }
   129786 
   129787 /*
   129788 ** This function retrieves the doclist for the specified term (or term
   129789 ** prefix) from the database.
   129790 */
   129791 static int fts3TermSelect(
   129792   Fts3Table *p,                   /* Virtual table handle */
   129793   Fts3PhraseToken *pTok,          /* Token to query for */
   129794   int iColumn,                    /* Column to query (or -ve for all columns) */
   129795   int *pnOut,                     /* OUT: Size of buffer at *ppOut */
   129796   char **ppOut                    /* OUT: Malloced result buffer */
   129797 ){
   129798   int rc;                         /* Return code */
   129799   Fts3MultiSegReader *pSegcsr;    /* Seg-reader cursor for this term */
   129800   TermSelect tsc;                 /* Object for pair-wise doclist merging */
   129801   Fts3SegFilter filter;           /* Segment term filter configuration */
   129802 
   129803   pSegcsr = pTok->pSegcsr;
   129804   memset(&tsc, 0, sizeof(TermSelect));
   129805 
   129806   filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
   129807         | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
   129808         | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
   129809         | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
   129810   filter.iCol = iColumn;
   129811   filter.zTerm = pTok->z;
   129812   filter.nTerm = pTok->n;
   129813 
   129814   rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
   129815   while( SQLITE_OK==rc
   129816       && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
   129817   ){
   129818     rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
   129819   }
   129820 
   129821   if( rc==SQLITE_OK ){
   129822     rc = fts3TermSelectFinishMerge(p, &tsc);
   129823   }
   129824   if( rc==SQLITE_OK ){
   129825     *ppOut = tsc.aaOutput[0];
   129826     *pnOut = tsc.anOutput[0];
   129827   }else{
   129828     int i;
   129829     for(i=0; i<SizeofArray(tsc.aaOutput); i++){
   129830       sqlite3_free(tsc.aaOutput[i]);
   129831     }
   129832   }
   129833 
   129834   fts3SegReaderCursorFree(pSegcsr);
   129835   pTok->pSegcsr = 0;
   129836   return rc;
   129837 }
   129838 
   129839 /*
   129840 ** This function counts the total number of docids in the doclist stored
   129841 ** in buffer aList[], size nList bytes.
   129842 **
   129843 ** If the isPoslist argument is true, then it is assumed that the doclist
   129844 ** contains a position-list following each docid. Otherwise, it is assumed
   129845 ** that the doclist is simply a list of docids stored as delta encoded
   129846 ** varints.
   129847 */
   129848 static int fts3DoclistCountDocids(char *aList, int nList){
   129849   int nDoc = 0;                   /* Return value */
   129850   if( aList ){
   129851     char *aEnd = &aList[nList];   /* Pointer to one byte after EOF */
   129852     char *p = aList;              /* Cursor */
   129853     while( p<aEnd ){
   129854       nDoc++;
   129855       while( (*p++)&0x80 );     /* Skip docid varint */
   129856       fts3PoslistCopy(0, &p);   /* Skip over position list */
   129857     }
   129858   }
   129859 
   129860   return nDoc;
   129861 }
   129862 
   129863 /*
   129864 ** Advance the cursor to the next row in the %_content table that
   129865 ** matches the search criteria.  For a MATCH search, this will be
   129866 ** the next row that matches. For a full-table scan, this will be
   129867 ** simply the next row in the %_content table.  For a docid lookup,
   129868 ** this routine simply sets the EOF flag.
   129869 **
   129870 ** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
   129871 ** even if we reach end-of-file.  The fts3EofMethod() will be called
   129872 ** subsequently to determine whether or not an EOF was hit.
   129873 */
   129874 static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
   129875   int rc;
   129876   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
   129877   if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
   129878     if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
   129879       pCsr->isEof = 1;
   129880       rc = sqlite3_reset(pCsr->pStmt);
   129881     }else{
   129882       pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
   129883       rc = SQLITE_OK;
   129884     }
   129885   }else{
   129886     rc = fts3EvalNext((Fts3Cursor *)pCursor);
   129887   }
   129888   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
   129889   return rc;
   129890 }
   129891 
   129892 /*
   129893 ** The following are copied from sqliteInt.h.
   129894 **
   129895 ** Constants for the largest and smallest possible 64-bit signed integers.
   129896 ** These macros are designed to work correctly on both 32-bit and 64-bit
   129897 ** compilers.
   129898 */
   129899 #ifndef SQLITE_AMALGAMATION
   129900 # define LARGEST_INT64  (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
   129901 # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
   129902 #endif
   129903 
   129904 /*
   129905 ** If the numeric type of argument pVal is "integer", then return it
   129906 ** converted to a 64-bit signed integer. Otherwise, return a copy of
   129907 ** the second parameter, iDefault.
   129908 */
   129909 static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
   129910   if( pVal ){
   129911     int eType = sqlite3_value_numeric_type(pVal);
   129912     if( eType==SQLITE_INTEGER ){
   129913       return sqlite3_value_int64(pVal);
   129914     }
   129915   }
   129916   return iDefault;
   129917 }
   129918 
   129919 /*
   129920 ** This is the xFilter interface for the virtual table.  See
   129921 ** the virtual table xFilter method documentation for additional
   129922 ** information.
   129923 **
   129924 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
   129925 ** the %_content table.
   129926 **
   129927 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
   129928 ** in the %_content table.
   129929 **
   129930 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
   129931 ** column on the left-hand side of the MATCH operator is column
   129932 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
   129933 ** side of the MATCH operator.
   129934 */
   129935 static int fts3FilterMethod(
   129936   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
   129937   int idxNum,                     /* Strategy index */
   129938   const char *idxStr,             /* Unused */
   129939   int nVal,                       /* Number of elements in apVal */
   129940   sqlite3_value **apVal           /* Arguments for the indexing scheme */
   129941 ){
   129942   int rc;
   129943   char *zSql;                     /* SQL statement used to access %_content */
   129944   int eSearch;
   129945   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
   129946   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
   129947 
   129948   sqlite3_value *pCons = 0;       /* The MATCH or rowid constraint, if any */
   129949   sqlite3_value *pLangid = 0;     /* The "langid = ?" constraint, if any */
   129950   sqlite3_value *pDocidGe = 0;    /* The "docid >= ?" constraint, if any */
   129951   sqlite3_value *pDocidLe = 0;    /* The "docid <= ?" constraint, if any */
   129952   int iIdx;
   129953 
   129954   UNUSED_PARAMETER(idxStr);
   129955   UNUSED_PARAMETER(nVal);
   129956 
   129957   eSearch = (idxNum & 0x0000FFFF);
   129958   assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
   129959   assert( p->pSegments==0 );
   129960 
   129961   /* Collect arguments into local variables */
   129962   iIdx = 0;
   129963   if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
   129964   if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
   129965   if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
   129966   if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
   129967   assert( iIdx==nVal );
   129968 
   129969   /* In case the cursor has been used before, clear it now. */
   129970   sqlite3_finalize(pCsr->pStmt);
   129971   sqlite3_free(pCsr->aDoclist);
   129972   sqlite3Fts3ExprFree(pCsr->pExpr);
   129973   memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
   129974 
   129975   /* Set the lower and upper bounds on docids to return */
   129976   pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
   129977   pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
   129978 
   129979   if( idxStr ){
   129980     pCsr->bDesc = (idxStr[0]=='D');
   129981   }else{
   129982     pCsr->bDesc = p->bDescIdx;
   129983   }
   129984   pCsr->eSearch = (i16)eSearch;
   129985 
   129986   if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
   129987     int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
   129988     const char *zQuery = (const char *)sqlite3_value_text(pCons);
   129989 
   129990     if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
   129991       return SQLITE_NOMEM;
   129992     }
   129993 
   129994     pCsr->iLangid = 0;
   129995     if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
   129996 
   129997     assert( p->base.zErrMsg==0 );
   129998     rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
   129999         p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
   130000         &p->base.zErrMsg
   130001     );
   130002     if( rc!=SQLITE_OK ){
   130003       return rc;
   130004     }
   130005 
   130006     rc = fts3EvalStart(pCsr);
   130007     sqlite3Fts3SegmentsClose(p);
   130008     if( rc!=SQLITE_OK ) return rc;
   130009     pCsr->pNextId = pCsr->aDoclist;
   130010     pCsr->iPrevId = 0;
   130011   }
   130012 
   130013   /* Compile a SELECT statement for this cursor. For a full-table-scan, the
   130014   ** statement loops through all rows of the %_content table. For a
   130015   ** full-text query or docid lookup, the statement retrieves a single
   130016   ** row by docid.
   130017   */
   130018   if( eSearch==FTS3_FULLSCAN_SEARCH ){
   130019     zSql = sqlite3_mprintf(
   130020         "SELECT %s ORDER BY rowid %s",
   130021         p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
   130022     );
   130023     if( zSql ){
   130024       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
   130025       sqlite3_free(zSql);
   130026     }else{
   130027       rc = SQLITE_NOMEM;
   130028     }
   130029   }else if( eSearch==FTS3_DOCID_SEARCH ){
   130030     rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
   130031     if( rc==SQLITE_OK ){
   130032       rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
   130033     }
   130034   }
   130035   if( rc!=SQLITE_OK ) return rc;
   130036 
   130037   return fts3NextMethod(pCursor);
   130038 }
   130039 
   130040 /*
   130041 ** This is the xEof method of the virtual table. SQLite calls this
   130042 ** routine to find out if it has reached the end of a result set.
   130043 */
   130044 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
   130045   return ((Fts3Cursor *)pCursor)->isEof;
   130046 }
   130047 
   130048 /*
   130049 ** This is the xRowid method. The SQLite core calls this routine to
   130050 ** retrieve the rowid for the current row of the result set. fts3
   130051 ** exposes %_content.docid as the rowid for the virtual table. The
   130052 ** rowid should be written to *pRowid.
   130053 */
   130054 static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
   130055   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
   130056   *pRowid = pCsr->iPrevId;
   130057   return SQLITE_OK;
   130058 }
   130059 
   130060 /*
   130061 ** This is the xColumn method, called by SQLite to request a value from
   130062 ** the row that the supplied cursor currently points to.
   130063 **
   130064 ** If:
   130065 **
   130066 **   (iCol <  p->nColumn)   -> The value of the iCol'th user column.
   130067 **   (iCol == p->nColumn)   -> Magic column with the same name as the table.
   130068 **   (iCol == p->nColumn+1) -> Docid column
   130069 **   (iCol == p->nColumn+2) -> Langid column
   130070 */
   130071 static int fts3ColumnMethod(
   130072   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
   130073   sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
   130074   int iCol                        /* Index of column to read value from */
   130075 ){
   130076   int rc = SQLITE_OK;             /* Return Code */
   130077   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
   130078   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
   130079 
   130080   /* The column value supplied by SQLite must be in range. */
   130081   assert( iCol>=0 && iCol<=p->nColumn+2 );
   130082 
   130083   if( iCol==p->nColumn+1 ){
   130084     /* This call is a request for the "docid" column. Since "docid" is an
   130085     ** alias for "rowid", use the xRowid() method to obtain the value.
   130086     */
   130087     sqlite3_result_int64(pCtx, pCsr->iPrevId);
   130088   }else if( iCol==p->nColumn ){
   130089     /* The extra column whose name is the same as the table.
   130090     ** Return a blob which is a pointer to the cursor.  */
   130091     sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
   130092   }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
   130093     sqlite3_result_int64(pCtx, pCsr->iLangid);
   130094   }else{
   130095     /* The requested column is either a user column (one that contains
   130096     ** indexed data), or the language-id column.  */
   130097     rc = fts3CursorSeek(0, pCsr);
   130098 
   130099     if( rc==SQLITE_OK ){
   130100       if( iCol==p->nColumn+2 ){
   130101         int iLangid = 0;
   130102         if( p->zLanguageid ){
   130103           iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
   130104         }
   130105         sqlite3_result_int(pCtx, iLangid);
   130106       }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
   130107         sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
   130108       }
   130109     }
   130110   }
   130111 
   130112   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
   130113   return rc;
   130114 }
   130115 
   130116 /*
   130117 ** This function is the implementation of the xUpdate callback used by
   130118 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
   130119 ** inserted, updated or deleted.
   130120 */
   130121 static int fts3UpdateMethod(
   130122   sqlite3_vtab *pVtab,            /* Virtual table handle */
   130123   int nArg,                       /* Size of argument array */
   130124   sqlite3_value **apVal,          /* Array of arguments */
   130125   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
   130126 ){
   130127   return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
   130128 }
   130129 
   130130 /*
   130131 ** Implementation of xSync() method. Flush the contents of the pending-terms
   130132 ** hash-table to the database.
   130133 */
   130134 static int fts3SyncMethod(sqlite3_vtab *pVtab){
   130135 
   130136   /* Following an incremental-merge operation, assuming that the input
   130137   ** segments are not completely consumed (the usual case), they are updated
   130138   ** in place to remove the entries that have already been merged. This
   130139   ** involves updating the leaf block that contains the smallest unmerged
   130140   ** entry and each block (if any) between the leaf and the root node. So
   130141   ** if the height of the input segment b-trees is N, and input segments
   130142   ** are merged eight at a time, updating the input segments at the end
   130143   ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
   130144   ** small - often between 0 and 2. So the overhead of the incremental
   130145   ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
   130146   ** dwarfing the actual productive work accomplished, the incremental merge
   130147   ** is only attempted if it will write at least 64 leaf blocks. Hence
   130148   ** nMinMerge.
   130149   **
   130150   ** Of course, updating the input segments also involves deleting a bunch
   130151   ** of blocks from the segments table. But this is not considered overhead
   130152   ** as it would also be required by a crisis-merge that used the same input
   130153   ** segments.
   130154   */
   130155   const u32 nMinMerge = 64;       /* Minimum amount of incr-merge work to do */
   130156 
   130157   Fts3Table *p = (Fts3Table*)pVtab;
   130158   int rc = sqlite3Fts3PendingTermsFlush(p);
   130159 
   130160   if( rc==SQLITE_OK
   130161    && p->nLeafAdd>(nMinMerge/16)
   130162    && p->nAutoincrmerge && p->nAutoincrmerge!=0xff
   130163   ){
   130164     int mxLevel = 0;              /* Maximum relative level value in db */
   130165     int A;                        /* Incr-merge parameter A */
   130166 
   130167     rc = sqlite3Fts3MaxLevel(p, &mxLevel);
   130168     assert( rc==SQLITE_OK || mxLevel==0 );
   130169     A = p->nLeafAdd * mxLevel;
   130170     A += (A/2);
   130171     if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge);
   130172   }
   130173   sqlite3Fts3SegmentsClose(p);
   130174   return rc;
   130175 }
   130176 
   130177 /*
   130178 ** If it is currently unknown whether or not the FTS table has an %_stat
   130179 ** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
   130180 ** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
   130181 ** if an error occurs.
   130182 */
   130183 static int fts3SetHasStat(Fts3Table *p){
   130184   int rc = SQLITE_OK;
   130185   if( p->bHasStat==2 ){
   130186     const char *zFmt ="SELECT 1 FROM %Q.sqlite_master WHERE tbl_name='%q_stat'";
   130187     char *zSql = sqlite3_mprintf(zFmt, p->zDb, p->zName);
   130188     if( zSql ){
   130189       sqlite3_stmt *pStmt = 0;
   130190       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
   130191       if( rc==SQLITE_OK ){
   130192         int bHasStat = (sqlite3_step(pStmt)==SQLITE_ROW);
   130193         rc = sqlite3_finalize(pStmt);
   130194         if( rc==SQLITE_OK ) p->bHasStat = bHasStat;
   130195       }
   130196       sqlite3_free(zSql);
   130197     }else{
   130198       rc = SQLITE_NOMEM;
   130199     }
   130200   }
   130201   return rc;
   130202 }
   130203 
   130204 /*
   130205 ** Implementation of xBegin() method.
   130206 */
   130207 static int fts3BeginMethod(sqlite3_vtab *pVtab){
   130208   Fts3Table *p = (Fts3Table*)pVtab;
   130209   UNUSED_PARAMETER(pVtab);
   130210   assert( p->pSegments==0 );
   130211   assert( p->nPendingData==0 );
   130212   assert( p->inTransaction!=1 );
   130213   TESTONLY( p->inTransaction = 1 );
   130214   TESTONLY( p->mxSavepoint = -1; );
   130215   p->nLeafAdd = 0;
   130216   return fts3SetHasStat(p);
   130217 }
   130218 
   130219 /*
   130220 ** Implementation of xCommit() method. This is a no-op. The contents of
   130221 ** the pending-terms hash-table have already been flushed into the database
   130222 ** by fts3SyncMethod().
   130223 */
   130224 static int fts3CommitMethod(sqlite3_vtab *pVtab){
   130225   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
   130226   UNUSED_PARAMETER(pVtab);
   130227   assert( p->nPendingData==0 );
   130228   assert( p->inTransaction!=0 );
   130229   assert( p->pSegments==0 );
   130230   TESTONLY( p->inTransaction = 0 );
   130231   TESTONLY( p->mxSavepoint = -1; );
   130232   return SQLITE_OK;
   130233 }
   130234 
   130235 /*
   130236 ** Implementation of xRollback(). Discard the contents of the pending-terms
   130237 ** hash-table. Any changes made to the database are reverted by SQLite.
   130238 */
   130239 static int fts3RollbackMethod(sqlite3_vtab *pVtab){
   130240   Fts3Table *p = (Fts3Table*)pVtab;
   130241   sqlite3Fts3PendingTermsClear(p);
   130242   assert( p->inTransaction!=0 );
   130243   TESTONLY( p->inTransaction = 0 );
   130244   TESTONLY( p->mxSavepoint = -1; );
   130245   return SQLITE_OK;
   130246 }
   130247 
   130248 /*
   130249 ** When called, *ppPoslist must point to the byte immediately following the
   130250 ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
   130251 ** moves *ppPoslist so that it instead points to the first byte of the
   130252 ** same position list.
   130253 */
   130254 static void fts3ReversePoslist(char *pStart, char **ppPoslist){
   130255   char *p = &(*ppPoslist)[-2];
   130256   char c = 0;
   130257 
   130258   while( p>pStart && (c=*p--)==0 );
   130259   while( p>pStart && (*p & 0x80) | c ){
   130260     c = *p--;
   130261   }
   130262   if( p>pStart ){ p = &p[2]; }
   130263   while( *p++&0x80 );
   130264   *ppPoslist = p;
   130265 }
   130266 
   130267 /*
   130268 ** Helper function used by the implementation of the overloaded snippet(),
   130269 ** offsets() and optimize() SQL functions.
   130270 **
   130271 ** If the value passed as the third argument is a blob of size
   130272 ** sizeof(Fts3Cursor*), then the blob contents are copied to the
   130273 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
   130274 ** message is written to context pContext and SQLITE_ERROR returned. The
   130275 ** string passed via zFunc is used as part of the error message.
   130276 */
   130277 static int fts3FunctionArg(
   130278   sqlite3_context *pContext,      /* SQL function call context */
   130279   const char *zFunc,              /* Function name */
   130280   sqlite3_value *pVal,            /* argv[0] passed to function */
   130281   Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */
   130282 ){
   130283   Fts3Cursor *pRet;
   130284   if( sqlite3_value_type(pVal)!=SQLITE_BLOB
   130285    || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
   130286   ){
   130287     char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
   130288     sqlite3_result_error(pContext, zErr, -1);
   130289     sqlite3_free(zErr);
   130290     return SQLITE_ERROR;
   130291   }
   130292   memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
   130293   *ppCsr = pRet;
   130294   return SQLITE_OK;
   130295 }
   130296 
   130297 /*
   130298 ** Implementation of the snippet() function for FTS3
   130299 */
   130300 static void fts3SnippetFunc(
   130301   sqlite3_context *pContext,      /* SQLite function call context */
   130302   int nVal,                       /* Size of apVal[] array */
   130303   sqlite3_value **apVal           /* Array of arguments */
   130304 ){
   130305   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
   130306   const char *zStart = "<b>";
   130307   const char *zEnd = "</b>";
   130308   const char *zEllipsis = "<b>...</b>";
   130309   int iCol = -1;
   130310   int nToken = 15;                /* Default number of tokens in snippet */
   130311 
   130312   /* There must be at least one argument passed to this function (otherwise
   130313   ** the non-overloaded version would have been called instead of this one).
   130314   */
   130315   assert( nVal>=1 );
   130316 
   130317   if( nVal>6 ){
   130318     sqlite3_result_error(pContext,
   130319         "wrong number of arguments to function snippet()", -1);
   130320     return;
   130321   }
   130322   if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
   130323 
   130324   switch( nVal ){
   130325     case 6: nToken = sqlite3_value_int(apVal[5]);
   130326     case 5: iCol = sqlite3_value_int(apVal[4]);
   130327     case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
   130328     case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
   130329     case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
   130330   }
   130331   if( !zEllipsis || !zEnd || !zStart ){
   130332     sqlite3_result_error_nomem(pContext);
   130333   }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
   130334     sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
   130335   }
   130336 }
   130337 
   130338 /*
   130339 ** Implementation of the offsets() function for FTS3
   130340 */
   130341 static void fts3OffsetsFunc(
   130342   sqlite3_context *pContext,      /* SQLite function call context */
   130343   int nVal,                       /* Size of argument array */
   130344   sqlite3_value **apVal           /* Array of arguments */
   130345 ){
   130346   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
   130347 
   130348   UNUSED_PARAMETER(nVal);
   130349 
   130350   assert( nVal==1 );
   130351   if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
   130352   assert( pCsr );
   130353   if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
   130354     sqlite3Fts3Offsets(pContext, pCsr);
   130355   }
   130356 }
   130357 
   130358 /*
   130359 ** Implementation of the special optimize() function for FTS3. This
   130360 ** function merges all segments in the database to a single segment.
   130361 ** Example usage is:
   130362 **
   130363 **   SELECT optimize(t) FROM t LIMIT 1;
   130364 **
   130365 ** where 't' is the name of an FTS3 table.
   130366 */
   130367 static void fts3OptimizeFunc(
   130368   sqlite3_context *pContext,      /* SQLite function call context */
   130369   int nVal,                       /* Size of argument array */
   130370   sqlite3_value **apVal           /* Array of arguments */
   130371 ){
   130372   int rc;                         /* Return code */
   130373   Fts3Table *p;                   /* Virtual table handle */
   130374   Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
   130375 
   130376   UNUSED_PARAMETER(nVal);
   130377 
   130378   assert( nVal==1 );
   130379   if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
   130380   p = (Fts3Table *)pCursor->base.pVtab;
   130381   assert( p );
   130382 
   130383   rc = sqlite3Fts3Optimize(p);
   130384 
   130385   switch( rc ){
   130386     case SQLITE_OK:
   130387       sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
   130388       break;
   130389     case SQLITE_DONE:
   130390       sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
   130391       break;
   130392     default:
   130393       sqlite3_result_error_code(pContext, rc);
   130394       break;
   130395   }
   130396 }
   130397 
   130398 /*
   130399 ** Implementation of the matchinfo() function for FTS3
   130400 */
   130401 static void fts3MatchinfoFunc(
   130402   sqlite3_context *pContext,      /* SQLite function call context */
   130403   int nVal,                       /* Size of argument array */
   130404   sqlite3_value **apVal           /* Array of arguments */
   130405 ){
   130406   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
   130407   assert( nVal==1 || nVal==2 );
   130408   if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
   130409     const char *zArg = 0;
   130410     if( nVal>1 ){
   130411       zArg = (const char *)sqlite3_value_text(apVal[1]);
   130412     }
   130413     sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
   130414   }
   130415 }
   130416 
   130417 /*
   130418 ** This routine implements the xFindFunction method for the FTS3
   130419 ** virtual table.
   130420 */
   130421 static int fts3FindFunctionMethod(
   130422   sqlite3_vtab *pVtab,            /* Virtual table handle */
   130423   int nArg,                       /* Number of SQL function arguments */
   130424   const char *zName,              /* Name of SQL function */
   130425   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
   130426   void **ppArg                    /* Unused */
   130427 ){
   130428   struct Overloaded {
   130429     const char *zName;
   130430     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
   130431   } aOverload[] = {
   130432     { "snippet", fts3SnippetFunc },
   130433     { "offsets", fts3OffsetsFunc },
   130434     { "optimize", fts3OptimizeFunc },
   130435     { "matchinfo", fts3MatchinfoFunc },
   130436   };
   130437   int i;                          /* Iterator variable */
   130438 
   130439   UNUSED_PARAMETER(pVtab);
   130440   UNUSED_PARAMETER(nArg);
   130441   UNUSED_PARAMETER(ppArg);
   130442 
   130443   for(i=0; i<SizeofArray(aOverload); i++){
   130444     if( strcmp(zName, aOverload[i].zName)==0 ){
   130445       *pxFunc = aOverload[i].xFunc;
   130446       return 1;
   130447     }
   130448   }
   130449 
   130450   /* No function of the specified name was found. Return 0. */
   130451   return 0;
   130452 }
   130453 
   130454 /*
   130455 ** Implementation of FTS3 xRename method. Rename an fts3 table.
   130456 */
   130457 static int fts3RenameMethod(
   130458   sqlite3_vtab *pVtab,            /* Virtual table handle */
   130459   const char *zName               /* New name of table */
   130460 ){
   130461   Fts3Table *p = (Fts3Table *)pVtab;
   130462   sqlite3 *db = p->db;            /* Database connection */
   130463   int rc;                         /* Return Code */
   130464 
   130465   /* At this point it must be known if the %_stat table exists or not.
   130466   ** So bHasStat may not be 2.  */
   130467   rc = fts3SetHasStat(p);
   130468 
   130469   /* As it happens, the pending terms table is always empty here. This is
   130470   ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
   130471   ** always opens a savepoint transaction. And the xSavepoint() method
   130472   ** flushes the pending terms table. But leave the (no-op) call to
   130473   ** PendingTermsFlush() in in case that changes.
   130474   */
   130475   assert( p->nPendingData==0 );
   130476   if( rc==SQLITE_OK ){
   130477     rc = sqlite3Fts3PendingTermsFlush(p);
   130478   }
   130479 
   130480   if( p->zContentTbl==0 ){
   130481     fts3DbExec(&rc, db,
   130482       "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
   130483       p->zDb, p->zName, zName
   130484     );
   130485   }
   130486 
   130487   if( p->bHasDocsize ){
   130488     fts3DbExec(&rc, db,
   130489       "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
   130490       p->zDb, p->zName, zName
   130491     );
   130492   }
   130493   if( p->bHasStat ){
   130494     fts3DbExec(&rc, db,
   130495       "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
   130496       p->zDb, p->zName, zName
   130497     );
   130498   }
   130499   fts3DbExec(&rc, db,
   130500     "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
   130501     p->zDb, p->zName, zName
   130502   );
   130503   fts3DbExec(&rc, db,
   130504     "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
   130505     p->zDb, p->zName, zName
   130506   );
   130507   return rc;
   130508 }
   130509 
   130510 /*
   130511 ** The xSavepoint() method.
   130512 **
   130513 ** Flush the contents of the pending-terms table to disk.
   130514 */
   130515 static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
   130516   int rc = SQLITE_OK;
   130517   UNUSED_PARAMETER(iSavepoint);
   130518   assert( ((Fts3Table *)pVtab)->inTransaction );
   130519   assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
   130520   TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
   130521   if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
   130522     rc = fts3SyncMethod(pVtab);
   130523   }
   130524   return rc;
   130525 }
   130526 
   130527 /*
   130528 ** The xRelease() method.
   130529 **
   130530 ** This is a no-op.
   130531 */
   130532 static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
   130533   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
   130534   UNUSED_PARAMETER(iSavepoint);
   130535   UNUSED_PARAMETER(pVtab);
   130536   assert( p->inTransaction );
   130537   assert( p->mxSavepoint >= iSavepoint );
   130538   TESTONLY( p->mxSavepoint = iSavepoint-1 );
   130539   return SQLITE_OK;
   130540 }
   130541 
   130542 /*
   130543 ** The xRollbackTo() method.
   130544 **
   130545 ** Discard the contents of the pending terms table.
   130546 */
   130547 static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
   130548   Fts3Table *p = (Fts3Table*)pVtab;
   130549   UNUSED_PARAMETER(iSavepoint);
   130550   assert( p->inTransaction );
   130551   assert( p->mxSavepoint >= iSavepoint );
   130552   TESTONLY( p->mxSavepoint = iSavepoint );
   130553   sqlite3Fts3PendingTermsClear(p);
   130554   return SQLITE_OK;
   130555 }
   130556 
   130557 static const sqlite3_module fts3Module = {
   130558   /* iVersion      */ 2,
   130559   /* xCreate       */ fts3CreateMethod,
   130560   /* xConnect      */ fts3ConnectMethod,
   130561   /* xBestIndex    */ fts3BestIndexMethod,
   130562   /* xDisconnect   */ fts3DisconnectMethod,
   130563   /* xDestroy      */ fts3DestroyMethod,
   130564   /* xOpen         */ fts3OpenMethod,
   130565   /* xClose        */ fts3CloseMethod,
   130566   /* xFilter       */ fts3FilterMethod,
   130567   /* xNext         */ fts3NextMethod,
   130568   /* xEof          */ fts3EofMethod,
   130569   /* xColumn       */ fts3ColumnMethod,
   130570   /* xRowid        */ fts3RowidMethod,
   130571   /* xUpdate       */ fts3UpdateMethod,
   130572   /* xBegin        */ fts3BeginMethod,
   130573   /* xSync         */ fts3SyncMethod,
   130574   /* xCommit       */ fts3CommitMethod,
   130575   /* xRollback     */ fts3RollbackMethod,
   130576   /* xFindFunction */ fts3FindFunctionMethod,
   130577   /* xRename */       fts3RenameMethod,
   130578   /* xSavepoint    */ fts3SavepointMethod,
   130579   /* xRelease      */ fts3ReleaseMethod,
   130580   /* xRollbackTo   */ fts3RollbackToMethod,
   130581 };
   130582 
   130583 /*
   130584 ** This function is registered as the module destructor (called when an
   130585 ** FTS3 enabled database connection is closed). It frees the memory
   130586 ** allocated for the tokenizer hash table.
   130587 */
   130588 static void hashDestroy(void *p){
   130589   Fts3Hash *pHash = (Fts3Hash *)p;
   130590   sqlite3Fts3HashClear(pHash);
   130591   sqlite3_free(pHash);
   130592 }
   130593 
   130594 /*
   130595 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
   130596 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
   130597 ** respectively. The following three forward declarations are for functions
   130598 ** declared in these files used to retrieve the respective implementations.
   130599 **
   130600 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
   130601 ** to by the argument to point to the "simple" tokenizer implementation.
   130602 ** And so on.
   130603 */
   130604 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
   130605 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
   130606 #ifndef SQLITE_DISABLE_FTS3_UNICODE
   130607 SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
   130608 #endif
   130609 #ifdef SQLITE_ENABLE_ICU
   130610 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
   130611 #endif
   130612 
   130613 /*
   130614 ** Initialize the fts3 extension. If this extension is built as part
   130615 ** of the sqlite library, then this function is called directly by
   130616 ** SQLite. If fts3 is built as a dynamically loadable extension, this
   130617 ** function is called by the sqlite3_extension_init() entry point.
   130618 */
   130619 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
   130620   int rc = SQLITE_OK;
   130621   Fts3Hash *pHash = 0;
   130622   const sqlite3_tokenizer_module *pSimple = 0;
   130623   const sqlite3_tokenizer_module *pPorter = 0;
   130624 #ifndef SQLITE_DISABLE_FTS3_UNICODE
   130625   const sqlite3_tokenizer_module *pUnicode = 0;
   130626 #endif
   130627 
   130628 #ifdef SQLITE_ENABLE_ICU
   130629   const sqlite3_tokenizer_module *pIcu = 0;
   130630   sqlite3Fts3IcuTokenizerModule(&pIcu);
   130631 #endif
   130632 
   130633 #ifndef SQLITE_DISABLE_FTS3_UNICODE
   130634   sqlite3Fts3UnicodeTokenizer(&pUnicode);
   130635 #endif
   130636 
   130637 #ifdef SQLITE_TEST
   130638   rc = sqlite3Fts3InitTerm(db);
   130639   if( rc!=SQLITE_OK ) return rc;
   130640 #endif
   130641 
   130642   rc = sqlite3Fts3InitAux(db);
   130643   if( rc!=SQLITE_OK ) return rc;
   130644 
   130645   sqlite3Fts3SimpleTokenizerModule(&pSimple);
   130646   sqlite3Fts3PorterTokenizerModule(&pPorter);
   130647 
   130648   /* Allocate and initialize the hash-table used to store tokenizers. */
   130649   pHash = sqlite3_malloc(sizeof(Fts3Hash));
   130650   if( !pHash ){
   130651     rc = SQLITE_NOMEM;
   130652   }else{
   130653     sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
   130654   }
   130655 
   130656   /* Load the built-in tokenizers into the hash table */
   130657   if( rc==SQLITE_OK ){
   130658     if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
   130659      || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
   130660 
   130661 #ifndef SQLITE_DISABLE_FTS3_UNICODE
   130662      || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
   130663 #endif
   130664 #ifdef SQLITE_ENABLE_ICU
   130665      || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
   130666 #endif
   130667     ){
   130668       rc = SQLITE_NOMEM;
   130669     }
   130670   }
   130671 
   130672 #ifdef SQLITE_TEST
   130673   if( rc==SQLITE_OK ){
   130674     rc = sqlite3Fts3ExprInitTestInterface(db);
   130675   }
   130676 #endif
   130677 
   130678   /* Create the virtual table wrapper around the hash-table and overload
   130679   ** the two scalar functions. If this is successful, register the
   130680   ** module with sqlite.
   130681   */
   130682   if( SQLITE_OK==rc
   130683 #ifndef ANDROID    /* fts3_tokenizer disabled for security reasons */
   130684    && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
   130685 #endif
   130686    && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
   130687    && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
   130688    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
   130689    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
   130690    && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
   130691   ){
   130692 #ifdef SQLITE_ENABLE_FTS3_BACKWARDS
   130693     rc = sqlite3_create_module_v2(
   130694         db, "fts1", &fts3Module, (void *)pHash, 0
   130695         );
   130696     if(rc) return rc;
   130697     rc = sqlite3_create_module_v2(
   130698         db, "fts2", &fts3Module, (void *)pHash, 0
   130699         );
   130700     if(rc) return rc;
   130701 #endif
   130702     rc = sqlite3_create_module_v2(
   130703         db, "fts3", &fts3Module, (void *)pHash, hashDestroy
   130704         );
   130705     if( rc==SQLITE_OK ){
   130706       rc = sqlite3_create_module_v2(
   130707           db, "fts4", &fts3Module, (void *)pHash, 0
   130708       );
   130709     }
   130710     if( rc==SQLITE_OK ){
   130711       rc = sqlite3Fts3InitTok(db, (void *)pHash);
   130712     }
   130713     return rc;
   130714   }
   130715 
   130716 
   130717   /* An error has occurred. Delete the hash table and return the error code. */
   130718   assert( rc!=SQLITE_OK );
   130719   if( pHash ){
   130720     sqlite3Fts3HashClear(pHash);
   130721     sqlite3_free(pHash);
   130722   }
   130723   return rc;
   130724 }
   130725 
   130726 /*
   130727 ** Allocate an Fts3MultiSegReader for each token in the expression headed
   130728 ** by pExpr.
   130729 **
   130730 ** An Fts3SegReader object is a cursor that can seek or scan a range of
   130731 ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
   130732 ** Fts3SegReader objects internally to provide an interface to seek or scan
   130733 ** within the union of all segments of a b-tree. Hence the name.
   130734 **
   130735 ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
   130736 ** segment b-tree (if the term is not a prefix or it is a prefix for which
   130737 ** there exists prefix b-tree of the right length) then it may be traversed
   130738 ** and merged incrementally. Otherwise, it has to be merged into an in-memory
   130739 ** doclist and then traversed.
   130740 */
   130741 static void fts3EvalAllocateReaders(
   130742   Fts3Cursor *pCsr,               /* FTS cursor handle */
   130743   Fts3Expr *pExpr,                /* Allocate readers for this expression */
   130744   int *pnToken,                   /* OUT: Total number of tokens in phrase. */
   130745   int *pnOr,                      /* OUT: Total number of OR nodes in expr. */
   130746   int *pRc                        /* IN/OUT: Error code */
   130747 ){
   130748   if( pExpr && SQLITE_OK==*pRc ){
   130749     if( pExpr->eType==FTSQUERY_PHRASE ){
   130750       int i;
   130751       int nToken = pExpr->pPhrase->nToken;
   130752       *pnToken += nToken;
   130753       for(i=0; i<nToken; i++){
   130754         Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
   130755         int rc = fts3TermSegReaderCursor(pCsr,
   130756             pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
   130757         );
   130758         if( rc!=SQLITE_OK ){
   130759           *pRc = rc;
   130760           return;
   130761         }
   130762       }
   130763       assert( pExpr->pPhrase->iDoclistToken==0 );
   130764       pExpr->pPhrase->iDoclistToken = -1;
   130765     }else{
   130766       *pnOr += (pExpr->eType==FTSQUERY_OR);
   130767       fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
   130768       fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
   130769     }
   130770   }
   130771 }
   130772 
   130773 /*
   130774 ** Arguments pList/nList contain the doclist for token iToken of phrase p.
   130775 ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
   130776 **
   130777 ** This function assumes that pList points to a buffer allocated using
   130778 ** sqlite3_malloc(). This function takes responsibility for eventually
   130779 ** freeing the buffer.
   130780 */
   130781 static void fts3EvalPhraseMergeToken(
   130782   Fts3Table *pTab,                /* FTS Table pointer */
   130783   Fts3Phrase *p,                  /* Phrase to merge pList/nList into */
   130784   int iToken,                     /* Token pList/nList corresponds to */
   130785   char *pList,                    /* Pointer to doclist */
   130786   int nList                       /* Number of bytes in pList */
   130787 ){
   130788   assert( iToken!=p->iDoclistToken );
   130789 
   130790   if( pList==0 ){
   130791     sqlite3_free(p->doclist.aAll);
   130792     p->doclist.aAll = 0;
   130793     p->doclist.nAll = 0;
   130794   }
   130795 
   130796   else if( p->iDoclistToken<0 ){
   130797     p->doclist.aAll = pList;
   130798     p->doclist.nAll = nList;
   130799   }
   130800 
   130801   else if( p->doclist.aAll==0 ){
   130802     sqlite3_free(pList);
   130803   }
   130804 
   130805   else {
   130806     char *pLeft;
   130807     char *pRight;
   130808     int nLeft;
   130809     int nRight;
   130810     int nDiff;
   130811 
   130812     if( p->iDoclistToken<iToken ){
   130813       pLeft = p->doclist.aAll;
   130814       nLeft = p->doclist.nAll;
   130815       pRight = pList;
   130816       nRight = nList;
   130817       nDiff = iToken - p->iDoclistToken;
   130818     }else{
   130819       pRight = p->doclist.aAll;
   130820       nRight = p->doclist.nAll;
   130821       pLeft = pList;
   130822       nLeft = nList;
   130823       nDiff = p->iDoclistToken - iToken;
   130824     }
   130825 
   130826     fts3DoclistPhraseMerge(pTab->bDescIdx, nDiff, pLeft, nLeft, pRight,&nRight);
   130827     sqlite3_free(pLeft);
   130828     p->doclist.aAll = pRight;
   130829     p->doclist.nAll = nRight;
   130830   }
   130831 
   130832   if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
   130833 }
   130834 
   130835 /*
   130836 ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
   130837 ** does not take deferred tokens into account.
   130838 **
   130839 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
   130840 */
   130841 static int fts3EvalPhraseLoad(
   130842   Fts3Cursor *pCsr,               /* FTS Cursor handle */
   130843   Fts3Phrase *p                   /* Phrase object */
   130844 ){
   130845   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   130846   int iToken;
   130847   int rc = SQLITE_OK;
   130848 
   130849   for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
   130850     Fts3PhraseToken *pToken = &p->aToken[iToken];
   130851     assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
   130852 
   130853     if( pToken->pSegcsr ){
   130854       int nThis = 0;
   130855       char *pThis = 0;
   130856       rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
   130857       if( rc==SQLITE_OK ){
   130858         fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
   130859       }
   130860     }
   130861     assert( pToken->pSegcsr==0 );
   130862   }
   130863 
   130864   return rc;
   130865 }
   130866 
   130867 /*
   130868 ** This function is called on each phrase after the position lists for
   130869 ** any deferred tokens have been loaded into memory. It updates the phrases
   130870 ** current position list to include only those positions that are really
   130871 ** instances of the phrase (after considering deferred tokens). If this
   130872 ** means that the phrase does not appear in the current row, doclist.pList
   130873 ** and doclist.nList are both zeroed.
   130874 **
   130875 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
   130876 */
   130877 static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
   130878   int iToken;                     /* Used to iterate through phrase tokens */
   130879   char *aPoslist = 0;             /* Position list for deferred tokens */
   130880   int nPoslist = 0;               /* Number of bytes in aPoslist */
   130881   int iPrev = -1;                 /* Token number of previous deferred token */
   130882 
   130883   assert( pPhrase->doclist.bFreeList==0 );
   130884 
   130885   for(iToken=0; iToken<pPhrase->nToken; iToken++){
   130886     Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
   130887     Fts3DeferredToken *pDeferred = pToken->pDeferred;
   130888 
   130889     if( pDeferred ){
   130890       char *pList;
   130891       int nList;
   130892       int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
   130893       if( rc!=SQLITE_OK ) return rc;
   130894 
   130895       if( pList==0 ){
   130896         sqlite3_free(aPoslist);
   130897         pPhrase->doclist.pList = 0;
   130898         pPhrase->doclist.nList = 0;
   130899         return SQLITE_OK;
   130900 
   130901       }else if( aPoslist==0 ){
   130902         aPoslist = pList;
   130903         nPoslist = nList;
   130904 
   130905       }else{
   130906         char *aOut = pList;
   130907         char *p1 = aPoslist;
   130908         char *p2 = aOut;
   130909 
   130910         assert( iPrev>=0 );
   130911         fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
   130912         sqlite3_free(aPoslist);
   130913         aPoslist = pList;
   130914         nPoslist = (int)(aOut - aPoslist);
   130915         if( nPoslist==0 ){
   130916           sqlite3_free(aPoslist);
   130917           pPhrase->doclist.pList = 0;
   130918           pPhrase->doclist.nList = 0;
   130919           return SQLITE_OK;
   130920         }
   130921       }
   130922       iPrev = iToken;
   130923     }
   130924   }
   130925 
   130926   if( iPrev>=0 ){
   130927     int nMaxUndeferred = pPhrase->iDoclistToken;
   130928     if( nMaxUndeferred<0 ){
   130929       pPhrase->doclist.pList = aPoslist;
   130930       pPhrase->doclist.nList = nPoslist;
   130931       pPhrase->doclist.iDocid = pCsr->iPrevId;
   130932       pPhrase->doclist.bFreeList = 1;
   130933     }else{
   130934       int nDistance;
   130935       char *p1;
   130936       char *p2;
   130937       char *aOut;
   130938 
   130939       if( nMaxUndeferred>iPrev ){
   130940         p1 = aPoslist;
   130941         p2 = pPhrase->doclist.pList;
   130942         nDistance = nMaxUndeferred - iPrev;
   130943       }else{
   130944         p1 = pPhrase->doclist.pList;
   130945         p2 = aPoslist;
   130946         nDistance = iPrev - nMaxUndeferred;
   130947       }
   130948 
   130949       aOut = (char *)sqlite3_malloc(nPoslist+8);
   130950       if( !aOut ){
   130951         sqlite3_free(aPoslist);
   130952         return SQLITE_NOMEM;
   130953       }
   130954 
   130955       pPhrase->doclist.pList = aOut;
   130956       if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
   130957         pPhrase->doclist.bFreeList = 1;
   130958         pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
   130959       }else{
   130960         sqlite3_free(aOut);
   130961         pPhrase->doclist.pList = 0;
   130962         pPhrase->doclist.nList = 0;
   130963       }
   130964       sqlite3_free(aPoslist);
   130965     }
   130966   }
   130967 
   130968   return SQLITE_OK;
   130969 }
   130970 
   130971 /*
   130972 ** Maximum number of tokens a phrase may have to be considered for the
   130973 ** incremental doclists strategy.
   130974 */
   130975 #define MAX_INCR_PHRASE_TOKENS 4
   130976 
   130977 /*
   130978 ** This function is called for each Fts3Phrase in a full-text query
   130979 ** expression to initialize the mechanism for returning rows. Once this
   130980 ** function has been called successfully on an Fts3Phrase, it may be
   130981 ** used with fts3EvalPhraseNext() to iterate through the matching docids.
   130982 **
   130983 ** If parameter bOptOk is true, then the phrase may (or may not) use the
   130984 ** incremental loading strategy. Otherwise, the entire doclist is loaded into
   130985 ** memory within this call.
   130986 **
   130987 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
   130988 */
   130989 static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
   130990   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   130991   int rc = SQLITE_OK;             /* Error code */
   130992   int i;
   130993 
   130994   /* Determine if doclists may be loaded from disk incrementally. This is
   130995   ** possible if the bOptOk argument is true, the FTS doclists will be
   130996   ** scanned in forward order, and the phrase consists of
   130997   ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
   130998   ** tokens or prefix tokens that cannot use a prefix-index.  */
   130999   int bHaveIncr = 0;
   131000   int bIncrOk = (bOptOk
   131001    && pCsr->bDesc==pTab->bDescIdx
   131002    && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
   131003    && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
   131004 #ifdef SQLITE_TEST
   131005    && pTab->bNoIncrDoclist==0
   131006 #endif
   131007   );
   131008   for(i=0; bIncrOk==1 && i<p->nToken; i++){
   131009     Fts3PhraseToken *pToken = &p->aToken[i];
   131010     if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
   131011       bIncrOk = 0;
   131012     }
   131013     if( pToken->pSegcsr ) bHaveIncr = 1;
   131014   }
   131015 
   131016   if( bIncrOk && bHaveIncr ){
   131017     /* Use the incremental approach. */
   131018     int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
   131019     for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
   131020       Fts3PhraseToken *pToken = &p->aToken[i];
   131021       Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
   131022       if( pSegcsr ){
   131023         rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
   131024       }
   131025     }
   131026     p->bIncr = 1;
   131027   }else{
   131028     /* Load the full doclist for the phrase into memory. */
   131029     rc = fts3EvalPhraseLoad(pCsr, p);
   131030     p->bIncr = 0;
   131031   }
   131032 
   131033   assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
   131034   return rc;
   131035 }
   131036 
   131037 /*
   131038 ** This function is used to iterate backwards (from the end to start)
   131039 ** through doclists. It is used by this module to iterate through phrase
   131040 ** doclists in reverse and by the fts3_write.c module to iterate through
   131041 ** pending-terms lists when writing to databases with "order=desc".
   131042 **
   131043 ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
   131044 ** descending (parameter bDescIdx==1) order of docid. Regardless, this
   131045 ** function iterates from the end of the doclist to the beginning.
   131046 */
   131047 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
   131048   int bDescIdx,                   /* True if the doclist is desc */
   131049   char *aDoclist,                 /* Pointer to entire doclist */
   131050   int nDoclist,                   /* Length of aDoclist in bytes */
   131051   char **ppIter,                  /* IN/OUT: Iterator pointer */
   131052   sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
   131053   int *pnList,                    /* OUT: List length pointer */
   131054   u8 *pbEof                       /* OUT: End-of-file flag */
   131055 ){
   131056   char *p = *ppIter;
   131057 
   131058   assert( nDoclist>0 );
   131059   assert( *pbEof==0 );
   131060   assert( p || *piDocid==0 );
   131061   assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
   131062 
   131063   if( p==0 ){
   131064     sqlite3_int64 iDocid = 0;
   131065     char *pNext = 0;
   131066     char *pDocid = aDoclist;
   131067     char *pEnd = &aDoclist[nDoclist];
   131068     int iMul = 1;
   131069 
   131070     while( pDocid<pEnd ){
   131071       sqlite3_int64 iDelta;
   131072       pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
   131073       iDocid += (iMul * iDelta);
   131074       pNext = pDocid;
   131075       fts3PoslistCopy(0, &pDocid);
   131076       while( pDocid<pEnd && *pDocid==0 ) pDocid++;
   131077       iMul = (bDescIdx ? -1 : 1);
   131078     }
   131079 
   131080     *pnList = (int)(pEnd - pNext);
   131081     *ppIter = pNext;
   131082     *piDocid = iDocid;
   131083   }else{
   131084     int iMul = (bDescIdx ? -1 : 1);
   131085     sqlite3_int64 iDelta;
   131086     fts3GetReverseVarint(&p, aDoclist, &iDelta);
   131087     *piDocid -= (iMul * iDelta);
   131088 
   131089     if( p==aDoclist ){
   131090       *pbEof = 1;
   131091     }else{
   131092       char *pSave = p;
   131093       fts3ReversePoslist(aDoclist, &p);
   131094       *pnList = (int)(pSave - p);
   131095     }
   131096     *ppIter = p;
   131097   }
   131098 }
   131099 
   131100 /*
   131101 ** Iterate forwards through a doclist.
   131102 */
   131103 SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
   131104   int bDescIdx,                   /* True if the doclist is desc */
   131105   char *aDoclist,                 /* Pointer to entire doclist */
   131106   int nDoclist,                   /* Length of aDoclist in bytes */
   131107   char **ppIter,                  /* IN/OUT: Iterator pointer */
   131108   sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
   131109   u8 *pbEof                       /* OUT: End-of-file flag */
   131110 ){
   131111   char *p = *ppIter;
   131112 
   131113   assert( nDoclist>0 );
   131114   assert( *pbEof==0 );
   131115   assert( p || *piDocid==0 );
   131116   assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
   131117 
   131118   if( p==0 ){
   131119     p = aDoclist;
   131120     p += sqlite3Fts3GetVarint(p, piDocid);
   131121   }else{
   131122     fts3PoslistCopy(0, &p);
   131123     if( p>=&aDoclist[nDoclist] ){
   131124       *pbEof = 1;
   131125     }else{
   131126       sqlite3_int64 iVar;
   131127       p += sqlite3Fts3GetVarint(p, &iVar);
   131128       *piDocid += ((bDescIdx ? -1 : 1) * iVar);
   131129     }
   131130   }
   131131 
   131132   *ppIter = p;
   131133 }
   131134 
   131135 /*
   131136 ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
   131137 ** to true if EOF is reached.
   131138 */
   131139 static void fts3EvalDlPhraseNext(
   131140   Fts3Table *pTab,
   131141   Fts3Doclist *pDL,
   131142   u8 *pbEof
   131143 ){
   131144   char *pIter;                            /* Used to iterate through aAll */
   131145   char *pEnd = &pDL->aAll[pDL->nAll];     /* 1 byte past end of aAll */
   131146 
   131147   if( pDL->pNextDocid ){
   131148     pIter = pDL->pNextDocid;
   131149   }else{
   131150     pIter = pDL->aAll;
   131151   }
   131152 
   131153   if( pIter>=pEnd ){
   131154     /* We have already reached the end of this doclist. EOF. */
   131155     *pbEof = 1;
   131156   }else{
   131157     sqlite3_int64 iDelta;
   131158     pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
   131159     if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
   131160       pDL->iDocid += iDelta;
   131161     }else{
   131162       pDL->iDocid -= iDelta;
   131163     }
   131164     pDL->pList = pIter;
   131165     fts3PoslistCopy(0, &pIter);
   131166     pDL->nList = (int)(pIter - pDL->pList);
   131167 
   131168     /* pIter now points just past the 0x00 that terminates the position-
   131169     ** list for document pDL->iDocid. However, if this position-list was
   131170     ** edited in place by fts3EvalNearTrim(), then pIter may not actually
   131171     ** point to the start of the next docid value. The following line deals
   131172     ** with this case by advancing pIter past the zero-padding added by
   131173     ** fts3EvalNearTrim().  */
   131174     while( pIter<pEnd && *pIter==0 ) pIter++;
   131175 
   131176     pDL->pNextDocid = pIter;
   131177     assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
   131178     *pbEof = 0;
   131179   }
   131180 }
   131181 
   131182 /*
   131183 ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
   131184 */
   131185 typedef struct TokenDoclist TokenDoclist;
   131186 struct TokenDoclist {
   131187   int bIgnore;
   131188   sqlite3_int64 iDocid;
   131189   char *pList;
   131190   int nList;
   131191 };
   131192 
   131193 /*
   131194 ** Token pToken is an incrementally loaded token that is part of a
   131195 ** multi-token phrase. Advance it to the next matching document in the
   131196 ** database and populate output variable *p with the details of the new
   131197 ** entry. Or, if the iterator has reached EOF, set *pbEof to true.
   131198 **
   131199 ** If an error occurs, return an SQLite error code. Otherwise, return
   131200 ** SQLITE_OK.
   131201 */
   131202 static int incrPhraseTokenNext(
   131203   Fts3Table *pTab,                /* Virtual table handle */
   131204   Fts3Phrase *pPhrase,            /* Phrase to advance token of */
   131205   int iToken,                     /* Specific token to advance */
   131206   TokenDoclist *p,                /* OUT: Docid and doclist for new entry */
   131207   u8 *pbEof                       /* OUT: True if iterator is at EOF */
   131208 ){
   131209   int rc = SQLITE_OK;
   131210 
   131211   if( pPhrase->iDoclistToken==iToken ){
   131212     assert( p->bIgnore==0 );
   131213     assert( pPhrase->aToken[iToken].pSegcsr==0 );
   131214     fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
   131215     p->pList = pPhrase->doclist.pList;
   131216     p->nList = pPhrase->doclist.nList;
   131217     p->iDocid = pPhrase->doclist.iDocid;
   131218   }else{
   131219     Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
   131220     assert( pToken->pDeferred==0 );
   131221     assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
   131222     if( pToken->pSegcsr ){
   131223       assert( p->bIgnore==0 );
   131224       rc = sqlite3Fts3MsrIncrNext(
   131225           pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
   131226       );
   131227       if( p->pList==0 ) *pbEof = 1;
   131228     }else{
   131229       p->bIgnore = 1;
   131230     }
   131231   }
   131232 
   131233   return rc;
   131234 }
   131235 
   131236 
   131237 /*
   131238 ** The phrase iterator passed as the second argument:
   131239 **
   131240 **   * features at least one token that uses an incremental doclist, and
   131241 **
   131242 **   * does not contain any deferred tokens.
   131243 **
   131244 ** Advance it to the next matching documnent in the database and populate
   131245 ** the Fts3Doclist.pList and nList fields.
   131246 **
   131247 ** If there is no "next" entry and no error occurs, then *pbEof is set to
   131248 ** 1 before returning. Otherwise, if no error occurs and the iterator is
   131249 ** successfully advanced, *pbEof is set to 0.
   131250 **
   131251 ** If an error occurs, return an SQLite error code. Otherwise, return
   131252 ** SQLITE_OK.
   131253 */
   131254 static int fts3EvalIncrPhraseNext(
   131255   Fts3Cursor *pCsr,               /* FTS Cursor handle */
   131256   Fts3Phrase *p,                  /* Phrase object to advance to next docid */
   131257   u8 *pbEof                       /* OUT: Set to 1 if EOF */
   131258 ){
   131259   int rc = SQLITE_OK;
   131260   Fts3Doclist *pDL = &p->doclist;
   131261   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   131262   u8 bEof = 0;
   131263 
   131264   /* This is only called if it is guaranteed that the phrase has at least
   131265   ** one incremental token. In which case the bIncr flag is set. */
   131266   assert( p->bIncr==1 );
   131267 
   131268   if( p->nToken==1 && p->bIncr ){
   131269     rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
   131270         &pDL->iDocid, &pDL->pList, &pDL->nList
   131271     );
   131272     if( pDL->pList==0 ) bEof = 1;
   131273   }else{
   131274     int bDescDoclist = pCsr->bDesc;
   131275     struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
   131276 
   131277     memset(a, 0, sizeof(a));
   131278     assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
   131279     assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
   131280 
   131281     while( bEof==0 ){
   131282       int bMaxSet = 0;
   131283       sqlite3_int64 iMax = 0;     /* Largest docid for all iterators */
   131284       int i;                      /* Used to iterate through tokens */
   131285 
   131286       /* Advance the iterator for each token in the phrase once. */
   131287       for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
   131288         rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
   131289         if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
   131290           iMax = a[i].iDocid;
   131291           bMaxSet = 1;
   131292         }
   131293       }
   131294       assert( rc!=SQLITE_OK || a[p->nToken-1].bIgnore==0 );
   131295       assert( rc!=SQLITE_OK || bMaxSet );
   131296 
   131297       /* Keep advancing iterators until they all point to the same document */
   131298       for(i=0; i<p->nToken; i++){
   131299         while( rc==SQLITE_OK && bEof==0
   131300             && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
   131301         ){
   131302           rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
   131303           if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
   131304             iMax = a[i].iDocid;
   131305             i = 0;
   131306           }
   131307         }
   131308       }
   131309 
   131310       /* Check if the current entries really are a phrase match */
   131311       if( bEof==0 ){
   131312         int nList = 0;
   131313         int nByte = a[p->nToken-1].nList;
   131314         char *aDoclist = sqlite3_malloc(nByte+1);
   131315         if( !aDoclist ) return SQLITE_NOMEM;
   131316         memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
   131317 
   131318         for(i=0; i<(p->nToken-1); i++){
   131319           if( a[i].bIgnore==0 ){
   131320             char *pL = a[i].pList;
   131321             char *pR = aDoclist;
   131322             char *pOut = aDoclist;
   131323             int nDist = p->nToken-1-i;
   131324             int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
   131325             if( res==0 ) break;
   131326             nList = (int)(pOut - aDoclist);
   131327           }
   131328         }
   131329         if( i==(p->nToken-1) ){
   131330           pDL->iDocid = iMax;
   131331           pDL->pList = aDoclist;
   131332           pDL->nList = nList;
   131333           pDL->bFreeList = 1;
   131334           break;
   131335         }
   131336         sqlite3_free(aDoclist);
   131337       }
   131338     }
   131339   }
   131340 
   131341   *pbEof = bEof;
   131342   return rc;
   131343 }
   131344 
   131345 /*
   131346 ** Attempt to move the phrase iterator to point to the next matching docid.
   131347 ** If an error occurs, return an SQLite error code. Otherwise, return
   131348 ** SQLITE_OK.
   131349 **
   131350 ** If there is no "next" entry and no error occurs, then *pbEof is set to
   131351 ** 1 before returning. Otherwise, if no error occurs and the iterator is
   131352 ** successfully advanced, *pbEof is set to 0.
   131353 */
   131354 static int fts3EvalPhraseNext(
   131355   Fts3Cursor *pCsr,               /* FTS Cursor handle */
   131356   Fts3Phrase *p,                  /* Phrase object to advance to next docid */
   131357   u8 *pbEof                       /* OUT: Set to 1 if EOF */
   131358 ){
   131359   int rc = SQLITE_OK;
   131360   Fts3Doclist *pDL = &p->doclist;
   131361   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   131362 
   131363   if( p->bIncr ){
   131364     rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
   131365   }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
   131366     sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
   131367         &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
   131368     );
   131369     pDL->pList = pDL->pNextDocid;
   131370   }else{
   131371     fts3EvalDlPhraseNext(pTab, pDL, pbEof);
   131372   }
   131373 
   131374   return rc;
   131375 }
   131376 
   131377 /*
   131378 **
   131379 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
   131380 ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
   131381 ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
   131382 ** expressions for which all descendent tokens are deferred.
   131383 **
   131384 ** If parameter bOptOk is zero, then it is guaranteed that the
   131385 ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
   131386 ** each phrase in the expression (subject to deferred token processing).
   131387 ** Or, if bOptOk is non-zero, then one or more tokens within the expression
   131388 ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
   131389 **
   131390 ** If an error occurs within this function, *pRc is set to an SQLite error
   131391 ** code before returning.
   131392 */
   131393 static void fts3EvalStartReaders(
   131394   Fts3Cursor *pCsr,               /* FTS Cursor handle */
   131395   Fts3Expr *pExpr,                /* Expression to initialize phrases in */
   131396   int *pRc                        /* IN/OUT: Error code */
   131397 ){
   131398   if( pExpr && SQLITE_OK==*pRc ){
   131399     if( pExpr->eType==FTSQUERY_PHRASE ){
   131400       int i;
   131401       int nToken = pExpr->pPhrase->nToken;
   131402       for(i=0; i<nToken; i++){
   131403         if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
   131404       }
   131405       pExpr->bDeferred = (i==nToken);
   131406       *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
   131407     }else{
   131408       fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
   131409       fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
   131410       pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
   131411     }
   131412   }
   131413 }
   131414 
   131415 /*
   131416 ** An array of the following structures is assembled as part of the process
   131417 ** of selecting tokens to defer before the query starts executing (as part
   131418 ** of the xFilter() method). There is one element in the array for each
   131419 ** token in the FTS expression.
   131420 **
   131421 ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
   131422 ** to phrases that are connected only by AND and NEAR operators (not OR or
   131423 ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
   131424 ** separately. The root of a tokens AND/NEAR cluster is stored in
   131425 ** Fts3TokenAndCost.pRoot.
   131426 */
   131427 typedef struct Fts3TokenAndCost Fts3TokenAndCost;
   131428 struct Fts3TokenAndCost {
   131429   Fts3Phrase *pPhrase;            /* The phrase the token belongs to */
   131430   int iToken;                     /* Position of token in phrase */
   131431   Fts3PhraseToken *pToken;        /* The token itself */
   131432   Fts3Expr *pRoot;                /* Root of NEAR/AND cluster */
   131433   int nOvfl;                      /* Number of overflow pages to load doclist */
   131434   int iCol;                       /* The column the token must match */
   131435 };
   131436 
   131437 /*
   131438 ** This function is used to populate an allocated Fts3TokenAndCost array.
   131439 **
   131440 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
   131441 ** Otherwise, if an error occurs during execution, *pRc is set to an
   131442 ** SQLite error code.
   131443 */
   131444 static void fts3EvalTokenCosts(
   131445   Fts3Cursor *pCsr,               /* FTS Cursor handle */
   131446   Fts3Expr *pRoot,                /* Root of current AND/NEAR cluster */
   131447   Fts3Expr *pExpr,                /* Expression to consider */
   131448   Fts3TokenAndCost **ppTC,        /* Write new entries to *(*ppTC)++ */
   131449   Fts3Expr ***ppOr,               /* Write new OR root to *(*ppOr)++ */
   131450   int *pRc                        /* IN/OUT: Error code */
   131451 ){
   131452   if( *pRc==SQLITE_OK ){
   131453     if( pExpr->eType==FTSQUERY_PHRASE ){
   131454       Fts3Phrase *pPhrase = pExpr->pPhrase;
   131455       int i;
   131456       for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
   131457         Fts3TokenAndCost *pTC = (*ppTC)++;
   131458         pTC->pPhrase = pPhrase;
   131459         pTC->iToken = i;
   131460         pTC->pRoot = pRoot;
   131461         pTC->pToken = &pPhrase->aToken[i];
   131462         pTC->iCol = pPhrase->iColumn;
   131463         *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
   131464       }
   131465     }else if( pExpr->eType!=FTSQUERY_NOT ){
   131466       assert( pExpr->eType==FTSQUERY_OR
   131467            || pExpr->eType==FTSQUERY_AND
   131468            || pExpr->eType==FTSQUERY_NEAR
   131469       );
   131470       assert( pExpr->pLeft && pExpr->pRight );
   131471       if( pExpr->eType==FTSQUERY_OR ){
   131472         pRoot = pExpr->pLeft;
   131473         **ppOr = pRoot;
   131474         (*ppOr)++;
   131475       }
   131476       fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
   131477       if( pExpr->eType==FTSQUERY_OR ){
   131478         pRoot = pExpr->pRight;
   131479         **ppOr = pRoot;
   131480         (*ppOr)++;
   131481       }
   131482       fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
   131483     }
   131484   }
   131485 }
   131486 
   131487 /*
   131488 ** Determine the average document (row) size in pages. If successful,
   131489 ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
   131490 ** an SQLite error code.
   131491 **
   131492 ** The average document size in pages is calculated by first calculating
   131493 ** determining the average size in bytes, B. If B is less than the amount
   131494 ** of data that will fit on a single leaf page of an intkey table in
   131495 ** this database, then the average docsize is 1. Otherwise, it is 1 plus
   131496 ** the number of overflow pages consumed by a record B bytes in size.
   131497 */
   131498 static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
   131499   if( pCsr->nRowAvg==0 ){
   131500     /* The average document size, which is required to calculate the cost
   131501     ** of each doclist, has not yet been determined. Read the required
   131502     ** data from the %_stat table to calculate it.
   131503     **
   131504     ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
   131505     ** varints, where nCol is the number of columns in the FTS3 table.
   131506     ** The first varint is the number of documents currently stored in
   131507     ** the table. The following nCol varints contain the total amount of
   131508     ** data stored in all rows of each column of the table, from left
   131509     ** to right.
   131510     */
   131511     int rc;
   131512     Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
   131513     sqlite3_stmt *pStmt;
   131514     sqlite3_int64 nDoc = 0;
   131515     sqlite3_int64 nByte = 0;
   131516     const char *pEnd;
   131517     const char *a;
   131518 
   131519     rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
   131520     if( rc!=SQLITE_OK ) return rc;
   131521     a = sqlite3_column_blob(pStmt, 0);
   131522     assert( a );
   131523 
   131524     pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
   131525     a += sqlite3Fts3GetVarint(a, &nDoc);
   131526     while( a<pEnd ){
   131527       a += sqlite3Fts3GetVarint(a, &nByte);
   131528     }
   131529     if( nDoc==0 || nByte==0 ){
   131530       sqlite3_reset(pStmt);
   131531       return FTS_CORRUPT_VTAB;
   131532     }
   131533 
   131534     pCsr->nDoc = nDoc;
   131535     pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
   131536     assert( pCsr->nRowAvg>0 );
   131537     rc = sqlite3_reset(pStmt);
   131538     if( rc!=SQLITE_OK ) return rc;
   131539   }
   131540 
   131541   *pnPage = pCsr->nRowAvg;
   131542   return SQLITE_OK;
   131543 }
   131544 
   131545 /*
   131546 ** This function is called to select the tokens (if any) that will be
   131547 ** deferred. The array aTC[] has already been populated when this is
   131548 ** called.
   131549 **
   131550 ** This function is called once for each AND/NEAR cluster in the
   131551 ** expression. Each invocation determines which tokens to defer within
   131552 ** the cluster with root node pRoot. See comments above the definition
   131553 ** of struct Fts3TokenAndCost for more details.
   131554 **
   131555 ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
   131556 ** called on each token to defer. Otherwise, an SQLite error code is
   131557 ** returned.
   131558 */
   131559 static int fts3EvalSelectDeferred(
   131560   Fts3Cursor *pCsr,               /* FTS Cursor handle */
   131561   Fts3Expr *pRoot,                /* Consider tokens with this root node */
   131562   Fts3TokenAndCost *aTC,          /* Array of expression tokens and costs */
   131563   int nTC                         /* Number of entries in aTC[] */
   131564 ){
   131565   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   131566   int nDocSize = 0;               /* Number of pages per doc loaded */
   131567   int rc = SQLITE_OK;             /* Return code */
   131568   int ii;                         /* Iterator variable for various purposes */
   131569   int nOvfl = 0;                  /* Total overflow pages used by doclists */
   131570   int nToken = 0;                 /* Total number of tokens in cluster */
   131571 
   131572   int nMinEst = 0;                /* The minimum count for any phrase so far. */
   131573   int nLoad4 = 1;                 /* (Phrases that will be loaded)^4. */
   131574 
   131575   /* Tokens are never deferred for FTS tables created using the content=xxx
   131576   ** option. The reason being that it is not guaranteed that the content
   131577   ** table actually contains the same data as the index. To prevent this from
   131578   ** causing any problems, the deferred token optimization is completely
   131579   ** disabled for content=xxx tables. */
   131580   if( pTab->zContentTbl ){
   131581     return SQLITE_OK;
   131582   }
   131583 
   131584   /* Count the tokens in this AND/NEAR cluster. If none of the doclists
   131585   ** associated with the tokens spill onto overflow pages, or if there is
   131586   ** only 1 token, exit early. No tokens to defer in this case. */
   131587   for(ii=0; ii<nTC; ii++){
   131588     if( aTC[ii].pRoot==pRoot ){
   131589       nOvfl += aTC[ii].nOvfl;
   131590       nToken++;
   131591     }
   131592   }
   131593   if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
   131594 
   131595   /* Obtain the average docsize (in pages). */
   131596   rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
   131597   assert( rc!=SQLITE_OK || nDocSize>0 );
   131598 
   131599 
   131600   /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
   131601   ** of the number of overflow pages that will be loaded by the pager layer
   131602   ** to retrieve the entire doclist for the token from the full-text index.
   131603   ** Load the doclists for tokens that are either:
   131604   **
   131605   **   a. The cheapest token in the entire query (i.e. the one visited by the
   131606   **      first iteration of this loop), or
   131607   **
   131608   **   b. Part of a multi-token phrase.
   131609   **
   131610   ** After each token doclist is loaded, merge it with the others from the
   131611   ** same phrase and count the number of documents that the merged doclist
   131612   ** contains. Set variable "nMinEst" to the smallest number of documents in
   131613   ** any phrase doclist for which 1 or more token doclists have been loaded.
   131614   ** Let nOther be the number of other phrases for which it is certain that
   131615   ** one or more tokens will not be deferred.
   131616   **
   131617   ** Then, for each token, defer it if loading the doclist would result in
   131618   ** loading N or more overflow pages into memory, where N is computed as:
   131619   **
   131620   **    (nMinEst + 4^nOther - 1) / (4^nOther)
   131621   */
   131622   for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
   131623     int iTC;                      /* Used to iterate through aTC[] array. */
   131624     Fts3TokenAndCost *pTC = 0;    /* Set to cheapest remaining token. */
   131625 
   131626     /* Set pTC to point to the cheapest remaining token. */
   131627     for(iTC=0; iTC<nTC; iTC++){
   131628       if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
   131629        && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
   131630       ){
   131631         pTC = &aTC[iTC];
   131632       }
   131633     }
   131634     assert( pTC );
   131635 
   131636     if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
   131637       /* The number of overflow pages to load for this (and therefore all
   131638       ** subsequent) tokens is greater than the estimated number of pages
   131639       ** that will be loaded if all subsequent tokens are deferred.
   131640       */
   131641       Fts3PhraseToken *pToken = pTC->pToken;
   131642       rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
   131643       fts3SegReaderCursorFree(pToken->pSegcsr);
   131644       pToken->pSegcsr = 0;
   131645     }else{
   131646       /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
   131647       ** for-loop. Except, limit the value to 2^24 to prevent it from
   131648       ** overflowing the 32-bit integer it is stored in. */
   131649       if( ii<12 ) nLoad4 = nLoad4*4;
   131650 
   131651       if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
   131652         /* Either this is the cheapest token in the entire query, or it is
   131653         ** part of a multi-token phrase. Either way, the entire doclist will
   131654         ** (eventually) be loaded into memory. It may as well be now. */
   131655         Fts3PhraseToken *pToken = pTC->pToken;
   131656         int nList = 0;
   131657         char *pList = 0;
   131658         rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
   131659         assert( rc==SQLITE_OK || pList==0 );
   131660         if( rc==SQLITE_OK ){
   131661           int nCount;
   131662           fts3EvalPhraseMergeToken(pTab, pTC->pPhrase, pTC->iToken,pList,nList);
   131663           nCount = fts3DoclistCountDocids(
   131664               pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
   131665           );
   131666           if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
   131667         }
   131668       }
   131669     }
   131670     pTC->pToken = 0;
   131671   }
   131672 
   131673   return rc;
   131674 }
   131675 
   131676 /*
   131677 ** This function is called from within the xFilter method. It initializes
   131678 ** the full-text query currently stored in pCsr->pExpr. To iterate through
   131679 ** the results of a query, the caller does:
   131680 **
   131681 **    fts3EvalStart(pCsr);
   131682 **    while( 1 ){
   131683 **      fts3EvalNext(pCsr);
   131684 **      if( pCsr->bEof ) break;
   131685 **      ... return row pCsr->iPrevId to the caller ...
   131686 **    }
   131687 */
   131688 static int fts3EvalStart(Fts3Cursor *pCsr){
   131689   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   131690   int rc = SQLITE_OK;
   131691   int nToken = 0;
   131692   int nOr = 0;
   131693 
   131694   /* Allocate a MultiSegReader for each token in the expression. */
   131695   fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
   131696 
   131697   /* Determine which, if any, tokens in the expression should be deferred. */
   131698 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
   131699   if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
   131700     Fts3TokenAndCost *aTC;
   131701     Fts3Expr **apOr;
   131702     aTC = (Fts3TokenAndCost *)sqlite3_malloc(
   131703         sizeof(Fts3TokenAndCost) * nToken
   131704       + sizeof(Fts3Expr *) * nOr * 2
   131705     );
   131706     apOr = (Fts3Expr **)&aTC[nToken];
   131707 
   131708     if( !aTC ){
   131709       rc = SQLITE_NOMEM;
   131710     }else{
   131711       int ii;
   131712       Fts3TokenAndCost *pTC = aTC;
   131713       Fts3Expr **ppOr = apOr;
   131714 
   131715       fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
   131716       nToken = (int)(pTC-aTC);
   131717       nOr = (int)(ppOr-apOr);
   131718 
   131719       if( rc==SQLITE_OK ){
   131720         rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
   131721         for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
   131722           rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
   131723         }
   131724       }
   131725 
   131726       sqlite3_free(aTC);
   131727     }
   131728   }
   131729 #endif
   131730 
   131731   fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
   131732   return rc;
   131733 }
   131734 
   131735 /*
   131736 ** Invalidate the current position list for phrase pPhrase.
   131737 */
   131738 static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
   131739   if( pPhrase->doclist.bFreeList ){
   131740     sqlite3_free(pPhrase->doclist.pList);
   131741   }
   131742   pPhrase->doclist.pList = 0;
   131743   pPhrase->doclist.nList = 0;
   131744   pPhrase->doclist.bFreeList = 0;
   131745 }
   131746 
   131747 /*
   131748 ** This function is called to edit the position list associated with
   131749 ** the phrase object passed as the fifth argument according to a NEAR
   131750 ** condition. For example:
   131751 **
   131752 **     abc NEAR/5 "def ghi"
   131753 **
   131754 ** Parameter nNear is passed the NEAR distance of the expression (5 in
   131755 ** the example above). When this function is called, *paPoslist points to
   131756 ** the position list, and *pnToken is the number of phrase tokens in, the
   131757 ** phrase on the other side of the NEAR operator to pPhrase. For example,
   131758 ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
   131759 ** the position list associated with phrase "abc".
   131760 **
   131761 ** All positions in the pPhrase position list that are not sufficiently
   131762 ** close to a position in the *paPoslist position list are removed. If this
   131763 ** leaves 0 positions, zero is returned. Otherwise, non-zero.
   131764 **
   131765 ** Before returning, *paPoslist is set to point to the position lsit
   131766 ** associated with pPhrase. And *pnToken is set to the number of tokens in
   131767 ** pPhrase.
   131768 */
   131769 static int fts3EvalNearTrim(
   131770   int nNear,                      /* NEAR distance. As in "NEAR/nNear". */
   131771   char *aTmp,                     /* Temporary space to use */
   131772   char **paPoslist,               /* IN/OUT: Position list */
   131773   int *pnToken,                   /* IN/OUT: Tokens in phrase of *paPoslist */
   131774   Fts3Phrase *pPhrase             /* The phrase object to trim the doclist of */
   131775 ){
   131776   int nParam1 = nNear + pPhrase->nToken;
   131777   int nParam2 = nNear + *pnToken;
   131778   int nNew;
   131779   char *p2;
   131780   char *pOut;
   131781   int res;
   131782 
   131783   assert( pPhrase->doclist.pList );
   131784 
   131785   p2 = pOut = pPhrase->doclist.pList;
   131786   res = fts3PoslistNearMerge(
   131787     &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
   131788   );
   131789   if( res ){
   131790     nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
   131791     assert( pPhrase->doclist.pList[nNew]=='\0' );
   131792     assert( nNew<=pPhrase->doclist.nList && nNew>0 );
   131793     memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
   131794     pPhrase->doclist.nList = nNew;
   131795     *paPoslist = pPhrase->doclist.pList;
   131796     *pnToken = pPhrase->nToken;
   131797   }
   131798 
   131799   return res;
   131800 }
   131801 
   131802 /*
   131803 ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
   131804 ** Otherwise, it advances the expression passed as the second argument to
   131805 ** point to the next matching row in the database. Expressions iterate through
   131806 ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
   131807 ** or descending if it is non-zero.
   131808 **
   131809 ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
   131810 ** successful, the following variables in pExpr are set:
   131811 **
   131812 **   Fts3Expr.bEof                (non-zero if EOF - there is no next row)
   131813 **   Fts3Expr.iDocid              (valid if bEof==0. The docid of the next row)
   131814 **
   131815 ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
   131816 ** at EOF, then the following variables are populated with the position list
   131817 ** for the phrase for the visited row:
   131818 **
   131819 **   FTs3Expr.pPhrase->doclist.nList        (length of pList in bytes)
   131820 **   FTs3Expr.pPhrase->doclist.pList        (pointer to position list)
   131821 **
   131822 ** It says above that this function advances the expression to the next
   131823 ** matching row. This is usually true, but there are the following exceptions:
   131824 **
   131825 **   1. Deferred tokens are not taken into account. If a phrase consists
   131826 **      entirely of deferred tokens, it is assumed to match every row in
   131827 **      the db. In this case the position-list is not populated at all.
   131828 **
   131829 **      Or, if a phrase contains one or more deferred tokens and one or
   131830 **      more non-deferred tokens, then the expression is advanced to the
   131831 **      next possible match, considering only non-deferred tokens. In other
   131832 **      words, if the phrase is "A B C", and "B" is deferred, the expression
   131833 **      is advanced to the next row that contains an instance of "A * C",
   131834 **      where "*" may match any single token. The position list in this case
   131835 **      is populated as for "A * C" before returning.
   131836 **
   131837 **   2. NEAR is treated as AND. If the expression is "x NEAR y", it is
   131838 **      advanced to point to the next row that matches "x AND y".
   131839 **
   131840 ** See fts3EvalTestDeferredAndNear() for details on testing if a row is
   131841 ** really a match, taking into account deferred tokens and NEAR operators.
   131842 */
   131843 static void fts3EvalNextRow(
   131844   Fts3Cursor *pCsr,               /* FTS Cursor handle */
   131845   Fts3Expr *pExpr,                /* Expr. to advance to next matching row */
   131846   int *pRc                        /* IN/OUT: Error code */
   131847 ){
   131848   if( *pRc==SQLITE_OK ){
   131849     int bDescDoclist = pCsr->bDesc;         /* Used by DOCID_CMP() macro */
   131850     assert( pExpr->bEof==0 );
   131851     pExpr->bStart = 1;
   131852 
   131853     switch( pExpr->eType ){
   131854       case FTSQUERY_NEAR:
   131855       case FTSQUERY_AND: {
   131856         Fts3Expr *pLeft = pExpr->pLeft;
   131857         Fts3Expr *pRight = pExpr->pRight;
   131858         assert( !pLeft->bDeferred || !pRight->bDeferred );
   131859 
   131860         if( pLeft->bDeferred ){
   131861           /* LHS is entirely deferred. So we assume it matches every row.
   131862           ** Advance the RHS iterator to find the next row visited. */
   131863           fts3EvalNextRow(pCsr, pRight, pRc);
   131864           pExpr->iDocid = pRight->iDocid;
   131865           pExpr->bEof = pRight->bEof;
   131866         }else if( pRight->bDeferred ){
   131867           /* RHS is entirely deferred. So we assume it matches every row.
   131868           ** Advance the LHS iterator to find the next row visited. */
   131869           fts3EvalNextRow(pCsr, pLeft, pRc);
   131870           pExpr->iDocid = pLeft->iDocid;
   131871           pExpr->bEof = pLeft->bEof;
   131872         }else{
   131873           /* Neither the RHS or LHS are deferred. */
   131874           fts3EvalNextRow(pCsr, pLeft, pRc);
   131875           fts3EvalNextRow(pCsr, pRight, pRc);
   131876           while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
   131877             sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
   131878             if( iDiff==0 ) break;
   131879             if( iDiff<0 ){
   131880               fts3EvalNextRow(pCsr, pLeft, pRc);
   131881             }else{
   131882               fts3EvalNextRow(pCsr, pRight, pRc);
   131883             }
   131884           }
   131885           pExpr->iDocid = pLeft->iDocid;
   131886           pExpr->bEof = (pLeft->bEof || pRight->bEof);
   131887         }
   131888         break;
   131889       }
   131890 
   131891       case FTSQUERY_OR: {
   131892         Fts3Expr *pLeft = pExpr->pLeft;
   131893         Fts3Expr *pRight = pExpr->pRight;
   131894         sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
   131895 
   131896         assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
   131897         assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
   131898 
   131899         if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
   131900           fts3EvalNextRow(pCsr, pLeft, pRc);
   131901         }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
   131902           fts3EvalNextRow(pCsr, pRight, pRc);
   131903         }else{
   131904           fts3EvalNextRow(pCsr, pLeft, pRc);
   131905           fts3EvalNextRow(pCsr, pRight, pRc);
   131906         }
   131907 
   131908         pExpr->bEof = (pLeft->bEof && pRight->bEof);
   131909         iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
   131910         if( pRight->bEof || (pLeft->bEof==0 &&  iCmp<0) ){
   131911           pExpr->iDocid = pLeft->iDocid;
   131912         }else{
   131913           pExpr->iDocid = pRight->iDocid;
   131914         }
   131915 
   131916         break;
   131917       }
   131918 
   131919       case FTSQUERY_NOT: {
   131920         Fts3Expr *pLeft = pExpr->pLeft;
   131921         Fts3Expr *pRight = pExpr->pRight;
   131922 
   131923         if( pRight->bStart==0 ){
   131924           fts3EvalNextRow(pCsr, pRight, pRc);
   131925           assert( *pRc!=SQLITE_OK || pRight->bStart );
   131926         }
   131927 
   131928         fts3EvalNextRow(pCsr, pLeft, pRc);
   131929         if( pLeft->bEof==0 ){
   131930           while( !*pRc
   131931               && !pRight->bEof
   131932               && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
   131933           ){
   131934             fts3EvalNextRow(pCsr, pRight, pRc);
   131935           }
   131936         }
   131937         pExpr->iDocid = pLeft->iDocid;
   131938         pExpr->bEof = pLeft->bEof;
   131939         break;
   131940       }
   131941 
   131942       default: {
   131943         Fts3Phrase *pPhrase = pExpr->pPhrase;
   131944         fts3EvalInvalidatePoslist(pPhrase);
   131945         *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
   131946         pExpr->iDocid = pPhrase->doclist.iDocid;
   131947         break;
   131948       }
   131949     }
   131950   }
   131951 }
   131952 
   131953 /*
   131954 ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
   131955 ** cluster, then this function returns 1 immediately.
   131956 **
   131957 ** Otherwise, it checks if the current row really does match the NEAR
   131958 ** expression, using the data currently stored in the position lists
   131959 ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
   131960 **
   131961 ** If the current row is a match, the position list associated with each
   131962 ** phrase in the NEAR expression is edited in place to contain only those
   131963 ** phrase instances sufficiently close to their peers to satisfy all NEAR
   131964 ** constraints. In this case it returns 1. If the NEAR expression does not
   131965 ** match the current row, 0 is returned. The position lists may or may not
   131966 ** be edited if 0 is returned.
   131967 */
   131968 static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
   131969   int res = 1;
   131970 
   131971   /* The following block runs if pExpr is the root of a NEAR query.
   131972   ** For example, the query:
   131973   **
   131974   **         "w" NEAR "x" NEAR "y" NEAR "z"
   131975   **
   131976   ** which is represented in tree form as:
   131977   **
   131978   **                               |
   131979   **                          +--NEAR--+      <-- root of NEAR query
   131980   **                          |        |
   131981   **                     +--NEAR--+   "z"
   131982   **                     |        |
   131983   **                +--NEAR--+   "y"
   131984   **                |        |
   131985   **               "w"      "x"
   131986   **
   131987   ** The right-hand child of a NEAR node is always a phrase. The
   131988   ** left-hand child may be either a phrase or a NEAR node. There are
   131989   ** no exceptions to this - it's the way the parser in fts3_expr.c works.
   131990   */
   131991   if( *pRc==SQLITE_OK
   131992    && pExpr->eType==FTSQUERY_NEAR
   131993    && pExpr->bEof==0
   131994    && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
   131995   ){
   131996     Fts3Expr *p;
   131997     int nTmp = 0;                 /* Bytes of temp space */
   131998     char *aTmp;                   /* Temp space for PoslistNearMerge() */
   131999 
   132000     /* Allocate temporary working space. */
   132001     for(p=pExpr; p->pLeft; p=p->pLeft){
   132002       nTmp += p->pRight->pPhrase->doclist.nList;
   132003     }
   132004     nTmp += p->pPhrase->doclist.nList;
   132005     if( nTmp==0 ){
   132006       res = 0;
   132007     }else{
   132008       aTmp = sqlite3_malloc(nTmp*2);
   132009       if( !aTmp ){
   132010         *pRc = SQLITE_NOMEM;
   132011         res = 0;
   132012       }else{
   132013         char *aPoslist = p->pPhrase->doclist.pList;
   132014         int nToken = p->pPhrase->nToken;
   132015 
   132016         for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
   132017           Fts3Phrase *pPhrase = p->pRight->pPhrase;
   132018           int nNear = p->nNear;
   132019           res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
   132020         }
   132021 
   132022         aPoslist = pExpr->pRight->pPhrase->doclist.pList;
   132023         nToken = pExpr->pRight->pPhrase->nToken;
   132024         for(p=pExpr->pLeft; p && res; p=p->pLeft){
   132025           int nNear;
   132026           Fts3Phrase *pPhrase;
   132027           assert( p->pParent && p->pParent->pLeft==p );
   132028           nNear = p->pParent->nNear;
   132029           pPhrase = (
   132030               p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
   132031               );
   132032           res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
   132033         }
   132034       }
   132035 
   132036       sqlite3_free(aTmp);
   132037     }
   132038   }
   132039 
   132040   return res;
   132041 }
   132042 
   132043 /*
   132044 ** This function is a helper function for fts3EvalTestDeferredAndNear().
   132045 ** Assuming no error occurs or has occurred, It returns non-zero if the
   132046 ** expression passed as the second argument matches the row that pCsr
   132047 ** currently points to, or zero if it does not.
   132048 **
   132049 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
   132050 ** If an error occurs during execution of this function, *pRc is set to
   132051 ** the appropriate SQLite error code. In this case the returned value is
   132052 ** undefined.
   132053 */
   132054 static int fts3EvalTestExpr(
   132055   Fts3Cursor *pCsr,               /* FTS cursor handle */
   132056   Fts3Expr *pExpr,                /* Expr to test. May or may not be root. */
   132057   int *pRc                        /* IN/OUT: Error code */
   132058 ){
   132059   int bHit = 1;                   /* Return value */
   132060   if( *pRc==SQLITE_OK ){
   132061     switch( pExpr->eType ){
   132062       case FTSQUERY_NEAR:
   132063       case FTSQUERY_AND:
   132064         bHit = (
   132065             fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
   132066          && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
   132067          && fts3EvalNearTest(pExpr, pRc)
   132068         );
   132069 
   132070         /* If the NEAR expression does not match any rows, zero the doclist for
   132071         ** all phrases involved in the NEAR. This is because the snippet(),
   132072         ** offsets() and matchinfo() functions are not supposed to recognize
   132073         ** any instances of phrases that are part of unmatched NEAR queries.
   132074         ** For example if this expression:
   132075         **
   132076         **    ... MATCH 'a OR (b NEAR c)'
   132077         **
   132078         ** is matched against a row containing:
   132079         **
   132080         **        'a b d e'
   132081         **
   132082         ** then any snippet() should ony highlight the "a" term, not the "b"
   132083         ** (as "b" is part of a non-matching NEAR clause).
   132084         */
   132085         if( bHit==0
   132086          && pExpr->eType==FTSQUERY_NEAR
   132087          && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
   132088         ){
   132089           Fts3Expr *p;
   132090           for(p=pExpr; p->pPhrase==0; p=p->pLeft){
   132091             if( p->pRight->iDocid==pCsr->iPrevId ){
   132092               fts3EvalInvalidatePoslist(p->pRight->pPhrase);
   132093             }
   132094           }
   132095           if( p->iDocid==pCsr->iPrevId ){
   132096             fts3EvalInvalidatePoslist(p->pPhrase);
   132097           }
   132098         }
   132099 
   132100         break;
   132101 
   132102       case FTSQUERY_OR: {
   132103         int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
   132104         int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
   132105         bHit = bHit1 || bHit2;
   132106         break;
   132107       }
   132108 
   132109       case FTSQUERY_NOT:
   132110         bHit = (
   132111             fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
   132112          && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
   132113         );
   132114         break;
   132115 
   132116       default: {
   132117 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
   132118         if( pCsr->pDeferred
   132119          && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
   132120         ){
   132121           Fts3Phrase *pPhrase = pExpr->pPhrase;
   132122           assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
   132123           if( pExpr->bDeferred ){
   132124             fts3EvalInvalidatePoslist(pPhrase);
   132125           }
   132126           *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
   132127           bHit = (pPhrase->doclist.pList!=0);
   132128           pExpr->iDocid = pCsr->iPrevId;
   132129         }else
   132130 #endif
   132131         {
   132132           bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
   132133         }
   132134         break;
   132135       }
   132136     }
   132137   }
   132138   return bHit;
   132139 }
   132140 
   132141 /*
   132142 ** This function is called as the second part of each xNext operation when
   132143 ** iterating through the results of a full-text query. At this point the
   132144 ** cursor points to a row that matches the query expression, with the
   132145 ** following caveats:
   132146 **
   132147 **   * Up until this point, "NEAR" operators in the expression have been
   132148 **     treated as "AND".
   132149 **
   132150 **   * Deferred tokens have not yet been considered.
   132151 **
   132152 ** If *pRc is not SQLITE_OK when this function is called, it immediately
   132153 ** returns 0. Otherwise, it tests whether or not after considering NEAR
   132154 ** operators and deferred tokens the current row is still a match for the
   132155 ** expression. It returns 1 if both of the following are true:
   132156 **
   132157 **   1. *pRc is SQLITE_OK when this function returns, and
   132158 **
   132159 **   2. After scanning the current FTS table row for the deferred tokens,
   132160 **      it is determined that the row does *not* match the query.
   132161 **
   132162 ** Or, if no error occurs and it seems the current row does match the FTS
   132163 ** query, return 0.
   132164 */
   132165 static int fts3EvalTestDeferredAndNear(Fts3Cursor *pCsr, int *pRc){
   132166   int rc = *pRc;
   132167   int bMiss = 0;
   132168   if( rc==SQLITE_OK ){
   132169 
   132170     /* If there are one or more deferred tokens, load the current row into
   132171     ** memory and scan it to determine the position list for each deferred
   132172     ** token. Then, see if this row is really a match, considering deferred
   132173     ** tokens and NEAR operators (neither of which were taken into account
   132174     ** earlier, by fts3EvalNextRow()).
   132175     */
   132176     if( pCsr->pDeferred ){
   132177       rc = fts3CursorSeek(0, pCsr);
   132178       if( rc==SQLITE_OK ){
   132179         rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
   132180       }
   132181     }
   132182     bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
   132183 
   132184     /* Free the position-lists accumulated for each deferred token above. */
   132185     sqlite3Fts3FreeDeferredDoclists(pCsr);
   132186     *pRc = rc;
   132187   }
   132188   return (rc==SQLITE_OK && bMiss);
   132189 }
   132190 
   132191 /*
   132192 ** Advance to the next document that matches the FTS expression in
   132193 ** Fts3Cursor.pExpr.
   132194 */
   132195 static int fts3EvalNext(Fts3Cursor *pCsr){
   132196   int rc = SQLITE_OK;             /* Return Code */
   132197   Fts3Expr *pExpr = pCsr->pExpr;
   132198   assert( pCsr->isEof==0 );
   132199   if( pExpr==0 ){
   132200     pCsr->isEof = 1;
   132201   }else{
   132202     do {
   132203       if( pCsr->isRequireSeek==0 ){
   132204         sqlite3_reset(pCsr->pStmt);
   132205       }
   132206       assert( sqlite3_data_count(pCsr->pStmt)==0 );
   132207       fts3EvalNextRow(pCsr, pExpr, &rc);
   132208       pCsr->isEof = pExpr->bEof;
   132209       pCsr->isRequireSeek = 1;
   132210       pCsr->isMatchinfoNeeded = 1;
   132211       pCsr->iPrevId = pExpr->iDocid;
   132212     }while( pCsr->isEof==0 && fts3EvalTestDeferredAndNear(pCsr, &rc) );
   132213   }
   132214 
   132215   /* Check if the cursor is past the end of the docid range specified
   132216   ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag.  */
   132217   if( rc==SQLITE_OK && (
   132218         (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
   132219      || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
   132220   )){
   132221     pCsr->isEof = 1;
   132222   }
   132223 
   132224   return rc;
   132225 }
   132226 
   132227 /*
   132228 ** Restart interation for expression pExpr so that the next call to
   132229 ** fts3EvalNext() visits the first row. Do not allow incremental
   132230 ** loading or merging of phrase doclists for this iteration.
   132231 **
   132232 ** If *pRc is other than SQLITE_OK when this function is called, it is
   132233 ** a no-op. If an error occurs within this function, *pRc is set to an
   132234 ** SQLite error code before returning.
   132235 */
   132236 static void fts3EvalRestart(
   132237   Fts3Cursor *pCsr,
   132238   Fts3Expr *pExpr,
   132239   int *pRc
   132240 ){
   132241   if( pExpr && *pRc==SQLITE_OK ){
   132242     Fts3Phrase *pPhrase = pExpr->pPhrase;
   132243 
   132244     if( pPhrase ){
   132245       fts3EvalInvalidatePoslist(pPhrase);
   132246       if( pPhrase->bIncr ){
   132247         int i;
   132248         for(i=0; i<pPhrase->nToken; i++){
   132249           Fts3PhraseToken *pToken = &pPhrase->aToken[i];
   132250           assert( pToken->pDeferred==0 );
   132251           if( pToken->pSegcsr ){
   132252             sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
   132253           }
   132254         }
   132255         *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
   132256       }
   132257       pPhrase->doclist.pNextDocid = 0;
   132258       pPhrase->doclist.iDocid = 0;
   132259     }
   132260 
   132261     pExpr->iDocid = 0;
   132262     pExpr->bEof = 0;
   132263     pExpr->bStart = 0;
   132264 
   132265     fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
   132266     fts3EvalRestart(pCsr, pExpr->pRight, pRc);
   132267   }
   132268 }
   132269 
   132270 /*
   132271 ** After allocating the Fts3Expr.aMI[] array for each phrase in the
   132272 ** expression rooted at pExpr, the cursor iterates through all rows matched
   132273 ** by pExpr, calling this function for each row. This function increments
   132274 ** the values in Fts3Expr.aMI[] according to the position-list currently
   132275 ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
   132276 ** expression nodes.
   132277 */
   132278 static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
   132279   if( pExpr ){
   132280     Fts3Phrase *pPhrase = pExpr->pPhrase;
   132281     if( pPhrase && pPhrase->doclist.pList ){
   132282       int iCol = 0;
   132283       char *p = pPhrase->doclist.pList;
   132284 
   132285       assert( *p );
   132286       while( 1 ){
   132287         u8 c = 0;
   132288         int iCnt = 0;
   132289         while( 0xFE & (*p | c) ){
   132290           if( (c&0x80)==0 ) iCnt++;
   132291           c = *p++ & 0x80;
   132292         }
   132293 
   132294         /* aMI[iCol*3 + 1] = Number of occurrences
   132295         ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
   132296         */
   132297         pExpr->aMI[iCol*3 + 1] += iCnt;
   132298         pExpr->aMI[iCol*3 + 2] += (iCnt>0);
   132299         if( *p==0x00 ) break;
   132300         p++;
   132301         p += fts3GetVarint32(p, &iCol);
   132302       }
   132303     }
   132304 
   132305     fts3EvalUpdateCounts(pExpr->pLeft);
   132306     fts3EvalUpdateCounts(pExpr->pRight);
   132307   }
   132308 }
   132309 
   132310 /*
   132311 ** Expression pExpr must be of type FTSQUERY_PHRASE.
   132312 **
   132313 ** If it is not already allocated and populated, this function allocates and
   132314 ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
   132315 ** of a NEAR expression, then it also allocates and populates the same array
   132316 ** for all other phrases that are part of the NEAR expression.
   132317 **
   132318 ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
   132319 ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
   132320 */
   132321 static int fts3EvalGatherStats(
   132322   Fts3Cursor *pCsr,               /* Cursor object */
   132323   Fts3Expr *pExpr                 /* FTSQUERY_PHRASE expression */
   132324 ){
   132325   int rc = SQLITE_OK;             /* Return code */
   132326 
   132327   assert( pExpr->eType==FTSQUERY_PHRASE );
   132328   if( pExpr->aMI==0 ){
   132329     Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   132330     Fts3Expr *pRoot;                /* Root of NEAR expression */
   132331     Fts3Expr *p;                    /* Iterator used for several purposes */
   132332 
   132333     sqlite3_int64 iPrevId = pCsr->iPrevId;
   132334     sqlite3_int64 iDocid;
   132335     u8 bEof;
   132336 
   132337     /* Find the root of the NEAR expression */
   132338     pRoot = pExpr;
   132339     while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
   132340       pRoot = pRoot->pParent;
   132341     }
   132342     iDocid = pRoot->iDocid;
   132343     bEof = pRoot->bEof;
   132344     assert( pRoot->bStart );
   132345 
   132346     /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
   132347     for(p=pRoot; p; p=p->pLeft){
   132348       Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
   132349       assert( pE->aMI==0 );
   132350       pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
   132351       if( !pE->aMI ) return SQLITE_NOMEM;
   132352       memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
   132353     }
   132354 
   132355     fts3EvalRestart(pCsr, pRoot, &rc);
   132356 
   132357     while( pCsr->isEof==0 && rc==SQLITE_OK ){
   132358 
   132359       do {
   132360         /* Ensure the %_content statement is reset. */
   132361         if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
   132362         assert( sqlite3_data_count(pCsr->pStmt)==0 );
   132363 
   132364         /* Advance to the next document */
   132365         fts3EvalNextRow(pCsr, pRoot, &rc);
   132366         pCsr->isEof = pRoot->bEof;
   132367         pCsr->isRequireSeek = 1;
   132368         pCsr->isMatchinfoNeeded = 1;
   132369         pCsr->iPrevId = pRoot->iDocid;
   132370       }while( pCsr->isEof==0
   132371            && pRoot->eType==FTSQUERY_NEAR
   132372            && fts3EvalTestDeferredAndNear(pCsr, &rc)
   132373       );
   132374 
   132375       if( rc==SQLITE_OK && pCsr->isEof==0 ){
   132376         fts3EvalUpdateCounts(pRoot);
   132377       }
   132378     }
   132379 
   132380     pCsr->isEof = 0;
   132381     pCsr->iPrevId = iPrevId;
   132382 
   132383     if( bEof ){
   132384       pRoot->bEof = bEof;
   132385     }else{
   132386       /* Caution: pRoot may iterate through docids in ascending or descending
   132387       ** order. For this reason, even though it seems more defensive, the
   132388       ** do loop can not be written:
   132389       **
   132390       **   do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
   132391       */
   132392       fts3EvalRestart(pCsr, pRoot, &rc);
   132393       do {
   132394         fts3EvalNextRow(pCsr, pRoot, &rc);
   132395         assert( pRoot->bEof==0 );
   132396       }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
   132397       fts3EvalTestDeferredAndNear(pCsr, &rc);
   132398     }
   132399   }
   132400   return rc;
   132401 }
   132402 
   132403 /*
   132404 ** This function is used by the matchinfo() module to query a phrase
   132405 ** expression node for the following information:
   132406 **
   132407 **   1. The total number of occurrences of the phrase in each column of
   132408 **      the FTS table (considering all rows), and
   132409 **
   132410 **   2. For each column, the number of rows in the table for which the
   132411 **      column contains at least one instance of the phrase.
   132412 **
   132413 ** If no error occurs, SQLITE_OK is returned and the values for each column
   132414 ** written into the array aiOut as follows:
   132415 **
   132416 **   aiOut[iCol*3 + 1] = Number of occurrences
   132417 **   aiOut[iCol*3 + 2] = Number of rows containing at least one instance
   132418 **
   132419 ** Caveats:
   132420 **
   132421 **   * If a phrase consists entirely of deferred tokens, then all output
   132422 **     values are set to the number of documents in the table. In other
   132423 **     words we assume that very common tokens occur exactly once in each
   132424 **     column of each row of the table.
   132425 **
   132426 **   * If a phrase contains some deferred tokens (and some non-deferred
   132427 **     tokens), count the potential occurrence identified by considering
   132428 **     the non-deferred tokens instead of actual phrase occurrences.
   132429 **
   132430 **   * If the phrase is part of a NEAR expression, then only phrase instances
   132431 **     that meet the NEAR constraint are included in the counts.
   132432 */
   132433 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
   132434   Fts3Cursor *pCsr,               /* FTS cursor handle */
   132435   Fts3Expr *pExpr,                /* Phrase expression */
   132436   u32 *aiOut                      /* Array to write results into (see above) */
   132437 ){
   132438   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   132439   int rc = SQLITE_OK;
   132440   int iCol;
   132441 
   132442   if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
   132443     assert( pCsr->nDoc>0 );
   132444     for(iCol=0; iCol<pTab->nColumn; iCol++){
   132445       aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
   132446       aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
   132447     }
   132448   }else{
   132449     rc = fts3EvalGatherStats(pCsr, pExpr);
   132450     if( rc==SQLITE_OK ){
   132451       assert( pExpr->aMI );
   132452       for(iCol=0; iCol<pTab->nColumn; iCol++){
   132453         aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
   132454         aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
   132455       }
   132456     }
   132457   }
   132458 
   132459   return rc;
   132460 }
   132461 
   132462 /*
   132463 ** The expression pExpr passed as the second argument to this function
   132464 ** must be of type FTSQUERY_PHRASE.
   132465 **
   132466 ** The returned value is either NULL or a pointer to a buffer containing
   132467 ** a position-list indicating the occurrences of the phrase in column iCol
   132468 ** of the current row.
   132469 **
   132470 ** More specifically, the returned buffer contains 1 varint for each
   132471 ** occurrence of the phrase in the column, stored using the normal (delta+2)
   132472 ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
   132473 ** if the requested column contains "a b X c d X X" and the position-list
   132474 ** for 'X' is requested, the buffer returned may contain:
   132475 **
   132476 **     0x04 0x05 0x03 0x01   or   0x04 0x05 0x03 0x00
   132477 **
   132478 ** This function works regardless of whether or not the phrase is deferred,
   132479 ** incremental, or neither.
   132480 */
   132481 SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
   132482   Fts3Cursor *pCsr,               /* FTS3 cursor object */
   132483   Fts3Expr *pExpr,                /* Phrase to return doclist for */
   132484   int iCol,                       /* Column to return position list for */
   132485   char **ppOut                    /* OUT: Pointer to position list */
   132486 ){
   132487   Fts3Phrase *pPhrase = pExpr->pPhrase;
   132488   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   132489   char *pIter;
   132490   int iThis;
   132491   sqlite3_int64 iDocid;
   132492 
   132493   /* If this phrase is applies specifically to some column other than
   132494   ** column iCol, return a NULL pointer.  */
   132495   *ppOut = 0;
   132496   assert( iCol>=0 && iCol<pTab->nColumn );
   132497   if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
   132498     return SQLITE_OK;
   132499   }
   132500 
   132501   iDocid = pExpr->iDocid;
   132502   pIter = pPhrase->doclist.pList;
   132503   if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
   132504     int bDescDoclist = pTab->bDescIdx;      /* For DOCID_CMP macro */
   132505     int iMul;                     /* +1 if csr dir matches index dir, else -1 */
   132506     int bOr = 0;
   132507     u8 bEof = 0;
   132508     u8 bTreeEof = 0;
   132509     Fts3Expr *p;                  /* Used to iterate from pExpr to root */
   132510     Fts3Expr *pNear;              /* Most senior NEAR ancestor (or pExpr) */
   132511 
   132512     /* Check if this phrase descends from an OR expression node. If not,
   132513     ** return NULL. Otherwise, the entry that corresponds to docid
   132514     ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
   132515     ** tree that the node is part of has been marked as EOF, but the node
   132516     ** itself is not EOF, then it may point to an earlier entry. */
   132517     pNear = pExpr;
   132518     for(p=pExpr->pParent; p; p=p->pParent){
   132519       if( p->eType==FTSQUERY_OR ) bOr = 1;
   132520       if( p->eType==FTSQUERY_NEAR ) pNear = p;
   132521       if( p->bEof ) bTreeEof = 1;
   132522     }
   132523     if( bOr==0 ) return SQLITE_OK;
   132524 
   132525     /* This is the descendent of an OR node. In this case we cannot use
   132526     ** an incremental phrase. Load the entire doclist for the phrase
   132527     ** into memory in this case.  */
   132528     if( pPhrase->bIncr ){
   132529       int rc = SQLITE_OK;
   132530       int bEofSave = pExpr->bEof;
   132531       fts3EvalRestart(pCsr, pExpr, &rc);
   132532       while( rc==SQLITE_OK && !pExpr->bEof ){
   132533         fts3EvalNextRow(pCsr, pExpr, &rc);
   132534         if( bEofSave==0 && pExpr->iDocid==iDocid ) break;
   132535       }
   132536       pIter = pPhrase->doclist.pList;
   132537       assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
   132538       if( rc!=SQLITE_OK ) return rc;
   132539     }
   132540 
   132541     iMul = ((pCsr->bDesc==bDescDoclist) ? 1 : -1);
   132542     while( bTreeEof==1
   132543         && pNear->bEof==0
   132544         && (DOCID_CMP(pNear->iDocid, pCsr->iPrevId) * iMul)<0
   132545     ){
   132546       int rc = SQLITE_OK;
   132547       fts3EvalNextRow(pCsr, pExpr, &rc);
   132548       if( rc!=SQLITE_OK ) return rc;
   132549       iDocid = pExpr->iDocid;
   132550       pIter = pPhrase->doclist.pList;
   132551     }
   132552 
   132553     bEof = (pPhrase->doclist.nAll==0);
   132554     assert( bDescDoclist==0 || bDescDoclist==1 );
   132555     assert( pCsr->bDesc==0 || pCsr->bDesc==1 );
   132556 
   132557     if( bEof==0 ){
   132558       if( pCsr->bDesc==bDescDoclist ){
   132559         int dummy;
   132560         if( pNear->bEof ){
   132561           /* This expression is already at EOF. So position it to point to the
   132562           ** last entry in the doclist at pPhrase->doclist.aAll[]. Variable
   132563           ** iDocid is already set for this entry, so all that is required is
   132564           ** to set pIter to point to the first byte of the last position-list
   132565           ** in the doclist.
   132566           **
   132567           ** It would also be correct to set pIter and iDocid to zero. In
   132568           ** this case, the first call to sqltie3Fts4DoclistPrev() below
   132569           ** would also move the iterator to point to the last entry in the
   132570           ** doclist. However, this is expensive, as to do so it has to
   132571           ** iterate through the entire doclist from start to finish (since
   132572           ** it does not know the docid for the last entry).  */
   132573           pIter = &pPhrase->doclist.aAll[pPhrase->doclist.nAll-1];
   132574           fts3ReversePoslist(pPhrase->doclist.aAll, &pIter);
   132575         }
   132576         while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
   132577           sqlite3Fts3DoclistPrev(
   132578               bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
   132579               &pIter, &iDocid, &dummy, &bEof
   132580           );
   132581         }
   132582       }else{
   132583         if( pNear->bEof ){
   132584           pIter = 0;
   132585           iDocid = 0;
   132586         }
   132587         while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
   132588           sqlite3Fts3DoclistNext(
   132589               bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
   132590               &pIter, &iDocid, &bEof
   132591           );
   132592         }
   132593       }
   132594     }
   132595 
   132596     if( bEof || iDocid!=pCsr->iPrevId ) pIter = 0;
   132597   }
   132598   if( pIter==0 ) return SQLITE_OK;
   132599 
   132600   if( *pIter==0x01 ){
   132601     pIter++;
   132602     pIter += fts3GetVarint32(pIter, &iThis);
   132603   }else{
   132604     iThis = 0;
   132605   }
   132606   while( iThis<iCol ){
   132607     fts3ColumnlistCopy(0, &pIter);
   132608     if( *pIter==0x00 ) return 0;
   132609     pIter++;
   132610     pIter += fts3GetVarint32(pIter, &iThis);
   132611   }
   132612 
   132613   *ppOut = ((iCol==iThis)?pIter:0);
   132614   return SQLITE_OK;
   132615 }
   132616 
   132617 /*
   132618 ** Free all components of the Fts3Phrase structure that were allocated by
   132619 ** the eval module. Specifically, this means to free:
   132620 **
   132621 **   * the contents of pPhrase->doclist, and
   132622 **   * any Fts3MultiSegReader objects held by phrase tokens.
   132623 */
   132624 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
   132625   if( pPhrase ){
   132626     int i;
   132627     sqlite3_free(pPhrase->doclist.aAll);
   132628     fts3EvalInvalidatePoslist(pPhrase);
   132629     memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
   132630     for(i=0; i<pPhrase->nToken; i++){
   132631       fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
   132632       pPhrase->aToken[i].pSegcsr = 0;
   132633     }
   132634   }
   132635 }
   132636 
   132637 
   132638 /*
   132639 ** Return SQLITE_CORRUPT_VTAB.
   132640 */
   132641 #ifdef SQLITE_DEBUG
   132642 SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
   132643   return SQLITE_CORRUPT_VTAB;
   132644 }
   132645 #endif
   132646 
   132647 #if !SQLITE_CORE
   132648 /*
   132649 ** Initialize API pointer table, if required.
   132650 */
   132651 #ifdef _WIN32
   132652 __declspec(dllexport)
   132653 #endif
   132654 SQLITE_API int sqlite3_fts3_init(
   132655   sqlite3 *db,
   132656   char **pzErrMsg,
   132657   const sqlite3_api_routines *pApi
   132658 ){
   132659   SQLITE_EXTENSION_INIT2(pApi)
   132660   return sqlite3Fts3Init(db);
   132661 }
   132662 #endif
   132663 
   132664 #endif
   132665 
   132666 /************** End of fts3.c ************************************************/
   132667 /************** Begin file fts3_aux.c ****************************************/
   132668 /*
   132669 ** 2011 Jan 27
   132670 **
   132671 ** The author disclaims copyright to this source code.  In place of
   132672 ** a legal notice, here is a blessing:
   132673 **
   132674 **    May you do good and not evil.
   132675 **    May you find forgiveness for yourself and forgive others.
   132676 **    May you share freely, never taking more than you give.
   132677 **
   132678 ******************************************************************************
   132679 **
   132680 */
   132681 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   132682 
   132683 /* #include <string.h> */
   132684 /* #include <assert.h> */
   132685 
   132686 typedef struct Fts3auxTable Fts3auxTable;
   132687 typedef struct Fts3auxCursor Fts3auxCursor;
   132688 
   132689 struct Fts3auxTable {
   132690   sqlite3_vtab base;              /* Base class used by SQLite core */
   132691   Fts3Table *pFts3Tab;
   132692 };
   132693 
   132694 struct Fts3auxCursor {
   132695   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
   132696   Fts3MultiSegReader csr;        /* Must be right after "base" */
   132697   Fts3SegFilter filter;
   132698   char *zStop;
   132699   int nStop;                      /* Byte-length of string zStop */
   132700   int iLangid;                    /* Language id to query */
   132701   int isEof;                      /* True if cursor is at EOF */
   132702   sqlite3_int64 iRowid;           /* Current rowid */
   132703 
   132704   int iCol;                       /* Current value of 'col' column */
   132705   int nStat;                      /* Size of aStat[] array */
   132706   struct Fts3auxColstats {
   132707     sqlite3_int64 nDoc;           /* 'documents' values for current csr row */
   132708     sqlite3_int64 nOcc;           /* 'occurrences' values for current csr row */
   132709   } *aStat;
   132710 };
   132711 
   132712 /*
   132713 ** Schema of the terms table.
   132714 */
   132715 #define FTS3_AUX_SCHEMA \
   132716   "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
   132717 
   132718 /*
   132719 ** This function does all the work for both the xConnect and xCreate methods.
   132720 ** These tables have no persistent representation of their own, so xConnect
   132721 ** and xCreate are identical operations.
   132722 */
   132723 static int fts3auxConnectMethod(
   132724   sqlite3 *db,                    /* Database connection */
   132725   void *pUnused,                  /* Unused */
   132726   int argc,                       /* Number of elements in argv array */
   132727   const char * const *argv,       /* xCreate/xConnect argument array */
   132728   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
   132729   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
   132730 ){
   132731   char const *zDb;                /* Name of database (e.g. "main") */
   132732   char const *zFts3;              /* Name of fts3 table */
   132733   int nDb;                        /* Result of strlen(zDb) */
   132734   int nFts3;                      /* Result of strlen(zFts3) */
   132735   int nByte;                      /* Bytes of space to allocate here */
   132736   int rc;                         /* value returned by declare_vtab() */
   132737   Fts3auxTable *p;                /* Virtual table object to return */
   132738 
   132739   UNUSED_PARAMETER(pUnused);
   132740 
   132741   /* The user should invoke this in one of two forms:
   132742   **
   132743   **     CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
   132744   **     CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
   132745   */
   132746   if( argc!=4 && argc!=5 ) goto bad_args;
   132747 
   132748   zDb = argv[1];
   132749   nDb = (int)strlen(zDb);
   132750   if( argc==5 ){
   132751     if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
   132752       zDb = argv[3];
   132753       nDb = (int)strlen(zDb);
   132754       zFts3 = argv[4];
   132755     }else{
   132756       goto bad_args;
   132757     }
   132758   }else{
   132759     zFts3 = argv[3];
   132760   }
   132761   nFts3 = (int)strlen(zFts3);
   132762 
   132763   rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
   132764   if( rc!=SQLITE_OK ) return rc;
   132765 
   132766   nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
   132767   p = (Fts3auxTable *)sqlite3_malloc(nByte);
   132768   if( !p ) return SQLITE_NOMEM;
   132769   memset(p, 0, nByte);
   132770 
   132771   p->pFts3Tab = (Fts3Table *)&p[1];
   132772   p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
   132773   p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
   132774   p->pFts3Tab->db = db;
   132775   p->pFts3Tab->nIndex = 1;
   132776 
   132777   memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
   132778   memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
   132779   sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
   132780 
   132781   *ppVtab = (sqlite3_vtab *)p;
   132782   return SQLITE_OK;
   132783 
   132784  bad_args:
   132785   *pzErr = sqlite3_mprintf("invalid arguments to fts4aux constructor");
   132786   return SQLITE_ERROR;
   132787 }
   132788 
   132789 /*
   132790 ** This function does the work for both the xDisconnect and xDestroy methods.
   132791 ** These tables have no persistent representation of their own, so xDisconnect
   132792 ** and xDestroy are identical operations.
   132793 */
   132794 static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
   132795   Fts3auxTable *p = (Fts3auxTable *)pVtab;
   132796   Fts3Table *pFts3 = p->pFts3Tab;
   132797   int i;
   132798 
   132799   /* Free any prepared statements held */
   132800   for(i=0; i<SizeofArray(pFts3->aStmt); i++){
   132801     sqlite3_finalize(pFts3->aStmt[i]);
   132802   }
   132803   sqlite3_free(pFts3->zSegmentsTbl);
   132804   sqlite3_free(p);
   132805   return SQLITE_OK;
   132806 }
   132807 
   132808 #define FTS4AUX_EQ_CONSTRAINT 1
   132809 #define FTS4AUX_GE_CONSTRAINT 2
   132810 #define FTS4AUX_LE_CONSTRAINT 4
   132811 
   132812 /*
   132813 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
   132814 */
   132815 static int fts3auxBestIndexMethod(
   132816   sqlite3_vtab *pVTab,
   132817   sqlite3_index_info *pInfo
   132818 ){
   132819   int i;
   132820   int iEq = -1;
   132821   int iGe = -1;
   132822   int iLe = -1;
   132823   int iLangid = -1;
   132824   int iNext = 1;                  /* Next free argvIndex value */
   132825 
   132826   UNUSED_PARAMETER(pVTab);
   132827 
   132828   /* This vtab delivers always results in "ORDER BY term ASC" order. */
   132829   if( pInfo->nOrderBy==1
   132830    && pInfo->aOrderBy[0].iColumn==0
   132831    && pInfo->aOrderBy[0].desc==0
   132832   ){
   132833     pInfo->orderByConsumed = 1;
   132834   }
   132835 
   132836   /* Search for equality and range constraints on the "term" column.
   132837   ** And equality constraints on the hidden "languageid" column. */
   132838   for(i=0; i<pInfo->nConstraint; i++){
   132839     if( pInfo->aConstraint[i].usable ){
   132840       int op = pInfo->aConstraint[i].op;
   132841       int iCol = pInfo->aConstraint[i].iColumn;
   132842 
   132843       if( iCol==0 ){
   132844         if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
   132845         if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
   132846         if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
   132847         if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
   132848         if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
   132849       }
   132850       if( iCol==4 ){
   132851         if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
   132852       }
   132853     }
   132854   }
   132855 
   132856   if( iEq>=0 ){
   132857     pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
   132858     pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
   132859     pInfo->estimatedCost = 5;
   132860   }else{
   132861     pInfo->idxNum = 0;
   132862     pInfo->estimatedCost = 20000;
   132863     if( iGe>=0 ){
   132864       pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
   132865       pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
   132866       pInfo->estimatedCost /= 2;
   132867     }
   132868     if( iLe>=0 ){
   132869       pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
   132870       pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
   132871       pInfo->estimatedCost /= 2;
   132872     }
   132873   }
   132874   if( iLangid>=0 ){
   132875     pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
   132876     pInfo->estimatedCost--;
   132877   }
   132878 
   132879   return SQLITE_OK;
   132880 }
   132881 
   132882 /*
   132883 ** xOpen - Open a cursor.
   132884 */
   132885 static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
   132886   Fts3auxCursor *pCsr;            /* Pointer to cursor object to return */
   132887 
   132888   UNUSED_PARAMETER(pVTab);
   132889 
   132890   pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
   132891   if( !pCsr ) return SQLITE_NOMEM;
   132892   memset(pCsr, 0, sizeof(Fts3auxCursor));
   132893 
   132894   *ppCsr = (sqlite3_vtab_cursor *)pCsr;
   132895   return SQLITE_OK;
   132896 }
   132897 
   132898 /*
   132899 ** xClose - Close a cursor.
   132900 */
   132901 static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
   132902   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
   132903   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
   132904 
   132905   sqlite3Fts3SegmentsClose(pFts3);
   132906   sqlite3Fts3SegReaderFinish(&pCsr->csr);
   132907   sqlite3_free((void *)pCsr->filter.zTerm);
   132908   sqlite3_free(pCsr->zStop);
   132909   sqlite3_free(pCsr->aStat);
   132910   sqlite3_free(pCsr);
   132911   return SQLITE_OK;
   132912 }
   132913 
   132914 static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
   132915   if( nSize>pCsr->nStat ){
   132916     struct Fts3auxColstats *aNew;
   132917     aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
   132918         sizeof(struct Fts3auxColstats) * nSize
   132919     );
   132920     if( aNew==0 ) return SQLITE_NOMEM;
   132921     memset(&aNew[pCsr->nStat], 0,
   132922         sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
   132923     );
   132924     pCsr->aStat = aNew;
   132925     pCsr->nStat = nSize;
   132926   }
   132927   return SQLITE_OK;
   132928 }
   132929 
   132930 /*
   132931 ** xNext - Advance the cursor to the next row, if any.
   132932 */
   132933 static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
   132934   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
   132935   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
   132936   int rc;
   132937 
   132938   /* Increment our pretend rowid value. */
   132939   pCsr->iRowid++;
   132940 
   132941   for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
   132942     if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
   132943   }
   132944 
   132945   rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
   132946   if( rc==SQLITE_ROW ){
   132947     int i = 0;
   132948     int nDoclist = pCsr->csr.nDoclist;
   132949     char *aDoclist = pCsr->csr.aDoclist;
   132950     int iCol;
   132951 
   132952     int eState = 0;
   132953 
   132954     if( pCsr->zStop ){
   132955       int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
   132956       int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
   132957       if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
   132958         pCsr->isEof = 1;
   132959         return SQLITE_OK;
   132960       }
   132961     }
   132962 
   132963     if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
   132964     memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
   132965     iCol = 0;
   132966 
   132967     while( i<nDoclist ){
   132968       sqlite3_int64 v = 0;
   132969 
   132970       i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
   132971       switch( eState ){
   132972         /* State 0. In this state the integer just read was a docid. */
   132973         case 0:
   132974           pCsr->aStat[0].nDoc++;
   132975           eState = 1;
   132976           iCol = 0;
   132977           break;
   132978 
   132979         /* State 1. In this state we are expecting either a 1, indicating
   132980         ** that the following integer will be a column number, or the
   132981         ** start of a position list for column 0.
   132982         **
   132983         ** The only difference between state 1 and state 2 is that if the
   132984         ** integer encountered in state 1 is not 0 or 1, then we need to
   132985         ** increment the column 0 "nDoc" count for this term.
   132986         */
   132987         case 1:
   132988           assert( iCol==0 );
   132989           if( v>1 ){
   132990             pCsr->aStat[1].nDoc++;
   132991           }
   132992           eState = 2;
   132993           /* fall through */
   132994 
   132995         case 2:
   132996           if( v==0 ){       /* 0x00. Next integer will be a docid. */
   132997             eState = 0;
   132998           }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
   132999             eState = 3;
   133000           }else{            /* 2 or greater. A position. */
   133001             pCsr->aStat[iCol+1].nOcc++;
   133002             pCsr->aStat[0].nOcc++;
   133003           }
   133004           break;
   133005 
   133006         /* State 3. The integer just read is a column number. */
   133007         default: assert( eState==3 );
   133008           iCol = (int)v;
   133009           if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
   133010           pCsr->aStat[iCol+1].nDoc++;
   133011           eState = 2;
   133012           break;
   133013       }
   133014     }
   133015 
   133016     pCsr->iCol = 0;
   133017     rc = SQLITE_OK;
   133018   }else{
   133019     pCsr->isEof = 1;
   133020   }
   133021   return rc;
   133022 }
   133023 
   133024 /*
   133025 ** xFilter - Initialize a cursor to point at the start of its data.
   133026 */
   133027 static int fts3auxFilterMethod(
   133028   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
   133029   int idxNum,                     /* Strategy index */
   133030   const char *idxStr,             /* Unused */
   133031   int nVal,                       /* Number of elements in apVal */
   133032   sqlite3_value **apVal           /* Arguments for the indexing scheme */
   133033 ){
   133034   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
   133035   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
   133036   int rc;
   133037   int isScan = 0;
   133038   int iLangVal = 0;               /* Language id to query */
   133039 
   133040   int iEq = -1;                   /* Index of term=? value in apVal */
   133041   int iGe = -1;                   /* Index of term>=? value in apVal */
   133042   int iLe = -1;                   /* Index of term<=? value in apVal */
   133043   int iLangid = -1;               /* Index of languageid=? value in apVal */
   133044   int iNext = 0;
   133045 
   133046   UNUSED_PARAMETER(nVal);
   133047   UNUSED_PARAMETER(idxStr);
   133048 
   133049   assert( idxStr==0 );
   133050   assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
   133051        || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
   133052        || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
   133053   );
   133054 
   133055   if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
   133056     iEq = iNext++;
   133057   }else{
   133058     isScan = 1;
   133059     if( idxNum & FTS4AUX_GE_CONSTRAINT ){
   133060       iGe = iNext++;
   133061     }
   133062     if( idxNum & FTS4AUX_LE_CONSTRAINT ){
   133063       iLe = iNext++;
   133064     }
   133065   }
   133066   if( iNext<nVal ){
   133067     iLangid = iNext++;
   133068   }
   133069 
   133070   /* In case this cursor is being reused, close and zero it. */
   133071   testcase(pCsr->filter.zTerm);
   133072   sqlite3Fts3SegReaderFinish(&pCsr->csr);
   133073   sqlite3_free((void *)pCsr->filter.zTerm);
   133074   sqlite3_free(pCsr->aStat);
   133075   memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
   133076 
   133077   pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
   133078   if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
   133079 
   133080   if( iEq>=0 || iGe>=0 ){
   133081     const unsigned char *zStr = sqlite3_value_text(apVal[0]);
   133082     assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
   133083     if( zStr ){
   133084       pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
   133085       pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
   133086       if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
   133087     }
   133088   }
   133089 
   133090   if( iLe>=0 ){
   133091     pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
   133092     pCsr->nStop = sqlite3_value_bytes(apVal[iLe]);
   133093     if( pCsr->zStop==0 ) return SQLITE_NOMEM;
   133094   }
   133095 
   133096   if( iLangid>=0 ){
   133097     iLangVal = sqlite3_value_int(apVal[iLangid]);
   133098 
   133099     /* If the user specified a negative value for the languageid, use zero
   133100     ** instead. This works, as the "languageid=?" constraint will also
   133101     ** be tested by the VDBE layer. The test will always be false (since
   133102     ** this module will not return a row with a negative languageid), and
   133103     ** so the overall query will return zero rows.  */
   133104     if( iLangVal<0 ) iLangVal = 0;
   133105   }
   133106   pCsr->iLangid = iLangVal;
   133107 
   133108   rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
   133109       pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
   133110   );
   133111   if( rc==SQLITE_OK ){
   133112     rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
   133113   }
   133114 
   133115   if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
   133116   return rc;
   133117 }
   133118 
   133119 /*
   133120 ** xEof - Return true if the cursor is at EOF, or false otherwise.
   133121 */
   133122 static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
   133123   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
   133124   return pCsr->isEof;
   133125 }
   133126 
   133127 /*
   133128 ** xColumn - Return a column value.
   133129 */
   133130 static int fts3auxColumnMethod(
   133131   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
   133132   sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
   133133   int iCol                        /* Index of column to read value from */
   133134 ){
   133135   Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
   133136 
   133137   assert( p->isEof==0 );
   133138   switch( iCol ){
   133139     case 0: /* term */
   133140       sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
   133141       break;
   133142 
   133143     case 1: /* col */
   133144       if( p->iCol ){
   133145         sqlite3_result_int(pCtx, p->iCol-1);
   133146       }else{
   133147         sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
   133148       }
   133149       break;
   133150 
   133151     case 2: /* documents */
   133152       sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
   133153       break;
   133154 
   133155     case 3: /* occurrences */
   133156       sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
   133157       break;
   133158 
   133159     default: /* languageid */
   133160       assert( iCol==4 );
   133161       sqlite3_result_int(pCtx, p->iLangid);
   133162       break;
   133163   }
   133164 
   133165   return SQLITE_OK;
   133166 }
   133167 
   133168 /*
   133169 ** xRowid - Return the current rowid for the cursor.
   133170 */
   133171 static int fts3auxRowidMethod(
   133172   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
   133173   sqlite_int64 *pRowid            /* OUT: Rowid value */
   133174 ){
   133175   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
   133176   *pRowid = pCsr->iRowid;
   133177   return SQLITE_OK;
   133178 }
   133179 
   133180 /*
   133181 ** Register the fts3aux module with database connection db. Return SQLITE_OK
   133182 ** if successful or an error code if sqlite3_create_module() fails.
   133183 */
   133184 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
   133185   static const sqlite3_module fts3aux_module = {
   133186      0,                           /* iVersion      */
   133187      fts3auxConnectMethod,        /* xCreate       */
   133188      fts3auxConnectMethod,        /* xConnect      */
   133189      fts3auxBestIndexMethod,      /* xBestIndex    */
   133190      fts3auxDisconnectMethod,     /* xDisconnect   */
   133191      fts3auxDisconnectMethod,     /* xDestroy      */
   133192      fts3auxOpenMethod,           /* xOpen         */
   133193      fts3auxCloseMethod,          /* xClose        */
   133194      fts3auxFilterMethod,         /* xFilter       */
   133195      fts3auxNextMethod,           /* xNext         */
   133196      fts3auxEofMethod,            /* xEof          */
   133197      fts3auxColumnMethod,         /* xColumn       */
   133198      fts3auxRowidMethod,          /* xRowid        */
   133199      0,                           /* xUpdate       */
   133200      0,                           /* xBegin        */
   133201      0,                           /* xSync         */
   133202      0,                           /* xCommit       */
   133203      0,                           /* xRollback     */
   133204      0,                           /* xFindFunction */
   133205      0,                           /* xRename       */
   133206      0,                           /* xSavepoint    */
   133207      0,                           /* xRelease      */
   133208      0                            /* xRollbackTo   */
   133209   };
   133210   int rc;                         /* Return code */
   133211 
   133212   rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
   133213   return rc;
   133214 }
   133215 
   133216 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   133217 
   133218 /************** End of fts3_aux.c ********************************************/
   133219 /************** Begin file fts3_expr.c ***************************************/
   133220 /*
   133221 ** 2008 Nov 28
   133222 **
   133223 ** The author disclaims copyright to this source code.  In place of
   133224 ** a legal notice, here is a blessing:
   133225 **
   133226 **    May you do good and not evil.
   133227 **    May you find forgiveness for yourself and forgive others.
   133228 **    May you share freely, never taking more than you give.
   133229 **
   133230 ******************************************************************************
   133231 **
   133232 ** This module contains code that implements a parser for fts3 query strings
   133233 ** (the right-hand argument to the MATCH operator). Because the supported
   133234 ** syntax is relatively simple, the whole tokenizer/parser system is
   133235 ** hand-coded.
   133236 */
   133237 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   133238 
   133239 /*
   133240 ** By default, this module parses the legacy syntax that has been
   133241 ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
   133242 ** is defined, then it uses the new syntax. The differences between
   133243 ** the new and the old syntaxes are:
   133244 **
   133245 **  a) The new syntax supports parenthesis. The old does not.
   133246 **
   133247 **  b) The new syntax supports the AND and NOT operators. The old does not.
   133248 **
   133249 **  c) The old syntax supports the "-" token qualifier. This is not
   133250 **     supported by the new syntax (it is replaced by the NOT operator).
   133251 **
   133252 **  d) When using the old syntax, the OR operator has a greater precedence
   133253 **     than an implicit AND. When using the new, both implicity and explicit
   133254 **     AND operators have a higher precedence than OR.
   133255 **
   133256 ** If compiled with SQLITE_TEST defined, then this module exports the
   133257 ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
   133258 ** to zero causes the module to use the old syntax. If it is set to
   133259 ** non-zero the new syntax is activated. This is so both syntaxes can
   133260 ** be tested using a single build of testfixture.
   133261 **
   133262 ** The following describes the syntax supported by the fts3 MATCH
   133263 ** operator in a similar format to that used by the lemon parser
   133264 ** generator. This module does not use actually lemon, it uses a
   133265 ** custom parser.
   133266 **
   133267 **   query ::= andexpr (OR andexpr)*.
   133268 **
   133269 **   andexpr ::= notexpr (AND? notexpr)*.
   133270 **
   133271 **   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
   133272 **   notexpr ::= LP query RP.
   133273 **
   133274 **   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
   133275 **
   133276 **   distance_opt ::= .
   133277 **   distance_opt ::= / INTEGER.
   133278 **
   133279 **   phrase ::= TOKEN.
   133280 **   phrase ::= COLUMN:TOKEN.
   133281 **   phrase ::= "TOKEN TOKEN TOKEN...".
   133282 */
   133283 
   133284 #ifdef SQLITE_TEST
   133285 SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
   133286 #else
   133287 # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
   133288 #  define sqlite3_fts3_enable_parentheses 1
   133289 # else
   133290 #  define sqlite3_fts3_enable_parentheses 0
   133291 # endif
   133292 #endif
   133293 
   133294 /*
   133295 ** Default span for NEAR operators.
   133296 */
   133297 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
   133298 
   133299 /* #include <string.h> */
   133300 /* #include <assert.h> */
   133301 
   133302 /*
   133303 ** isNot:
   133304 **   This variable is used by function getNextNode(). When getNextNode() is
   133305 **   called, it sets ParseContext.isNot to true if the 'next node' is a
   133306 **   FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
   133307 **   FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
   133308 **   zero.
   133309 */
   133310 typedef struct ParseContext ParseContext;
   133311 struct ParseContext {
   133312   sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
   133313   int iLangid;                        /* Language id used with tokenizer */
   133314   const char **azCol;                 /* Array of column names for fts3 table */
   133315   int bFts4;                          /* True to allow FTS4-only syntax */
   133316   int nCol;                           /* Number of entries in azCol[] */
   133317   int iDefaultCol;                    /* Default column to query */
   133318   int isNot;                          /* True if getNextNode() sees a unary - */
   133319   sqlite3_context *pCtx;              /* Write error message here */
   133320   int nNest;                          /* Number of nested brackets */
   133321 };
   133322 
   133323 /*
   133324 ** This function is equivalent to the standard isspace() function.
   133325 **
   133326 ** The standard isspace() can be awkward to use safely, because although it
   133327 ** is defined to accept an argument of type int, its behavior when passed
   133328 ** an integer that falls outside of the range of the unsigned char type
   133329 ** is undefined (and sometimes, "undefined" means segfault). This wrapper
   133330 ** is defined to accept an argument of type char, and always returns 0 for
   133331 ** any values that fall outside of the range of the unsigned char type (i.e.
   133332 ** negative values).
   133333 */
   133334 static int fts3isspace(char c){
   133335   return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
   133336 }
   133337 
   133338 /*
   133339 ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
   133340 ** zero the memory before returning a pointer to it. If unsuccessful,
   133341 ** return NULL.
   133342 */
   133343 static void *fts3MallocZero(int nByte){
   133344   void *pRet = sqlite3_malloc(nByte);
   133345   if( pRet ) memset(pRet, 0, nByte);
   133346   return pRet;
   133347 }
   133348 
   133349 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
   133350   sqlite3_tokenizer *pTokenizer,
   133351   int iLangid,
   133352   const char *z,
   133353   int n,
   133354   sqlite3_tokenizer_cursor **ppCsr
   133355 ){
   133356   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
   133357   sqlite3_tokenizer_cursor *pCsr = 0;
   133358   int rc;
   133359 
   133360   rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
   133361   assert( rc==SQLITE_OK || pCsr==0 );
   133362   if( rc==SQLITE_OK ){
   133363     pCsr->pTokenizer = pTokenizer;
   133364     if( pModule->iVersion>=1 ){
   133365       rc = pModule->xLanguageid(pCsr, iLangid);
   133366       if( rc!=SQLITE_OK ){
   133367         pModule->xClose(pCsr);
   133368         pCsr = 0;
   133369       }
   133370     }
   133371   }
   133372   *ppCsr = pCsr;
   133373   return rc;
   133374 }
   133375 
   133376 /*
   133377 ** Function getNextNode(), which is called by fts3ExprParse(), may itself
   133378 ** call fts3ExprParse(). So this forward declaration is required.
   133379 */
   133380 static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
   133381 
   133382 /*
   133383 ** Extract the next token from buffer z (length n) using the tokenizer
   133384 ** and other information (column names etc.) in pParse. Create an Fts3Expr
   133385 ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
   133386 ** single token and set *ppExpr to point to it. If the end of the buffer is
   133387 ** reached before a token is found, set *ppExpr to zero. It is the
   133388 ** responsibility of the caller to eventually deallocate the allocated
   133389 ** Fts3Expr structure (if any) by passing it to sqlite3_free().
   133390 **
   133391 ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
   133392 ** fails.
   133393 */
   133394 static int getNextToken(
   133395   ParseContext *pParse,                   /* fts3 query parse context */
   133396   int iCol,                               /* Value for Fts3Phrase.iColumn */
   133397   const char *z, int n,                   /* Input string */
   133398   Fts3Expr **ppExpr,                      /* OUT: expression */
   133399   int *pnConsumed                         /* OUT: Number of bytes consumed */
   133400 ){
   133401   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
   133402   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
   133403   int rc;
   133404   sqlite3_tokenizer_cursor *pCursor;
   133405   Fts3Expr *pRet = 0;
   133406   int i = 0;
   133407 
   133408   /* Set variable i to the maximum number of bytes of input to tokenize. */
   133409   for(i=0; i<n; i++){
   133410     if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break;
   133411     if( z[i]=='*' || z[i]=='"' ) break;
   133412   }
   133413 
   133414   *pnConsumed = i;
   133415   rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor);
   133416   if( rc==SQLITE_OK ){
   133417     const char *zToken;
   133418     int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
   133419     int nByte;                               /* total space to allocate */
   133420 
   133421     rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
   133422     if( rc==SQLITE_OK ){
   133423       nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
   133424       pRet = (Fts3Expr *)fts3MallocZero(nByte);
   133425       if( !pRet ){
   133426         rc = SQLITE_NOMEM;
   133427       }else{
   133428         pRet->eType = FTSQUERY_PHRASE;
   133429         pRet->pPhrase = (Fts3Phrase *)&pRet[1];
   133430         pRet->pPhrase->nToken = 1;
   133431         pRet->pPhrase->iColumn = iCol;
   133432         pRet->pPhrase->aToken[0].n = nToken;
   133433         pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
   133434         memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
   133435 
   133436         if( iEnd<n && z[iEnd]=='*' ){
   133437           pRet->pPhrase->aToken[0].isPrefix = 1;
   133438           iEnd++;
   133439         }
   133440 
   133441         while( 1 ){
   133442           if( !sqlite3_fts3_enable_parentheses
   133443            && iStart>0 && z[iStart-1]=='-'
   133444           ){
   133445             pParse->isNot = 1;
   133446             iStart--;
   133447           }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
   133448             pRet->pPhrase->aToken[0].bFirst = 1;
   133449             iStart--;
   133450           }else{
   133451             break;
   133452           }
   133453         }
   133454 
   133455       }
   133456       *pnConsumed = iEnd;
   133457     }else if( i && rc==SQLITE_DONE ){
   133458       rc = SQLITE_OK;
   133459     }
   133460 
   133461     pModule->xClose(pCursor);
   133462   }
   133463 
   133464   *ppExpr = pRet;
   133465   return rc;
   133466 }
   133467 
   133468 
   133469 /*
   133470 ** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
   133471 ** then free the old allocation.
   133472 */
   133473 static void *fts3ReallocOrFree(void *pOrig, int nNew){
   133474   void *pRet = sqlite3_realloc(pOrig, nNew);
   133475   if( !pRet ){
   133476     sqlite3_free(pOrig);
   133477   }
   133478   return pRet;
   133479 }
   133480 
   133481 /*
   133482 ** Buffer zInput, length nInput, contains the contents of a quoted string
   133483 ** that appeared as part of an fts3 query expression. Neither quote character
   133484 ** is included in the buffer. This function attempts to tokenize the entire
   133485 ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
   133486 ** containing the results.
   133487 **
   133488 ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
   133489 ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
   133490 ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
   133491 ** to 0.
   133492 */
   133493 static int getNextString(
   133494   ParseContext *pParse,                   /* fts3 query parse context */
   133495   const char *zInput, int nInput,         /* Input string */
   133496   Fts3Expr **ppExpr                       /* OUT: expression */
   133497 ){
   133498   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
   133499   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
   133500   int rc;
   133501   Fts3Expr *p = 0;
   133502   sqlite3_tokenizer_cursor *pCursor = 0;
   133503   char *zTemp = 0;
   133504   int nTemp = 0;
   133505 
   133506   const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
   133507   int nToken = 0;
   133508 
   133509   /* The final Fts3Expr data structure, including the Fts3Phrase,
   133510   ** Fts3PhraseToken structures token buffers are all stored as a single
   133511   ** allocation so that the expression can be freed with a single call to
   133512   ** sqlite3_free(). Setting this up requires a two pass approach.
   133513   **
   133514   ** The first pass, in the block below, uses a tokenizer cursor to iterate
   133515   ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
   133516   ** to assemble data in two dynamic buffers:
   133517   **
   133518   **   Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
   133519   **             structure, followed by the array of Fts3PhraseToken
   133520   **             structures. This pass only populates the Fts3PhraseToken array.
   133521   **
   133522   **   Buffer zTemp: Contains copies of all tokens.
   133523   **
   133524   ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
   133525   ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
   133526   ** structures.
   133527   */
   133528   rc = sqlite3Fts3OpenTokenizer(
   133529       pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
   133530   if( rc==SQLITE_OK ){
   133531     int ii;
   133532     for(ii=0; rc==SQLITE_OK; ii++){
   133533       const char *zByte;
   133534       int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
   133535       rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
   133536       if( rc==SQLITE_OK ){
   133537         Fts3PhraseToken *pToken;
   133538 
   133539         p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
   133540         if( !p ) goto no_mem;
   133541 
   133542         zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
   133543         if( !zTemp ) goto no_mem;
   133544 
   133545         assert( nToken==ii );
   133546         pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
   133547         memset(pToken, 0, sizeof(Fts3PhraseToken));
   133548 
   133549         memcpy(&zTemp[nTemp], zByte, nByte);
   133550         nTemp += nByte;
   133551 
   133552         pToken->n = nByte;
   133553         pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
   133554         pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
   133555         nToken = ii+1;
   133556       }
   133557     }
   133558 
   133559     pModule->xClose(pCursor);
   133560     pCursor = 0;
   133561   }
   133562 
   133563   if( rc==SQLITE_DONE ){
   133564     int jj;
   133565     char *zBuf = 0;
   133566 
   133567     p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
   133568     if( !p ) goto no_mem;
   133569     memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
   133570     p->eType = FTSQUERY_PHRASE;
   133571     p->pPhrase = (Fts3Phrase *)&p[1];
   133572     p->pPhrase->iColumn = pParse->iDefaultCol;
   133573     p->pPhrase->nToken = nToken;
   133574 
   133575     zBuf = (char *)&p->pPhrase->aToken[nToken];
   133576     if( zTemp ){
   133577       memcpy(zBuf, zTemp, nTemp);
   133578       sqlite3_free(zTemp);
   133579     }else{
   133580       assert( nTemp==0 );
   133581     }
   133582 
   133583     for(jj=0; jj<p->pPhrase->nToken; jj++){
   133584       p->pPhrase->aToken[jj].z = zBuf;
   133585       zBuf += p->pPhrase->aToken[jj].n;
   133586     }
   133587     rc = SQLITE_OK;
   133588   }
   133589 
   133590   *ppExpr = p;
   133591   return rc;
   133592 no_mem:
   133593 
   133594   if( pCursor ){
   133595     pModule->xClose(pCursor);
   133596   }
   133597   sqlite3_free(zTemp);
   133598   sqlite3_free(p);
   133599   *ppExpr = 0;
   133600   return SQLITE_NOMEM;
   133601 }
   133602 
   133603 /*
   133604 ** The output variable *ppExpr is populated with an allocated Fts3Expr
   133605 ** structure, or set to 0 if the end of the input buffer is reached.
   133606 **
   133607 ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
   133608 ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
   133609 ** If SQLITE_ERROR is returned, pContext is populated with an error message.
   133610 */
   133611 static int getNextNode(
   133612   ParseContext *pParse,                   /* fts3 query parse context */
   133613   const char *z, int n,                   /* Input string */
   133614   Fts3Expr **ppExpr,                      /* OUT: expression */
   133615   int *pnConsumed                         /* OUT: Number of bytes consumed */
   133616 ){
   133617   static const struct Fts3Keyword {
   133618     char *z;                              /* Keyword text */
   133619     unsigned char n;                      /* Length of the keyword */
   133620     unsigned char parenOnly;              /* Only valid in paren mode */
   133621     unsigned char eType;                  /* Keyword code */
   133622   } aKeyword[] = {
   133623     { "OR" ,  2, 0, FTSQUERY_OR   },
   133624     { "AND",  3, 1, FTSQUERY_AND  },
   133625     { "NOT",  3, 1, FTSQUERY_NOT  },
   133626     { "NEAR", 4, 0, FTSQUERY_NEAR }
   133627   };
   133628   int ii;
   133629   int iCol;
   133630   int iColLen;
   133631   int rc;
   133632   Fts3Expr *pRet = 0;
   133633 
   133634   const char *zInput = z;
   133635   int nInput = n;
   133636 
   133637   pParse->isNot = 0;
   133638 
   133639   /* Skip over any whitespace before checking for a keyword, an open or
   133640   ** close bracket, or a quoted string.
   133641   */
   133642   while( nInput>0 && fts3isspace(*zInput) ){
   133643     nInput--;
   133644     zInput++;
   133645   }
   133646   if( nInput==0 ){
   133647     return SQLITE_DONE;
   133648   }
   133649 
   133650   /* See if we are dealing with a keyword. */
   133651   for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
   133652     const struct Fts3Keyword *pKey = &aKeyword[ii];
   133653 
   133654     if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
   133655       continue;
   133656     }
   133657 
   133658     if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
   133659       int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
   133660       int nKey = pKey->n;
   133661       char cNext;
   133662 
   133663       /* If this is a "NEAR" keyword, check for an explicit nearness. */
   133664       if( pKey->eType==FTSQUERY_NEAR ){
   133665         assert( nKey==4 );
   133666         if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
   133667           nNear = 0;
   133668           for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
   133669             nNear = nNear * 10 + (zInput[nKey] - '0');
   133670           }
   133671         }
   133672       }
   133673 
   133674       /* At this point this is probably a keyword. But for that to be true,
   133675       ** the next byte must contain either whitespace, an open or close
   133676       ** parenthesis, a quote character, or EOF.
   133677       */
   133678       cNext = zInput[nKey];
   133679       if( fts3isspace(cNext)
   133680        || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
   133681       ){
   133682         pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
   133683         if( !pRet ){
   133684           return SQLITE_NOMEM;
   133685         }
   133686         pRet->eType = pKey->eType;
   133687         pRet->nNear = nNear;
   133688         *ppExpr = pRet;
   133689         *pnConsumed = (int)((zInput - z) + nKey);
   133690         return SQLITE_OK;
   133691       }
   133692 
   133693       /* Turns out that wasn't a keyword after all. This happens if the
   133694       ** user has supplied a token such as "ORacle". Continue.
   133695       */
   133696     }
   133697   }
   133698 
   133699   /* See if we are dealing with a quoted phrase. If this is the case, then
   133700   ** search for the closing quote and pass the whole string to getNextString()
   133701   ** for processing. This is easy to do, as fts3 has no syntax for escaping
   133702   ** a quote character embedded in a string.
   133703   */
   133704   if( *zInput=='"' ){
   133705     for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
   133706     *pnConsumed = (int)((zInput - z) + ii + 1);
   133707     if( ii==nInput ){
   133708       return SQLITE_ERROR;
   133709     }
   133710     return getNextString(pParse, &zInput[1], ii-1, ppExpr);
   133711   }
   133712 
   133713   if( sqlite3_fts3_enable_parentheses ){
   133714     if( *zInput=='(' ){
   133715       int nConsumed = 0;
   133716       pParse->nNest++;
   133717       rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed);
   133718       if( rc==SQLITE_OK && !*ppExpr ){ rc = SQLITE_DONE; }
   133719       *pnConsumed = (int)(zInput - z) + 1 + nConsumed;
   133720       return rc;
   133721     }else if( *zInput==')' ){
   133722       pParse->nNest--;
   133723       *pnConsumed = (int)((zInput - z) + 1);
   133724       *ppExpr = 0;
   133725       return SQLITE_DONE;
   133726     }
   133727   }
   133728 
   133729   /* If control flows to this point, this must be a regular token, or
   133730   ** the end of the input. Read a regular token using the sqlite3_tokenizer
   133731   ** interface. Before doing so, figure out if there is an explicit
   133732   ** column specifier for the token.
   133733   **
   133734   ** TODO: Strangely, it is not possible to associate a column specifier
   133735   ** with a quoted phrase, only with a single token. Not sure if this was
   133736   ** an implementation artifact or an intentional decision when fts3 was
   133737   ** first implemented. Whichever it was, this module duplicates the
   133738   ** limitation.
   133739   */
   133740   iCol = pParse->iDefaultCol;
   133741   iColLen = 0;
   133742   for(ii=0; ii<pParse->nCol; ii++){
   133743     const char *zStr = pParse->azCol[ii];
   133744     int nStr = (int)strlen(zStr);
   133745     if( nInput>nStr && zInput[nStr]==':'
   133746      && sqlite3_strnicmp(zStr, zInput, nStr)==0
   133747     ){
   133748       iCol = ii;
   133749       iColLen = (int)((zInput - z) + nStr + 1);
   133750       break;
   133751     }
   133752   }
   133753   rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
   133754   *pnConsumed += iColLen;
   133755   return rc;
   133756 }
   133757 
   133758 /*
   133759 ** The argument is an Fts3Expr structure for a binary operator (any type
   133760 ** except an FTSQUERY_PHRASE). Return an integer value representing the
   133761 ** precedence of the operator. Lower values have a higher precedence (i.e.
   133762 ** group more tightly). For example, in the C language, the == operator
   133763 ** groups more tightly than ||, and would therefore have a higher precedence.
   133764 **
   133765 ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
   133766 ** is defined), the order of the operators in precedence from highest to
   133767 ** lowest is:
   133768 **
   133769 **   NEAR
   133770 **   NOT
   133771 **   AND (including implicit ANDs)
   133772 **   OR
   133773 **
   133774 ** Note that when using the old query syntax, the OR operator has a higher
   133775 ** precedence than the AND operator.
   133776 */
   133777 static int opPrecedence(Fts3Expr *p){
   133778   assert( p->eType!=FTSQUERY_PHRASE );
   133779   if( sqlite3_fts3_enable_parentheses ){
   133780     return p->eType;
   133781   }else if( p->eType==FTSQUERY_NEAR ){
   133782     return 1;
   133783   }else if( p->eType==FTSQUERY_OR ){
   133784     return 2;
   133785   }
   133786   assert( p->eType==FTSQUERY_AND );
   133787   return 3;
   133788 }
   133789 
   133790 /*
   133791 ** Argument ppHead contains a pointer to the current head of a query
   133792 ** expression tree being parsed. pPrev is the expression node most recently
   133793 ** inserted into the tree. This function adds pNew, which is always a binary
   133794 ** operator node, into the expression tree based on the relative precedence
   133795 ** of pNew and the existing nodes of the tree. This may result in the head
   133796 ** of the tree changing, in which case *ppHead is set to the new root node.
   133797 */
   133798 static void insertBinaryOperator(
   133799   Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
   133800   Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
   133801   Fts3Expr *pNew           /* New binary node to insert into expression tree */
   133802 ){
   133803   Fts3Expr *pSplit = pPrev;
   133804   while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
   133805     pSplit = pSplit->pParent;
   133806   }
   133807 
   133808   if( pSplit->pParent ){
   133809     assert( pSplit->pParent->pRight==pSplit );
   133810     pSplit->pParent->pRight = pNew;
   133811     pNew->pParent = pSplit->pParent;
   133812   }else{
   133813     *ppHead = pNew;
   133814   }
   133815   pNew->pLeft = pSplit;
   133816   pSplit->pParent = pNew;
   133817 }
   133818 
   133819 /*
   133820 ** Parse the fts3 query expression found in buffer z, length n. This function
   133821 ** returns either when the end of the buffer is reached or an unmatched
   133822 ** closing bracket - ')' - is encountered.
   133823 **
   133824 ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
   133825 ** parsed form of the expression and *pnConsumed is set to the number of
   133826 ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
   133827 ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
   133828 */
   133829 static int fts3ExprParse(
   133830   ParseContext *pParse,                   /* fts3 query parse context */
   133831   const char *z, int n,                   /* Text of MATCH query */
   133832   Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
   133833   int *pnConsumed                         /* OUT: Number of bytes consumed */
   133834 ){
   133835   Fts3Expr *pRet = 0;
   133836   Fts3Expr *pPrev = 0;
   133837   Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
   133838   int nIn = n;
   133839   const char *zIn = z;
   133840   int rc = SQLITE_OK;
   133841   int isRequirePhrase = 1;
   133842 
   133843   while( rc==SQLITE_OK ){
   133844     Fts3Expr *p = 0;
   133845     int nByte = 0;
   133846 
   133847     rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
   133848     assert( nByte>0 || (rc!=SQLITE_OK && p==0) );
   133849     if( rc==SQLITE_OK ){
   133850       if( p ){
   133851         int isPhrase;
   133852 
   133853         if( !sqlite3_fts3_enable_parentheses
   133854             && p->eType==FTSQUERY_PHRASE && pParse->isNot
   133855         ){
   133856           /* Create an implicit NOT operator. */
   133857           Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
   133858           if( !pNot ){
   133859             sqlite3Fts3ExprFree(p);
   133860             rc = SQLITE_NOMEM;
   133861             goto exprparse_out;
   133862           }
   133863           pNot->eType = FTSQUERY_NOT;
   133864           pNot->pRight = p;
   133865           p->pParent = pNot;
   133866           if( pNotBranch ){
   133867             pNot->pLeft = pNotBranch;
   133868             pNotBranch->pParent = pNot;
   133869           }
   133870           pNotBranch = pNot;
   133871           p = pPrev;
   133872         }else{
   133873           int eType = p->eType;
   133874           isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
   133875 
   133876           /* The isRequirePhrase variable is set to true if a phrase or
   133877           ** an expression contained in parenthesis is required. If a
   133878           ** binary operator (AND, OR, NOT or NEAR) is encounted when
   133879           ** isRequirePhrase is set, this is a syntax error.
   133880           */
   133881           if( !isPhrase && isRequirePhrase ){
   133882             sqlite3Fts3ExprFree(p);
   133883             rc = SQLITE_ERROR;
   133884             goto exprparse_out;
   133885           }
   133886 
   133887           if( isPhrase && !isRequirePhrase ){
   133888             /* Insert an implicit AND operator. */
   133889             Fts3Expr *pAnd;
   133890             assert( pRet && pPrev );
   133891             pAnd = fts3MallocZero(sizeof(Fts3Expr));
   133892             if( !pAnd ){
   133893               sqlite3Fts3ExprFree(p);
   133894               rc = SQLITE_NOMEM;
   133895               goto exprparse_out;
   133896             }
   133897             pAnd->eType = FTSQUERY_AND;
   133898             insertBinaryOperator(&pRet, pPrev, pAnd);
   133899             pPrev = pAnd;
   133900           }
   133901 
   133902           /* This test catches attempts to make either operand of a NEAR
   133903            ** operator something other than a phrase. For example, either of
   133904            ** the following:
   133905            **
   133906            **    (bracketed expression) NEAR phrase
   133907            **    phrase NEAR (bracketed expression)
   133908            **
   133909            ** Return an error in either case.
   133910            */
   133911           if( pPrev && (
   133912             (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
   133913          || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
   133914           )){
   133915             sqlite3Fts3ExprFree(p);
   133916             rc = SQLITE_ERROR;
   133917             goto exprparse_out;
   133918           }
   133919 
   133920           if( isPhrase ){
   133921             if( pRet ){
   133922               assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
   133923               pPrev->pRight = p;
   133924               p->pParent = pPrev;
   133925             }else{
   133926               pRet = p;
   133927             }
   133928           }else{
   133929             insertBinaryOperator(&pRet, pPrev, p);
   133930           }
   133931           isRequirePhrase = !isPhrase;
   133932         }
   133933         pPrev = p;
   133934       }
   133935       assert( nByte>0 );
   133936     }
   133937     assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
   133938     nIn -= nByte;
   133939     zIn += nByte;
   133940   }
   133941 
   133942   if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
   133943     rc = SQLITE_ERROR;
   133944   }
   133945 
   133946   if( rc==SQLITE_DONE ){
   133947     rc = SQLITE_OK;
   133948     if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
   133949       if( !pRet ){
   133950         rc = SQLITE_ERROR;
   133951       }else{
   133952         Fts3Expr *pIter = pNotBranch;
   133953         while( pIter->pLeft ){
   133954           pIter = pIter->pLeft;
   133955         }
   133956         pIter->pLeft = pRet;
   133957         pRet->pParent = pIter;
   133958         pRet = pNotBranch;
   133959       }
   133960     }
   133961   }
   133962   *pnConsumed = n - nIn;
   133963 
   133964 exprparse_out:
   133965   if( rc!=SQLITE_OK ){
   133966     sqlite3Fts3ExprFree(pRet);
   133967     sqlite3Fts3ExprFree(pNotBranch);
   133968     pRet = 0;
   133969   }
   133970   *ppExpr = pRet;
   133971   return rc;
   133972 }
   133973 
   133974 /*
   133975 ** Return SQLITE_ERROR if the maximum depth of the expression tree passed
   133976 ** as the only argument is more than nMaxDepth.
   133977 */
   133978 static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
   133979   int rc = SQLITE_OK;
   133980   if( p ){
   133981     if( nMaxDepth<0 ){
   133982       rc = SQLITE_TOOBIG;
   133983     }else{
   133984       rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
   133985       if( rc==SQLITE_OK ){
   133986         rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
   133987       }
   133988     }
   133989   }
   133990   return rc;
   133991 }
   133992 
   133993 /*
   133994 ** This function attempts to transform the expression tree at (*pp) to
   133995 ** an equivalent but more balanced form. The tree is modified in place.
   133996 ** If successful, SQLITE_OK is returned and (*pp) set to point to the
   133997 ** new root expression node.
   133998 **
   133999 ** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
   134000 **
   134001 ** Otherwise, if an error occurs, an SQLite error code is returned and
   134002 ** expression (*pp) freed.
   134003 */
   134004 static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
   134005   int rc = SQLITE_OK;             /* Return code */
   134006   Fts3Expr *pRoot = *pp;          /* Initial root node */
   134007   Fts3Expr *pFree = 0;            /* List of free nodes. Linked by pParent. */
   134008   int eType = pRoot->eType;       /* Type of node in this tree */
   134009 
   134010   if( nMaxDepth==0 ){
   134011     rc = SQLITE_ERROR;
   134012   }
   134013 
   134014   if( rc==SQLITE_OK && (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
   134015     Fts3Expr **apLeaf;
   134016     apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
   134017     if( 0==apLeaf ){
   134018       rc = SQLITE_NOMEM;
   134019     }else{
   134020       memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
   134021     }
   134022 
   134023     if( rc==SQLITE_OK ){
   134024       int i;
   134025       Fts3Expr *p;
   134026 
   134027       /* Set $p to point to the left-most leaf in the tree of eType nodes. */
   134028       for(p=pRoot; p->eType==eType; p=p->pLeft){
   134029         assert( p->pParent==0 || p->pParent->pLeft==p );
   134030         assert( p->pLeft && p->pRight );
   134031       }
   134032 
   134033       /* This loop runs once for each leaf in the tree of eType nodes. */
   134034       while( 1 ){
   134035         int iLvl;
   134036         Fts3Expr *pParent = p->pParent;     /* Current parent of p */
   134037 
   134038         assert( pParent==0 || pParent->pLeft==p );
   134039         p->pParent = 0;
   134040         if( pParent ){
   134041           pParent->pLeft = 0;
   134042         }else{
   134043           pRoot = 0;
   134044         }
   134045         rc = fts3ExprBalance(&p, nMaxDepth-1);
   134046         if( rc!=SQLITE_OK ) break;
   134047 
   134048         for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
   134049           if( apLeaf[iLvl]==0 ){
   134050             apLeaf[iLvl] = p;
   134051             p = 0;
   134052           }else{
   134053             assert( pFree );
   134054             pFree->pLeft = apLeaf[iLvl];
   134055             pFree->pRight = p;
   134056             pFree->pLeft->pParent = pFree;
   134057             pFree->pRight->pParent = pFree;
   134058 
   134059             p = pFree;
   134060             pFree = pFree->pParent;
   134061             p->pParent = 0;
   134062             apLeaf[iLvl] = 0;
   134063           }
   134064         }
   134065         if( p ){
   134066           sqlite3Fts3ExprFree(p);
   134067           rc = SQLITE_TOOBIG;
   134068           break;
   134069         }
   134070 
   134071         /* If that was the last leaf node, break out of the loop */
   134072         if( pParent==0 ) break;
   134073 
   134074         /* Set $p to point to the next leaf in the tree of eType nodes */
   134075         for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
   134076 
   134077         /* Remove pParent from the original tree. */
   134078         assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
   134079         pParent->pRight->pParent = pParent->pParent;
   134080         if( pParent->pParent ){
   134081           pParent->pParent->pLeft = pParent->pRight;
   134082         }else{
   134083           assert( pParent==pRoot );
   134084           pRoot = pParent->pRight;
   134085         }
   134086 
   134087         /* Link pParent into the free node list. It will be used as an
   134088         ** internal node of the new tree.  */
   134089         pParent->pParent = pFree;
   134090         pFree = pParent;
   134091       }
   134092 
   134093       if( rc==SQLITE_OK ){
   134094         p = 0;
   134095         for(i=0; i<nMaxDepth; i++){
   134096           if( apLeaf[i] ){
   134097             if( p==0 ){
   134098               p = apLeaf[i];
   134099               p->pParent = 0;
   134100             }else{
   134101               assert( pFree!=0 );
   134102               pFree->pRight = p;
   134103               pFree->pLeft = apLeaf[i];
   134104               pFree->pLeft->pParent = pFree;
   134105               pFree->pRight->pParent = pFree;
   134106 
   134107               p = pFree;
   134108               pFree = pFree->pParent;
   134109               p->pParent = 0;
   134110             }
   134111           }
   134112         }
   134113         pRoot = p;
   134114       }else{
   134115         /* An error occurred. Delete the contents of the apLeaf[] array
   134116         ** and pFree list. Everything else is cleaned up by the call to
   134117         ** sqlite3Fts3ExprFree(pRoot) below.  */
   134118         Fts3Expr *pDel;
   134119         for(i=0; i<nMaxDepth; i++){
   134120           sqlite3Fts3ExprFree(apLeaf[i]);
   134121         }
   134122         while( (pDel=pFree)!=0 ){
   134123           pFree = pDel->pParent;
   134124           sqlite3_free(pDel);
   134125         }
   134126       }
   134127 
   134128       assert( pFree==0 );
   134129       sqlite3_free( apLeaf );
   134130     }
   134131   }
   134132 
   134133   if( rc!=SQLITE_OK ){
   134134     sqlite3Fts3ExprFree(pRoot);
   134135     pRoot = 0;
   134136   }
   134137   *pp = pRoot;
   134138   return rc;
   134139 }
   134140 
   134141 /*
   134142 ** This function is similar to sqlite3Fts3ExprParse(), with the following
   134143 ** differences:
   134144 **
   134145 **   1. It does not do expression rebalancing.
   134146 **   2. It does not check that the expression does not exceed the
   134147 **      maximum allowable depth.
   134148 **   3. Even if it fails, *ppExpr may still be set to point to an
   134149 **      expression tree. It should be deleted using sqlite3Fts3ExprFree()
   134150 **      in this case.
   134151 */
   134152 static int fts3ExprParseUnbalanced(
   134153   sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
   134154   int iLangid,                        /* Language id for tokenizer */
   134155   char **azCol,                       /* Array of column names for fts3 table */
   134156   int bFts4,                          /* True to allow FTS4-only syntax */
   134157   int nCol,                           /* Number of entries in azCol[] */
   134158   int iDefaultCol,                    /* Default column to query */
   134159   const char *z, int n,               /* Text of MATCH query */
   134160   Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
   134161 ){
   134162   int nParsed;
   134163   int rc;
   134164   ParseContext sParse;
   134165 
   134166   memset(&sParse, 0, sizeof(ParseContext));
   134167   sParse.pTokenizer = pTokenizer;
   134168   sParse.iLangid = iLangid;
   134169   sParse.azCol = (const char **)azCol;
   134170   sParse.nCol = nCol;
   134171   sParse.iDefaultCol = iDefaultCol;
   134172   sParse.bFts4 = bFts4;
   134173   if( z==0 ){
   134174     *ppExpr = 0;
   134175     return SQLITE_OK;
   134176   }
   134177   if( n<0 ){
   134178     n = (int)strlen(z);
   134179   }
   134180   rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
   134181   assert( rc==SQLITE_OK || *ppExpr==0 );
   134182 
   134183   /* Check for mismatched parenthesis */
   134184   if( rc==SQLITE_OK && sParse.nNest ){
   134185     rc = SQLITE_ERROR;
   134186   }
   134187 
   134188   return rc;
   134189 }
   134190 
   134191 /*
   134192 ** Parameters z and n contain a pointer to and length of a buffer containing
   134193 ** an fts3 query expression, respectively. This function attempts to parse the
   134194 ** query expression and create a tree of Fts3Expr structures representing the
   134195 ** parsed expression. If successful, *ppExpr is set to point to the head
   134196 ** of the parsed expression tree and SQLITE_OK is returned. If an error
   134197 ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
   134198 ** error) is returned and *ppExpr is set to 0.
   134199 **
   134200 ** If parameter n is a negative number, then z is assumed to point to a
   134201 ** nul-terminated string and the length is determined using strlen().
   134202 **
   134203 ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
   134204 ** use to normalize query tokens while parsing the expression. The azCol[]
   134205 ** array, which is assumed to contain nCol entries, should contain the names
   134206 ** of each column in the target fts3 table, in order from left to right.
   134207 ** Column names must be nul-terminated strings.
   134208 **
   134209 ** The iDefaultCol parameter should be passed the index of the table column
   134210 ** that appears on the left-hand-side of the MATCH operator (the default
   134211 ** column to match against for tokens for which a column name is not explicitly
   134212 ** specified as part of the query string), or -1 if tokens may by default
   134213 ** match any table column.
   134214 */
   134215 SQLITE_PRIVATE int sqlite3Fts3ExprParse(
   134216   sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
   134217   int iLangid,                        /* Language id for tokenizer */
   134218   char **azCol,                       /* Array of column names for fts3 table */
   134219   int bFts4,                          /* True to allow FTS4-only syntax */
   134220   int nCol,                           /* Number of entries in azCol[] */
   134221   int iDefaultCol,                    /* Default column to query */
   134222   const char *z, int n,               /* Text of MATCH query */
   134223   Fts3Expr **ppExpr,                  /* OUT: Parsed query structure */
   134224   char **pzErr                        /* OUT: Error message (sqlite3_malloc) */
   134225 ){
   134226   int rc = fts3ExprParseUnbalanced(
   134227       pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
   134228   );
   134229 
   134230   /* Rebalance the expression. And check that its depth does not exceed
   134231   ** SQLITE_FTS3_MAX_EXPR_DEPTH.  */
   134232   if( rc==SQLITE_OK && *ppExpr ){
   134233     rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
   134234     if( rc==SQLITE_OK ){
   134235       rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
   134236     }
   134237   }
   134238 
   134239   if( rc!=SQLITE_OK ){
   134240     sqlite3Fts3ExprFree(*ppExpr);
   134241     *ppExpr = 0;
   134242     if( rc==SQLITE_TOOBIG ){
   134243       *pzErr = sqlite3_mprintf(
   134244           "FTS expression tree is too large (maximum depth %d)",
   134245           SQLITE_FTS3_MAX_EXPR_DEPTH
   134246       );
   134247       rc = SQLITE_ERROR;
   134248     }else if( rc==SQLITE_ERROR ){
   134249       *pzErr = sqlite3_mprintf("malformed MATCH expression: [%s]", z);
   134250     }
   134251   }
   134252 
   134253   return rc;
   134254 }
   134255 
   134256 /*
   134257 ** Free a single node of an expression tree.
   134258 */
   134259 static void fts3FreeExprNode(Fts3Expr *p){
   134260   assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
   134261   sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
   134262   sqlite3_free(p->aMI);
   134263   sqlite3_free(p);
   134264 }
   134265 
   134266 /*
   134267 ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
   134268 **
   134269 ** This function would be simpler if it recursively called itself. But
   134270 ** that would mean passing a sufficiently large expression to ExprParse()
   134271 ** could cause a stack overflow.
   134272 */
   134273 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
   134274   Fts3Expr *p;
   134275   assert( pDel==0 || pDel->pParent==0 );
   134276   for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
   134277     assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
   134278   }
   134279   while( p ){
   134280     Fts3Expr *pParent = p->pParent;
   134281     fts3FreeExprNode(p);
   134282     if( pParent && p==pParent->pLeft && pParent->pRight ){
   134283       p = pParent->pRight;
   134284       while( p && (p->pLeft || p->pRight) ){
   134285         assert( p==p->pParent->pRight || p==p->pParent->pLeft );
   134286         p = (p->pLeft ? p->pLeft : p->pRight);
   134287       }
   134288     }else{
   134289       p = pParent;
   134290     }
   134291   }
   134292 }
   134293 
   134294 /****************************************************************************
   134295 *****************************************************************************
   134296 ** Everything after this point is just test code.
   134297 */
   134298 
   134299 #ifdef SQLITE_TEST
   134300 
   134301 /* #include <stdio.h> */
   134302 
   134303 /*
   134304 ** Function to query the hash-table of tokenizers (see README.tokenizers).
   134305 */
   134306 static int queryTestTokenizer(
   134307   sqlite3 *db,
   134308   const char *zName,
   134309   const sqlite3_tokenizer_module **pp
   134310 ){
   134311   int rc;
   134312   sqlite3_stmt *pStmt;
   134313   const char zSql[] = "SELECT fts3_tokenizer(?)";
   134314 
   134315   *pp = 0;
   134316   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
   134317   if( rc!=SQLITE_OK ){
   134318     return rc;
   134319   }
   134320 
   134321   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
   134322   if( SQLITE_ROW==sqlite3_step(pStmt) ){
   134323     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
   134324       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
   134325     }
   134326   }
   134327 
   134328   return sqlite3_finalize(pStmt);
   134329 }
   134330 
   134331 /*
   134332 ** Return a pointer to a buffer containing a text representation of the
   134333 ** expression passed as the first argument. The buffer is obtained from
   134334 ** sqlite3_malloc(). It is the responsibility of the caller to use
   134335 ** sqlite3_free() to release the memory. If an OOM condition is encountered,
   134336 ** NULL is returned.
   134337 **
   134338 ** If the second argument is not NULL, then its contents are prepended to
   134339 ** the returned expression text and then freed using sqlite3_free().
   134340 */
   134341 static char *exprToString(Fts3Expr *pExpr, char *zBuf){
   134342   if( pExpr==0 ){
   134343     return sqlite3_mprintf("");
   134344   }
   134345   switch( pExpr->eType ){
   134346     case FTSQUERY_PHRASE: {
   134347       Fts3Phrase *pPhrase = pExpr->pPhrase;
   134348       int i;
   134349       zBuf = sqlite3_mprintf(
   134350           "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
   134351       for(i=0; zBuf && i<pPhrase->nToken; i++){
   134352         zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
   134353             pPhrase->aToken[i].n, pPhrase->aToken[i].z,
   134354             (pPhrase->aToken[i].isPrefix?"+":"")
   134355         );
   134356       }
   134357       return zBuf;
   134358     }
   134359 
   134360     case FTSQUERY_NEAR:
   134361       zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
   134362       break;
   134363     case FTSQUERY_NOT:
   134364       zBuf = sqlite3_mprintf("%zNOT ", zBuf);
   134365       break;
   134366     case FTSQUERY_AND:
   134367       zBuf = sqlite3_mprintf("%zAND ", zBuf);
   134368       break;
   134369     case FTSQUERY_OR:
   134370       zBuf = sqlite3_mprintf("%zOR ", zBuf);
   134371       break;
   134372   }
   134373 
   134374   if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
   134375   if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
   134376   if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
   134377 
   134378   if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
   134379   if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
   134380 
   134381   return zBuf;
   134382 }
   134383 
   134384 /*
   134385 ** This is the implementation of a scalar SQL function used to test the
   134386 ** expression parser. It should be called as follows:
   134387 **
   134388 **   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
   134389 **
   134390 ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
   134391 ** to parse the query expression (see README.tokenizers). The second argument
   134392 ** is the query expression to parse. Each subsequent argument is the name
   134393 ** of a column of the fts3 table that the query expression may refer to.
   134394 ** For example:
   134395 **
   134396 **   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
   134397 */
   134398 static void fts3ExprTest(
   134399   sqlite3_context *context,
   134400   int argc,
   134401   sqlite3_value **argv
   134402 ){
   134403   sqlite3_tokenizer_module const *pModule = 0;
   134404   sqlite3_tokenizer *pTokenizer = 0;
   134405   int rc;
   134406   char **azCol = 0;
   134407   const char *zExpr;
   134408   int nExpr;
   134409   int nCol;
   134410   int ii;
   134411   Fts3Expr *pExpr;
   134412   char *zBuf = 0;
   134413   sqlite3 *db = sqlite3_context_db_handle(context);
   134414 
   134415   if( argc<3 ){
   134416     sqlite3_result_error(context,
   134417         "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
   134418     );
   134419     return;
   134420   }
   134421 
   134422   rc = queryTestTokenizer(db,
   134423                           (const char *)sqlite3_value_text(argv[0]), &pModule);
   134424   if( rc==SQLITE_NOMEM ){
   134425     sqlite3_result_error_nomem(context);
   134426     goto exprtest_out;
   134427   }else if( !pModule ){
   134428     sqlite3_result_error(context, "No such tokenizer module", -1);
   134429     goto exprtest_out;
   134430   }
   134431 
   134432   rc = pModule->xCreate(0, 0, &pTokenizer);
   134433   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
   134434   if( rc==SQLITE_NOMEM ){
   134435     sqlite3_result_error_nomem(context);
   134436     goto exprtest_out;
   134437   }
   134438   pTokenizer->pModule = pModule;
   134439 
   134440   zExpr = (const char *)sqlite3_value_text(argv[1]);
   134441   nExpr = sqlite3_value_bytes(argv[1]);
   134442   nCol = argc-2;
   134443   azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
   134444   if( !azCol ){
   134445     sqlite3_result_error_nomem(context);
   134446     goto exprtest_out;
   134447   }
   134448   for(ii=0; ii<nCol; ii++){
   134449     azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
   134450   }
   134451 
   134452   if( sqlite3_user_data(context) ){
   134453     char *zDummy = 0;
   134454     rc = sqlite3Fts3ExprParse(
   134455         pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
   134456     );
   134457     assert( rc==SQLITE_OK || pExpr==0 );
   134458     sqlite3_free(zDummy);
   134459   }else{
   134460     rc = fts3ExprParseUnbalanced(
   134461         pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
   134462     );
   134463   }
   134464 
   134465   if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
   134466     sqlite3Fts3ExprFree(pExpr);
   134467     sqlite3_result_error(context, "Error parsing expression", -1);
   134468   }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
   134469     sqlite3_result_error_nomem(context);
   134470   }else{
   134471     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
   134472     sqlite3_free(zBuf);
   134473   }
   134474 
   134475   sqlite3Fts3ExprFree(pExpr);
   134476 
   134477 exprtest_out:
   134478   if( pModule && pTokenizer ){
   134479     rc = pModule->xDestroy(pTokenizer);
   134480   }
   134481   sqlite3_free(azCol);
   134482 }
   134483 
   134484 /*
   134485 ** Register the query expression parser test function fts3_exprtest()
   134486 ** with database connection db.
   134487 */
   134488 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
   134489   int rc = sqlite3_create_function(
   134490       db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
   134491   );
   134492   if( rc==SQLITE_OK ){
   134493     rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
   134494         -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
   134495     );
   134496   }
   134497   return rc;
   134498 }
   134499 
   134500 #endif
   134501 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   134502 
   134503 /************** End of fts3_expr.c *******************************************/
   134504 /************** Begin file fts3_hash.c ***************************************/
   134505 /*
   134506 ** 2001 September 22
   134507 **
   134508 ** The author disclaims copyright to this source code.  In place of
   134509 ** a legal notice, here is a blessing:
   134510 **
   134511 **    May you do good and not evil.
   134512 **    May you find forgiveness for yourself and forgive others.
   134513 **    May you share freely, never taking more than you give.
   134514 **
   134515 *************************************************************************
   134516 ** This is the implementation of generic hash-tables used in SQLite.
   134517 ** We've modified it slightly to serve as a standalone hash table
   134518 ** implementation for the full-text indexing module.
   134519 */
   134520 
   134521 /*
   134522 ** The code in this file is only compiled if:
   134523 **
   134524 **     * The FTS3 module is being built as an extension
   134525 **       (in which case SQLITE_CORE is not defined), or
   134526 **
   134527 **     * The FTS3 module is being built into the core of
   134528 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
   134529 */
   134530 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   134531 
   134532 /* #include <assert.h> */
   134533 /* #include <stdlib.h> */
   134534 /* #include <string.h> */
   134535 
   134536 
   134537 /*
   134538 ** Malloc and Free functions
   134539 */
   134540 static void *fts3HashMalloc(int n){
   134541   void *p = sqlite3_malloc(n);
   134542   if( p ){
   134543     memset(p, 0, n);
   134544   }
   134545   return p;
   134546 }
   134547 static void fts3HashFree(void *p){
   134548   sqlite3_free(p);
   134549 }
   134550 
   134551 /* Turn bulk memory into a hash table object by initializing the
   134552 ** fields of the Hash structure.
   134553 **
   134554 ** "pNew" is a pointer to the hash table that is to be initialized.
   134555 ** keyClass is one of the constants
   134556 ** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass
   134557 ** determines what kind of key the hash table will use.  "copyKey" is
   134558 ** true if the hash table should make its own private copy of keys and
   134559 ** false if it should just use the supplied pointer.
   134560 */
   134561 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
   134562   assert( pNew!=0 );
   134563   assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
   134564   pNew->keyClass = keyClass;
   134565   pNew->copyKey = copyKey;
   134566   pNew->first = 0;
   134567   pNew->count = 0;
   134568   pNew->htsize = 0;
   134569   pNew->ht = 0;
   134570 }
   134571 
   134572 /* Remove all entries from a hash table.  Reclaim all memory.
   134573 ** Call this routine to delete a hash table or to reset a hash table
   134574 ** to the empty state.
   134575 */
   134576 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
   134577   Fts3HashElem *elem;         /* For looping over all elements of the table */
   134578 
   134579   assert( pH!=0 );
   134580   elem = pH->first;
   134581   pH->first = 0;
   134582   fts3HashFree(pH->ht);
   134583   pH->ht = 0;
   134584   pH->htsize = 0;
   134585   while( elem ){
   134586     Fts3HashElem *next_elem = elem->next;
   134587     if( pH->copyKey && elem->pKey ){
   134588       fts3HashFree(elem->pKey);
   134589     }
   134590     fts3HashFree(elem);
   134591     elem = next_elem;
   134592   }
   134593   pH->count = 0;
   134594 }
   134595 
   134596 /*
   134597 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
   134598 */
   134599 static int fts3StrHash(const void *pKey, int nKey){
   134600   const char *z = (const char *)pKey;
   134601   unsigned h = 0;
   134602   if( nKey<=0 ) nKey = (int) strlen(z);
   134603   while( nKey > 0  ){
   134604     h = (h<<3) ^ h ^ *z++;
   134605     nKey--;
   134606   }
   134607   return (int)(h & 0x7fffffff);
   134608 }
   134609 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
   134610   if( n1!=n2 ) return 1;
   134611   return strncmp((const char*)pKey1,(const char*)pKey2,n1);
   134612 }
   134613 
   134614 /*
   134615 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
   134616 */
   134617 static int fts3BinHash(const void *pKey, int nKey){
   134618   int h = 0;
   134619   const char *z = (const char *)pKey;
   134620   while( nKey-- > 0 ){
   134621     h = (h<<3) ^ h ^ *(z++);
   134622   }
   134623   return h & 0x7fffffff;
   134624 }
   134625 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
   134626   if( n1!=n2 ) return 1;
   134627   return memcmp(pKey1,pKey2,n1);
   134628 }
   134629 
   134630 /*
   134631 ** Return a pointer to the appropriate hash function given the key class.
   134632 **
   134633 ** The C syntax in this function definition may be unfamilar to some
   134634 ** programmers, so we provide the following additional explanation:
   134635 **
   134636 ** The name of the function is "ftsHashFunction".  The function takes a
   134637 ** single parameter "keyClass".  The return value of ftsHashFunction()
   134638 ** is a pointer to another function.  Specifically, the return value
   134639 ** of ftsHashFunction() is a pointer to a function that takes two parameters
   134640 ** with types "const void*" and "int" and returns an "int".
   134641 */
   134642 static int (*ftsHashFunction(int keyClass))(const void*,int){
   134643   if( keyClass==FTS3_HASH_STRING ){
   134644     return &fts3StrHash;
   134645   }else{
   134646     assert( keyClass==FTS3_HASH_BINARY );
   134647     return &fts3BinHash;
   134648   }
   134649 }
   134650 
   134651 /*
   134652 ** Return a pointer to the appropriate hash function given the key class.
   134653 **
   134654 ** For help in interpreted the obscure C code in the function definition,
   134655 ** see the header comment on the previous function.
   134656 */
   134657 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
   134658   if( keyClass==FTS3_HASH_STRING ){
   134659     return &fts3StrCompare;
   134660   }else{
   134661     assert( keyClass==FTS3_HASH_BINARY );
   134662     return &fts3BinCompare;
   134663   }
   134664 }
   134665 
   134666 /* Link an element into the hash table
   134667 */
   134668 static void fts3HashInsertElement(
   134669   Fts3Hash *pH,            /* The complete hash table */
   134670   struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
   134671   Fts3HashElem *pNew       /* The element to be inserted */
   134672 ){
   134673   Fts3HashElem *pHead;     /* First element already in pEntry */
   134674   pHead = pEntry->chain;
   134675   if( pHead ){
   134676     pNew->next = pHead;
   134677     pNew->prev = pHead->prev;
   134678     if( pHead->prev ){ pHead->prev->next = pNew; }
   134679     else             { pH->first = pNew; }
   134680     pHead->prev = pNew;
   134681   }else{
   134682     pNew->next = pH->first;
   134683     if( pH->first ){ pH->first->prev = pNew; }
   134684     pNew->prev = 0;
   134685     pH->first = pNew;
   134686   }
   134687   pEntry->count++;
   134688   pEntry->chain = pNew;
   134689 }
   134690 
   134691 
   134692 /* Resize the hash table so that it cantains "new_size" buckets.
   134693 ** "new_size" must be a power of 2.  The hash table might fail
   134694 ** to resize if sqliteMalloc() fails.
   134695 **
   134696 ** Return non-zero if a memory allocation error occurs.
   134697 */
   134698 static int fts3Rehash(Fts3Hash *pH, int new_size){
   134699   struct _fts3ht *new_ht;          /* The new hash table */
   134700   Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
   134701   int (*xHash)(const void*,int);   /* The hash function */
   134702 
   134703   assert( (new_size & (new_size-1))==0 );
   134704   new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
   134705   if( new_ht==0 ) return 1;
   134706   fts3HashFree(pH->ht);
   134707   pH->ht = new_ht;
   134708   pH->htsize = new_size;
   134709   xHash = ftsHashFunction(pH->keyClass);
   134710   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
   134711     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
   134712     next_elem = elem->next;
   134713     fts3HashInsertElement(pH, &new_ht[h], elem);
   134714   }
   134715   return 0;
   134716 }
   134717 
   134718 /* This function (for internal use only) locates an element in an
   134719 ** hash table that matches the given key.  The hash for this key has
   134720 ** already been computed and is passed as the 4th parameter.
   134721 */
   134722 static Fts3HashElem *fts3FindElementByHash(
   134723   const Fts3Hash *pH, /* The pH to be searched */
   134724   const void *pKey,   /* The key we are searching for */
   134725   int nKey,
   134726   int h               /* The hash for this key. */
   134727 ){
   134728   Fts3HashElem *elem;            /* Used to loop thru the element list */
   134729   int count;                     /* Number of elements left to test */
   134730   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
   134731 
   134732   if( pH->ht ){
   134733     struct _fts3ht *pEntry = &pH->ht[h];
   134734     elem = pEntry->chain;
   134735     count = pEntry->count;
   134736     xCompare = ftsCompareFunction(pH->keyClass);
   134737     while( count-- && elem ){
   134738       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
   134739         return elem;
   134740       }
   134741       elem = elem->next;
   134742     }
   134743   }
   134744   return 0;
   134745 }
   134746 
   134747 /* Remove a single entry from the hash table given a pointer to that
   134748 ** element and a hash on the element's key.
   134749 */
   134750 static void fts3RemoveElementByHash(
   134751   Fts3Hash *pH,         /* The pH containing "elem" */
   134752   Fts3HashElem* elem,   /* The element to be removed from the pH */
   134753   int h                 /* Hash value for the element */
   134754 ){
   134755   struct _fts3ht *pEntry;
   134756   if( elem->prev ){
   134757     elem->prev->next = elem->next;
   134758   }else{
   134759     pH->first = elem->next;
   134760   }
   134761   if( elem->next ){
   134762     elem->next->prev = elem->prev;
   134763   }
   134764   pEntry = &pH->ht[h];
   134765   if( pEntry->chain==elem ){
   134766     pEntry->chain = elem->next;
   134767   }
   134768   pEntry->count--;
   134769   if( pEntry->count<=0 ){
   134770     pEntry->chain = 0;
   134771   }
   134772   if( pH->copyKey && elem->pKey ){
   134773     fts3HashFree(elem->pKey);
   134774   }
   134775   fts3HashFree( elem );
   134776   pH->count--;
   134777   if( pH->count<=0 ){
   134778     assert( pH->first==0 );
   134779     assert( pH->count==0 );
   134780     fts3HashClear(pH);
   134781   }
   134782 }
   134783 
   134784 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
   134785   const Fts3Hash *pH,
   134786   const void *pKey,
   134787   int nKey
   134788 ){
   134789   int h;                          /* A hash on key */
   134790   int (*xHash)(const void*,int);  /* The hash function */
   134791 
   134792   if( pH==0 || pH->ht==0 ) return 0;
   134793   xHash = ftsHashFunction(pH->keyClass);
   134794   assert( xHash!=0 );
   134795   h = (*xHash)(pKey,nKey);
   134796   assert( (pH->htsize & (pH->htsize-1))==0 );
   134797   return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
   134798 }
   134799 
   134800 /*
   134801 ** Attempt to locate an element of the hash table pH with a key
   134802 ** that matches pKey,nKey.  Return the data for this element if it is
   134803 ** found, or NULL if there is no match.
   134804 */
   134805 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
   134806   Fts3HashElem *pElem;            /* The element that matches key (if any) */
   134807 
   134808   pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
   134809   return pElem ? pElem->data : 0;
   134810 }
   134811 
   134812 /* Insert an element into the hash table pH.  The key is pKey,nKey
   134813 ** and the data is "data".
   134814 **
   134815 ** If no element exists with a matching key, then a new
   134816 ** element is created.  A copy of the key is made if the copyKey
   134817 ** flag is set.  NULL is returned.
   134818 **
   134819 ** If another element already exists with the same key, then the
   134820 ** new data replaces the old data and the old data is returned.
   134821 ** The key is not copied in this instance.  If a malloc fails, then
   134822 ** the new data is returned and the hash table is unchanged.
   134823 **
   134824 ** If the "data" parameter to this function is NULL, then the
   134825 ** element corresponding to "key" is removed from the hash table.
   134826 */
   134827 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
   134828   Fts3Hash *pH,        /* The hash table to insert into */
   134829   const void *pKey,    /* The key */
   134830   int nKey,            /* Number of bytes in the key */
   134831   void *data           /* The data */
   134832 ){
   134833   int hraw;                 /* Raw hash value of the key */
   134834   int h;                    /* the hash of the key modulo hash table size */
   134835   Fts3HashElem *elem;       /* Used to loop thru the element list */
   134836   Fts3HashElem *new_elem;   /* New element added to the pH */
   134837   int (*xHash)(const void*,int);  /* The hash function */
   134838 
   134839   assert( pH!=0 );
   134840   xHash = ftsHashFunction(pH->keyClass);
   134841   assert( xHash!=0 );
   134842   hraw = (*xHash)(pKey, nKey);
   134843   assert( (pH->htsize & (pH->htsize-1))==0 );
   134844   h = hraw & (pH->htsize-1);
   134845   elem = fts3FindElementByHash(pH,pKey,nKey,h);
   134846   if( elem ){
   134847     void *old_data = elem->data;
   134848     if( data==0 ){
   134849       fts3RemoveElementByHash(pH,elem,h);
   134850     }else{
   134851       elem->data = data;
   134852     }
   134853     return old_data;
   134854   }
   134855   if( data==0 ) return 0;
   134856   if( (pH->htsize==0 && fts3Rehash(pH,8))
   134857    || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
   134858   ){
   134859     pH->count = 0;
   134860     return data;
   134861   }
   134862   assert( pH->htsize>0 );
   134863   new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
   134864   if( new_elem==0 ) return data;
   134865   if( pH->copyKey && pKey!=0 ){
   134866     new_elem->pKey = fts3HashMalloc( nKey );
   134867     if( new_elem->pKey==0 ){
   134868       fts3HashFree(new_elem);
   134869       return data;
   134870     }
   134871     memcpy((void*)new_elem->pKey, pKey, nKey);
   134872   }else{
   134873     new_elem->pKey = (void*)pKey;
   134874   }
   134875   new_elem->nKey = nKey;
   134876   pH->count++;
   134877   assert( pH->htsize>0 );
   134878   assert( (pH->htsize & (pH->htsize-1))==0 );
   134879   h = hraw & (pH->htsize-1);
   134880   fts3HashInsertElement(pH, &pH->ht[h], new_elem);
   134881   new_elem->data = data;
   134882   return 0;
   134883 }
   134884 
   134885 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   134886 
   134887 /************** End of fts3_hash.c *******************************************/
   134888 /************** Begin file fts3_porter.c *************************************/
   134889 /*
   134890 ** 2006 September 30
   134891 **
   134892 ** The author disclaims copyright to this source code.  In place of
   134893 ** a legal notice, here is a blessing:
   134894 **
   134895 **    May you do good and not evil.
   134896 **    May you find forgiveness for yourself and forgive others.
   134897 **    May you share freely, never taking more than you give.
   134898 **
   134899 *************************************************************************
   134900 ** Implementation of the full-text-search tokenizer that implements
   134901 ** a Porter stemmer.
   134902 */
   134903 
   134904 /*
   134905 ** The code in this file is only compiled if:
   134906 **
   134907 **     * The FTS3 module is being built as an extension
   134908 **       (in which case SQLITE_CORE is not defined), or
   134909 **
   134910 **     * The FTS3 module is being built into the core of
   134911 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
   134912 */
   134913 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   134914 
   134915 /* #include <assert.h> */
   134916 /* #include <stdlib.h> */
   134917 /* #include <stdio.h> */
   134918 /* #include <string.h> */
   134919 
   134920 
   134921 /*
   134922 ** Class derived from sqlite3_tokenizer
   134923 */
   134924 typedef struct porter_tokenizer {
   134925   sqlite3_tokenizer base;      /* Base class */
   134926 } porter_tokenizer;
   134927 
   134928 /*
   134929 ** Class derived from sqlite3_tokenizer_cursor
   134930 */
   134931 typedef struct porter_tokenizer_cursor {
   134932   sqlite3_tokenizer_cursor base;
   134933   const char *zInput;          /* input we are tokenizing */
   134934   int nInput;                  /* size of the input */
   134935   int iOffset;                 /* current position in zInput */
   134936   int iToken;                  /* index of next token to be returned */
   134937   char *zToken;                /* storage for current token */
   134938   int nAllocated;              /* space allocated to zToken buffer */
   134939 } porter_tokenizer_cursor;
   134940 
   134941 
   134942 /*
   134943 ** Create a new tokenizer instance.
   134944 */
   134945 static int porterCreate(
   134946   int argc, const char * const *argv,
   134947   sqlite3_tokenizer **ppTokenizer
   134948 ){
   134949   porter_tokenizer *t;
   134950 
   134951   UNUSED_PARAMETER(argc);
   134952   UNUSED_PARAMETER(argv);
   134953 
   134954   t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
   134955   if( t==NULL ) return SQLITE_NOMEM;
   134956   memset(t, 0, sizeof(*t));
   134957   *ppTokenizer = &t->base;
   134958   return SQLITE_OK;
   134959 }
   134960 
   134961 /*
   134962 ** Destroy a tokenizer
   134963 */
   134964 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
   134965   sqlite3_free(pTokenizer);
   134966   return SQLITE_OK;
   134967 }
   134968 
   134969 /*
   134970 ** Prepare to begin tokenizing a particular string.  The input
   134971 ** string to be tokenized is zInput[0..nInput-1].  A cursor
   134972 ** used to incrementally tokenize this string is returned in
   134973 ** *ppCursor.
   134974 */
   134975 static int porterOpen(
   134976   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
   134977   const char *zInput, int nInput,        /* String to be tokenized */
   134978   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
   134979 ){
   134980   porter_tokenizer_cursor *c;
   134981 
   134982   UNUSED_PARAMETER(pTokenizer);
   134983 
   134984   c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
   134985   if( c==NULL ) return SQLITE_NOMEM;
   134986 
   134987   c->zInput = zInput;
   134988   if( zInput==0 ){
   134989     c->nInput = 0;
   134990   }else if( nInput<0 ){
   134991     c->nInput = (int)strlen(zInput);
   134992   }else{
   134993     c->nInput = nInput;
   134994   }
   134995   c->iOffset = 0;                 /* start tokenizing at the beginning */
   134996   c->iToken = 0;
   134997   c->zToken = NULL;               /* no space allocated, yet. */
   134998   c->nAllocated = 0;
   134999 
   135000   *ppCursor = &c->base;
   135001   return SQLITE_OK;
   135002 }
   135003 
   135004 /*
   135005 ** Close a tokenization cursor previously opened by a call to
   135006 ** porterOpen() above.
   135007 */
   135008 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
   135009   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
   135010   sqlite3_free(c->zToken);
   135011   sqlite3_free(c);
   135012   return SQLITE_OK;
   135013 }
   135014 /*
   135015 ** Vowel or consonant
   135016 */
   135017 static const char cType[] = {
   135018    0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
   135019    1, 1, 1, 2, 1
   135020 };
   135021 
   135022 /*
   135023 ** isConsonant() and isVowel() determine if their first character in
   135024 ** the string they point to is a consonant or a vowel, according
   135025 ** to Porter ruls.
   135026 **
   135027 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
   135028 ** 'Y' is a consonant unless it follows another consonant,
   135029 ** in which case it is a vowel.
   135030 **
   135031 ** In these routine, the letters are in reverse order.  So the 'y' rule
   135032 ** is that 'y' is a consonant unless it is followed by another
   135033 ** consonent.
   135034 */
   135035 static int isVowel(const char*);
   135036 static int isConsonant(const char *z){
   135037   int j;
   135038   char x = *z;
   135039   if( x==0 ) return 0;
   135040   assert( x>='a' && x<='z' );
   135041   j = cType[x-'a'];
   135042   if( j<2 ) return j;
   135043   return z[1]==0 || isVowel(z + 1);
   135044 }
   135045 static int isVowel(const char *z){
   135046   int j;
   135047   char x = *z;
   135048   if( x==0 ) return 0;
   135049   assert( x>='a' && x<='z' );
   135050   j = cType[x-'a'];
   135051   if( j<2 ) return 1-j;
   135052   return isConsonant(z + 1);
   135053 }
   135054 
   135055 /*
   135056 ** Let any sequence of one or more vowels be represented by V and let
   135057 ** C be sequence of one or more consonants.  Then every word can be
   135058 ** represented as:
   135059 **
   135060 **           [C] (VC){m} [V]
   135061 **
   135062 ** In prose:  A word is an optional consonant followed by zero or
   135063 ** vowel-consonant pairs followed by an optional vowel.  "m" is the
   135064 ** number of vowel consonant pairs.  This routine computes the value
   135065 ** of m for the first i bytes of a word.
   135066 **
   135067 ** Return true if the m-value for z is 1 or more.  In other words,
   135068 ** return true if z contains at least one vowel that is followed
   135069 ** by a consonant.
   135070 **
   135071 ** In this routine z[] is in reverse order.  So we are really looking
   135072 ** for an instance of of a consonant followed by a vowel.
   135073 */
   135074 static int m_gt_0(const char *z){
   135075   while( isVowel(z) ){ z++; }
   135076   if( *z==0 ) return 0;
   135077   while( isConsonant(z) ){ z++; }
   135078   return *z!=0;
   135079 }
   135080 
   135081 /* Like mgt0 above except we are looking for a value of m which is
   135082 ** exactly 1
   135083 */
   135084 static int m_eq_1(const char *z){
   135085   while( isVowel(z) ){ z++; }
   135086   if( *z==0 ) return 0;
   135087   while( isConsonant(z) ){ z++; }
   135088   if( *z==0 ) return 0;
   135089   while( isVowel(z) ){ z++; }
   135090   if( *z==0 ) return 1;
   135091   while( isConsonant(z) ){ z++; }
   135092   return *z==0;
   135093 }
   135094 
   135095 /* Like mgt0 above except we are looking for a value of m>1 instead
   135096 ** or m>0
   135097 */
   135098 static int m_gt_1(const char *z){
   135099   while( isVowel(z) ){ z++; }
   135100   if( *z==0 ) return 0;
   135101   while( isConsonant(z) ){ z++; }
   135102   if( *z==0 ) return 0;
   135103   while( isVowel(z) ){ z++; }
   135104   if( *z==0 ) return 0;
   135105   while( isConsonant(z) ){ z++; }
   135106   return *z!=0;
   135107 }
   135108 
   135109 /*
   135110 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
   135111 */
   135112 static int hasVowel(const char *z){
   135113   while( isConsonant(z) ){ z++; }
   135114   return *z!=0;
   135115 }
   135116 
   135117 /*
   135118 ** Return TRUE if the word ends in a double consonant.
   135119 **
   135120 ** The text is reversed here. So we are really looking at
   135121 ** the first two characters of z[].
   135122 */
   135123 static int doubleConsonant(const char *z){
   135124   return isConsonant(z) && z[0]==z[1];
   135125 }
   135126 
   135127 /*
   135128 ** Return TRUE if the word ends with three letters which
   135129 ** are consonant-vowel-consonent and where the final consonant
   135130 ** is not 'w', 'x', or 'y'.
   135131 **
   135132 ** The word is reversed here.  So we are really checking the
   135133 ** first three letters and the first one cannot be in [wxy].
   135134 */
   135135 static int star_oh(const char *z){
   135136   return
   135137     isConsonant(z) &&
   135138     z[0]!='w' && z[0]!='x' && z[0]!='y' &&
   135139     isVowel(z+1) &&
   135140     isConsonant(z+2);
   135141 }
   135142 
   135143 /*
   135144 ** If the word ends with zFrom and xCond() is true for the stem
   135145 ** of the word that preceeds the zFrom ending, then change the
   135146 ** ending to zTo.
   135147 **
   135148 ** The input word *pz and zFrom are both in reverse order.  zTo
   135149 ** is in normal order.
   135150 **
   135151 ** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
   135152 ** match.  Not that TRUE is returned even if xCond() fails and
   135153 ** no substitution occurs.
   135154 */
   135155 static int stem(
   135156   char **pz,             /* The word being stemmed (Reversed) */
   135157   const char *zFrom,     /* If the ending matches this... (Reversed) */
   135158   const char *zTo,       /* ... change the ending to this (not reversed) */
   135159   int (*xCond)(const char*)   /* Condition that must be true */
   135160 ){
   135161   char *z = *pz;
   135162   while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
   135163   if( *zFrom!=0 ) return 0;
   135164   if( xCond && !xCond(z) ) return 1;
   135165   while( *zTo ){
   135166     *(--z) = *(zTo++);
   135167   }
   135168   *pz = z;
   135169   return 1;
   135170 }
   135171 
   135172 /*
   135173 ** This is the fallback stemmer used when the porter stemmer is
   135174 ** inappropriate.  The input word is copied into the output with
   135175 ** US-ASCII case folding.  If the input word is too long (more
   135176 ** than 20 bytes if it contains no digits or more than 6 bytes if
   135177 ** it contains digits) then word is truncated to 20 or 6 bytes
   135178 ** by taking 10 or 3 bytes from the beginning and end.
   135179 */
   135180 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
   135181   int i, mx, j;
   135182   int hasDigit = 0;
   135183   for(i=0; i<nIn; i++){
   135184     char c = zIn[i];
   135185     if( c>='A' && c<='Z' ){
   135186       zOut[i] = c - 'A' + 'a';
   135187     }else{
   135188       if( c>='0' && c<='9' ) hasDigit = 1;
   135189       zOut[i] = c;
   135190     }
   135191   }
   135192   mx = hasDigit ? 3 : 10;
   135193   if( nIn>mx*2 ){
   135194     for(j=mx, i=nIn-mx; i<nIn; i++, j++){
   135195       zOut[j] = zOut[i];
   135196     }
   135197     i = j;
   135198   }
   135199   zOut[i] = 0;
   135200   *pnOut = i;
   135201 }
   135202 
   135203 
   135204 /*
   135205 ** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
   135206 ** zOut is at least big enough to hold nIn bytes.  Write the actual
   135207 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
   135208 **
   135209 ** Any upper-case characters in the US-ASCII character set ([A-Z])
   135210 ** are converted to lower case.  Upper-case UTF characters are
   135211 ** unchanged.
   135212 **
   135213 ** Words that are longer than about 20 bytes are stemmed by retaining
   135214 ** a few bytes from the beginning and the end of the word.  If the
   135215 ** word contains digits, 3 bytes are taken from the beginning and
   135216 ** 3 bytes from the end.  For long words without digits, 10 bytes
   135217 ** are taken from each end.  US-ASCII case folding still applies.
   135218 **
   135219 ** If the input word contains not digits but does characters not
   135220 ** in [a-zA-Z] then no stemming is attempted and this routine just
   135221 ** copies the input into the input into the output with US-ASCII
   135222 ** case folding.
   135223 **
   135224 ** Stemming never increases the length of the word.  So there is
   135225 ** no chance of overflowing the zOut buffer.
   135226 */
   135227 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
   135228   int i, j;
   135229   char zReverse[28];
   135230   char *z, *z2;
   135231   if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
   135232     /* The word is too big or too small for the porter stemmer.
   135233     ** Fallback to the copy stemmer */
   135234     copy_stemmer(zIn, nIn, zOut, pnOut);
   135235     return;
   135236   }
   135237   for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
   135238     char c = zIn[i];
   135239     if( c>='A' && c<='Z' ){
   135240       zReverse[j] = c + 'a' - 'A';
   135241     }else if( c>='a' && c<='z' ){
   135242       zReverse[j] = c;
   135243     }else{
   135244       /* The use of a character not in [a-zA-Z] means that we fallback
   135245       ** to the copy stemmer */
   135246       copy_stemmer(zIn, nIn, zOut, pnOut);
   135247       return;
   135248     }
   135249   }
   135250   memset(&zReverse[sizeof(zReverse)-5], 0, 5);
   135251   z = &zReverse[j+1];
   135252 
   135253 
   135254   /* Step 1a */
   135255   if( z[0]=='s' ){
   135256     if(
   135257      !stem(&z, "sess", "ss", 0) &&
   135258      !stem(&z, "sei", "i", 0)  &&
   135259      !stem(&z, "ss", "ss", 0)
   135260     ){
   135261       z++;
   135262     }
   135263   }
   135264 
   135265   /* Step 1b */
   135266   z2 = z;
   135267   if( stem(&z, "dee", "ee", m_gt_0) ){
   135268     /* Do nothing.  The work was all in the test */
   135269   }else if(
   135270      (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
   135271       && z!=z2
   135272   ){
   135273      if( stem(&z, "ta", "ate", 0) ||
   135274          stem(&z, "lb", "ble", 0) ||
   135275          stem(&z, "zi", "ize", 0) ){
   135276        /* Do nothing.  The work was all in the test */
   135277      }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
   135278        z++;
   135279      }else if( m_eq_1(z) && star_oh(z) ){
   135280        *(--z) = 'e';
   135281      }
   135282   }
   135283 
   135284   /* Step 1c */
   135285   if( z[0]=='y' && hasVowel(z+1) ){
   135286     z[0] = 'i';
   135287   }
   135288 
   135289   /* Step 2 */
   135290   switch( z[1] ){
   135291    case 'a':
   135292      if( !stem(&z, "lanoita", "ate", m_gt_0) ){
   135293        stem(&z, "lanoit", "tion", m_gt_0);
   135294      }
   135295      break;
   135296    case 'c':
   135297      if( !stem(&z, "icne", "ence", m_gt_0) ){
   135298        stem(&z, "icna", "ance", m_gt_0);
   135299      }
   135300      break;
   135301    case 'e':
   135302      stem(&z, "rezi", "ize", m_gt_0);
   135303      break;
   135304    case 'g':
   135305      stem(&z, "igol", "log", m_gt_0);
   135306      break;
   135307    case 'l':
   135308      if( !stem(&z, "ilb", "ble", m_gt_0)
   135309       && !stem(&z, "illa", "al", m_gt_0)
   135310       && !stem(&z, "iltne", "ent", m_gt_0)
   135311       && !stem(&z, "ile", "e", m_gt_0)
   135312      ){
   135313        stem(&z, "ilsuo", "ous", m_gt_0);
   135314      }
   135315      break;
   135316    case 'o':
   135317      if( !stem(&z, "noitazi", "ize", m_gt_0)
   135318       && !stem(&z, "noita", "ate", m_gt_0)
   135319      ){
   135320        stem(&z, "rota", "ate", m_gt_0);
   135321      }
   135322      break;
   135323    case 's':
   135324      if( !stem(&z, "msila", "al", m_gt_0)
   135325       && !stem(&z, "ssenevi", "ive", m_gt_0)
   135326       && !stem(&z, "ssenluf", "ful", m_gt_0)
   135327      ){
   135328        stem(&z, "ssensuo", "ous", m_gt_0);
   135329      }
   135330      break;
   135331    case 't':
   135332      if( !stem(&z, "itila", "al", m_gt_0)
   135333       && !stem(&z, "itivi", "ive", m_gt_0)
   135334      ){
   135335        stem(&z, "itilib", "ble", m_gt_0);
   135336      }
   135337      break;
   135338   }
   135339 
   135340   /* Step 3 */
   135341   switch( z[0] ){
   135342    case 'e':
   135343      if( !stem(&z, "etaci", "ic", m_gt_0)
   135344       && !stem(&z, "evita", "", m_gt_0)
   135345      ){
   135346        stem(&z, "ezila", "al", m_gt_0);
   135347      }
   135348      break;
   135349    case 'i':
   135350      stem(&z, "itici", "ic", m_gt_0);
   135351      break;
   135352    case 'l':
   135353      if( !stem(&z, "laci", "ic", m_gt_0) ){
   135354        stem(&z, "luf", "", m_gt_0);
   135355      }
   135356      break;
   135357    case 's':
   135358      stem(&z, "ssen", "", m_gt_0);
   135359      break;
   135360   }
   135361 
   135362   /* Step 4 */
   135363   switch( z[1] ){
   135364    case 'a':
   135365      if( z[0]=='l' && m_gt_1(z+2) ){
   135366        z += 2;
   135367      }
   135368      break;
   135369    case 'c':
   135370      if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
   135371        z += 4;
   135372      }
   135373      break;
   135374    case 'e':
   135375      if( z[0]=='r' && m_gt_1(z+2) ){
   135376        z += 2;
   135377      }
   135378      break;
   135379    case 'i':
   135380      if( z[0]=='c' && m_gt_1(z+2) ){
   135381        z += 2;
   135382      }
   135383      break;
   135384    case 'l':
   135385      if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
   135386        z += 4;
   135387      }
   135388      break;
   135389    case 'n':
   135390      if( z[0]=='t' ){
   135391        if( z[2]=='a' ){
   135392          if( m_gt_1(z+3) ){
   135393            z += 3;
   135394          }
   135395        }else if( z[2]=='e' ){
   135396          if( !stem(&z, "tneme", "", m_gt_1)
   135397           && !stem(&z, "tnem", "", m_gt_1)
   135398          ){
   135399            stem(&z, "tne", "", m_gt_1);
   135400          }
   135401        }
   135402      }
   135403      break;
   135404    case 'o':
   135405      if( z[0]=='u' ){
   135406        if( m_gt_1(z+2) ){
   135407          z += 2;
   135408        }
   135409      }else if( z[3]=='s' || z[3]=='t' ){
   135410        stem(&z, "noi", "", m_gt_1);
   135411      }
   135412      break;
   135413    case 's':
   135414      if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
   135415        z += 3;
   135416      }
   135417      break;
   135418    case 't':
   135419      if( !stem(&z, "eta", "", m_gt_1) ){
   135420        stem(&z, "iti", "", m_gt_1);
   135421      }
   135422      break;
   135423    case 'u':
   135424      if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
   135425        z += 3;
   135426      }
   135427      break;
   135428    case 'v':
   135429    case 'z':
   135430      if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
   135431        z += 3;
   135432      }
   135433      break;
   135434   }
   135435 
   135436   /* Step 5a */
   135437   if( z[0]=='e' ){
   135438     if( m_gt_1(z+1) ){
   135439       z++;
   135440     }else if( m_eq_1(z+1) && !star_oh(z+1) ){
   135441       z++;
   135442     }
   135443   }
   135444 
   135445   /* Step 5b */
   135446   if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
   135447     z++;
   135448   }
   135449 
   135450   /* z[] is now the stemmed word in reverse order.  Flip it back
   135451   ** around into forward order and return.
   135452   */
   135453   *pnOut = i = (int)strlen(z);
   135454   zOut[i] = 0;
   135455   while( *z ){
   135456     zOut[--i] = *(z++);
   135457   }
   135458 }
   135459 
   135460 /*
   135461 ** Characters that can be part of a token.  We assume any character
   135462 ** whose value is greater than 0x80 (any UTF character) can be
   135463 ** part of a token.  In other words, delimiters all must have
   135464 ** values of 0x7f or lower.
   135465 */
   135466 static const char porterIdChar[] = {
   135467 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
   135468     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
   135469     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
   135470     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
   135471     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
   135472     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
   135473 };
   135474 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
   135475 
   135476 /*
   135477 ** Extract the next token from a tokenization cursor.  The cursor must
   135478 ** have been opened by a prior call to porterOpen().
   135479 */
   135480 static int porterNext(
   135481   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
   135482   const char **pzToken,               /* OUT: *pzToken is the token text */
   135483   int *pnBytes,                       /* OUT: Number of bytes in token */
   135484   int *piStartOffset,                 /* OUT: Starting offset of token */
   135485   int *piEndOffset,                   /* OUT: Ending offset of token */
   135486   int *piPosition                     /* OUT: Position integer of token */
   135487 ){
   135488   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
   135489   const char *z = c->zInput;
   135490 
   135491   while( c->iOffset<c->nInput ){
   135492     int iStartOffset, ch;
   135493 
   135494     /* Scan past delimiter characters */
   135495     while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
   135496       c->iOffset++;
   135497     }
   135498 
   135499     /* Count non-delimiter characters. */
   135500     iStartOffset = c->iOffset;
   135501     while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
   135502       c->iOffset++;
   135503     }
   135504 
   135505     if( c->iOffset>iStartOffset ){
   135506       int n = c->iOffset-iStartOffset;
   135507       if( n>c->nAllocated ){
   135508         char *pNew;
   135509         c->nAllocated = n+20;
   135510         pNew = sqlite3_realloc(c->zToken, c->nAllocated);
   135511         if( !pNew ) return SQLITE_NOMEM;
   135512         c->zToken = pNew;
   135513       }
   135514       porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
   135515       *pzToken = c->zToken;
   135516       *piStartOffset = iStartOffset;
   135517       *piEndOffset = c->iOffset;
   135518       *piPosition = c->iToken++;
   135519       return SQLITE_OK;
   135520     }
   135521   }
   135522   return SQLITE_DONE;
   135523 }
   135524 
   135525 /*
   135526 ** The set of routines that implement the porter-stemmer tokenizer
   135527 */
   135528 static const sqlite3_tokenizer_module porterTokenizerModule = {
   135529   0,
   135530   porterCreate,
   135531   porterDestroy,
   135532   porterOpen,
   135533   porterClose,
   135534   porterNext,
   135535   0
   135536 };
   135537 
   135538 /*
   135539 ** Allocate a new porter tokenizer.  Return a pointer to the new
   135540 ** tokenizer in *ppModule
   135541 */
   135542 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
   135543   sqlite3_tokenizer_module const**ppModule
   135544 ){
   135545   *ppModule = &porterTokenizerModule;
   135546 }
   135547 
   135548 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   135549 
   135550 /************** End of fts3_porter.c *****************************************/
   135551 /************** Begin file fts3_tokenizer.c **********************************/
   135552 /*
   135553 ** 2007 June 22
   135554 **
   135555 ** The author disclaims copyright to this source code.  In place of
   135556 ** a legal notice, here is a blessing:
   135557 **
   135558 **    May you do good and not evil.
   135559 **    May you find forgiveness for yourself and forgive others.
   135560 **    May you share freely, never taking more than you give.
   135561 **
   135562 ******************************************************************************
   135563 **
   135564 ** This is part of an SQLite module implementing full-text search.
   135565 ** This particular file implements the generic tokenizer interface.
   135566 */
   135567 
   135568 /*
   135569 ** The code in this file is only compiled if:
   135570 **
   135571 **     * The FTS3 module is being built as an extension
   135572 **       (in which case SQLITE_CORE is not defined), or
   135573 **
   135574 **     * The FTS3 module is being built into the core of
   135575 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
   135576 */
   135577 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   135578 
   135579 /* #include <assert.h> */
   135580 /* #include <string.h> */
   135581 
   135582 /*
   135583 ** Implementation of the SQL scalar function for accessing the underlying
   135584 ** hash table. This function may be called as follows:
   135585 **
   135586 **   SELECT <function-name>(<key-name>);
   135587 **   SELECT <function-name>(<key-name>, <pointer>);
   135588 **
   135589 ** where <function-name> is the name passed as the second argument
   135590 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
   135591 **
   135592 ** If the <pointer> argument is specified, it must be a blob value
   135593 ** containing a pointer to be stored as the hash data corresponding
   135594 ** to the string <key-name>. If <pointer> is not specified, then
   135595 ** the string <key-name> must already exist in the has table. Otherwise,
   135596 ** an error is returned.
   135597 **
   135598 ** Whether or not the <pointer> argument is specified, the value returned
   135599 ** is a blob containing the pointer stored as the hash data corresponding
   135600 ** to string <key-name> (after the hash-table is updated, if applicable).
   135601 */
   135602 static void scalarFunc(
   135603   sqlite3_context *context,
   135604   int argc,
   135605   sqlite3_value **argv
   135606 ){
   135607   Fts3Hash *pHash;
   135608   void *pPtr = 0;
   135609   const unsigned char *zName;
   135610   int nName;
   135611 
   135612   assert( argc==1 || argc==2 );
   135613 
   135614   pHash = (Fts3Hash *)sqlite3_user_data(context);
   135615 
   135616   zName = sqlite3_value_text(argv[0]);
   135617   nName = sqlite3_value_bytes(argv[0])+1;
   135618 
   135619   if( argc==2 ){
   135620     void *pOld;
   135621     int n = sqlite3_value_bytes(argv[1]);
   135622     if( n!=sizeof(pPtr) ){
   135623       sqlite3_result_error(context, "argument type mismatch", -1);
   135624       return;
   135625     }
   135626     pPtr = *(void **)sqlite3_value_blob(argv[1]);
   135627     pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
   135628     if( pOld==pPtr ){
   135629       sqlite3_result_error(context, "out of memory", -1);
   135630       return;
   135631     }
   135632   }else{
   135633     pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
   135634     if( !pPtr ){
   135635       char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
   135636       sqlite3_result_error(context, zErr, -1);
   135637       sqlite3_free(zErr);
   135638       return;
   135639     }
   135640   }
   135641 
   135642   sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
   135643 }
   135644 
   135645 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
   135646   static const char isFtsIdChar[] = {
   135647       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
   135648       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
   135649       0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
   135650       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
   135651       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
   135652       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
   135653       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
   135654       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
   135655   };
   135656   return (c&0x80 || isFtsIdChar[(int)(c)]);
   135657 }
   135658 
   135659 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
   135660   const char *z1;
   135661   const char *z2 = 0;
   135662 
   135663   /* Find the start of the next token. */
   135664   z1 = zStr;
   135665   while( z2==0 ){
   135666     char c = *z1;
   135667     switch( c ){
   135668       case '\0': return 0;        /* No more tokens here */
   135669       case '\'':
   135670       case '"':
   135671       case '`': {
   135672         z2 = z1;
   135673         while( *++z2 && (*z2!=c || *++z2==c) );
   135674         break;
   135675       }
   135676       case '[':
   135677         z2 = &z1[1];
   135678         while( *z2 && z2[0]!=']' ) z2++;
   135679         if( *z2 ) z2++;
   135680         break;
   135681 
   135682       default:
   135683         if( sqlite3Fts3IsIdChar(*z1) ){
   135684           z2 = &z1[1];
   135685           while( sqlite3Fts3IsIdChar(*z2) ) z2++;
   135686         }else{
   135687           z1++;
   135688         }
   135689     }
   135690   }
   135691 
   135692   *pn = (int)(z2-z1);
   135693   return z1;
   135694 }
   135695 
   135696 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
   135697   Fts3Hash *pHash,                /* Tokenizer hash table */
   135698   const char *zArg,               /* Tokenizer name */
   135699   sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
   135700   char **pzErr                    /* OUT: Set to malloced error message */
   135701 ){
   135702   int rc;
   135703   char *z = (char *)zArg;
   135704   int n = 0;
   135705   char *zCopy;
   135706   char *zEnd;                     /* Pointer to nul-term of zCopy */
   135707   sqlite3_tokenizer_module *m;
   135708 
   135709   zCopy = sqlite3_mprintf("%s", zArg);
   135710   if( !zCopy ) return SQLITE_NOMEM;
   135711   zEnd = &zCopy[strlen(zCopy)];
   135712 
   135713   z = (char *)sqlite3Fts3NextToken(zCopy, &n);
   135714   z[n] = '\0';
   135715   sqlite3Fts3Dequote(z);
   135716 
   135717   m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
   135718   if( !m ){
   135719     *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
   135720     rc = SQLITE_ERROR;
   135721   }else{
   135722     char const **aArg = 0;
   135723     int iArg = 0;
   135724     z = &z[n+1];
   135725     while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
   135726       int nNew = sizeof(char *)*(iArg+1);
   135727       char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
   135728       if( !aNew ){
   135729         sqlite3_free(zCopy);
   135730         sqlite3_free((void *)aArg);
   135731         return SQLITE_NOMEM;
   135732       }
   135733       aArg = aNew;
   135734       aArg[iArg++] = z;
   135735       z[n] = '\0';
   135736       sqlite3Fts3Dequote(z);
   135737       z = &z[n+1];
   135738     }
   135739     rc = m->xCreate(iArg, aArg, ppTok);
   135740     assert( rc!=SQLITE_OK || *ppTok );
   135741     if( rc!=SQLITE_OK ){
   135742       *pzErr = sqlite3_mprintf("unknown tokenizer");
   135743     }else{
   135744       (*ppTok)->pModule = m;
   135745     }
   135746     sqlite3_free((void *)aArg);
   135747   }
   135748 
   135749   sqlite3_free(zCopy);
   135750   return rc;
   135751 }
   135752 
   135753 
   135754 #ifdef SQLITE_TEST
   135755 
   135756 #include <tcl.h>
   135757 /* #include <string.h> */
   135758 
   135759 /*
   135760 ** Implementation of a special SQL scalar function for testing tokenizers
   135761 ** designed to be used in concert with the Tcl testing framework. This
   135762 ** function must be called with two or more arguments:
   135763 **
   135764 **   SELECT <function-name>(<key-name>, ..., <input-string>);
   135765 **
   135766 ** where <function-name> is the name passed as the second argument
   135767 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
   135768 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
   135769 **
   135770 ** The return value is a string that may be interpreted as a Tcl
   135771 ** list. For each token in the <input-string>, three elements are
   135772 ** added to the returned list. The first is the token position, the
   135773 ** second is the token text (folded, stemmed, etc.) and the third is the
   135774 ** substring of <input-string> associated with the token. For example,
   135775 ** using the built-in "simple" tokenizer:
   135776 **
   135777 **   SELECT fts_tokenizer_test('simple', 'I don't see how');
   135778 **
   135779 ** will return the string:
   135780 **
   135781 **   "{0 i I 1 dont don't 2 see see 3 how how}"
   135782 **
   135783 */
   135784 static void testFunc(
   135785   sqlite3_context *context,
   135786   int argc,
   135787   sqlite3_value **argv
   135788 ){
   135789   Fts3Hash *pHash;
   135790   sqlite3_tokenizer_module *p;
   135791   sqlite3_tokenizer *pTokenizer = 0;
   135792   sqlite3_tokenizer_cursor *pCsr = 0;
   135793 
   135794   const char *zErr = 0;
   135795 
   135796   const char *zName;
   135797   int nName;
   135798   const char *zInput;
   135799   int nInput;
   135800 
   135801   const char *azArg[64];
   135802 
   135803   const char *zToken;
   135804   int nToken = 0;
   135805   int iStart = 0;
   135806   int iEnd = 0;
   135807   int iPos = 0;
   135808   int i;
   135809 
   135810   Tcl_Obj *pRet;
   135811 
   135812   if( argc<2 ){
   135813     sqlite3_result_error(context, "insufficient arguments", -1);
   135814     return;
   135815   }
   135816 
   135817   nName = sqlite3_value_bytes(argv[0]);
   135818   zName = (const char *)sqlite3_value_text(argv[0]);
   135819   nInput = sqlite3_value_bytes(argv[argc-1]);
   135820   zInput = (const char *)sqlite3_value_text(argv[argc-1]);
   135821 
   135822   pHash = (Fts3Hash *)sqlite3_user_data(context);
   135823   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
   135824 
   135825   if( !p ){
   135826     char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
   135827     sqlite3_result_error(context, zErr, -1);
   135828     sqlite3_free(zErr);
   135829     return;
   135830   }
   135831 
   135832   pRet = Tcl_NewObj();
   135833   Tcl_IncrRefCount(pRet);
   135834 
   135835   for(i=1; i<argc-1; i++){
   135836     azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
   135837   }
   135838 
   135839   if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
   135840     zErr = "error in xCreate()";
   135841     goto finish;
   135842   }
   135843   pTokenizer->pModule = p;
   135844   if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
   135845     zErr = "error in xOpen()";
   135846     goto finish;
   135847   }
   135848 
   135849   while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
   135850     Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
   135851     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
   135852     zToken = &zInput[iStart];
   135853     nToken = iEnd-iStart;
   135854     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
   135855   }
   135856 
   135857   if( SQLITE_OK!=p->xClose(pCsr) ){
   135858     zErr = "error in xClose()";
   135859     goto finish;
   135860   }
   135861   if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
   135862     zErr = "error in xDestroy()";
   135863     goto finish;
   135864   }
   135865 
   135866 finish:
   135867   if( zErr ){
   135868     sqlite3_result_error(context, zErr, -1);
   135869   }else{
   135870     sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
   135871   }
   135872   Tcl_DecrRefCount(pRet);
   135873 }
   135874 
   135875 static
   135876 int registerTokenizer(
   135877   sqlite3 *db,
   135878   char *zName,
   135879   const sqlite3_tokenizer_module *p
   135880 ){
   135881   int rc;
   135882   sqlite3_stmt *pStmt;
   135883   const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
   135884 
   135885   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
   135886   if( rc!=SQLITE_OK ){
   135887     return rc;
   135888   }
   135889 
   135890   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
   135891   sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
   135892   sqlite3_step(pStmt);
   135893 
   135894   return sqlite3_finalize(pStmt);
   135895 }
   135896 
   135897 static
   135898 int queryTokenizer(
   135899   sqlite3 *db,
   135900   char *zName,
   135901   const sqlite3_tokenizer_module **pp
   135902 ){
   135903   int rc;
   135904   sqlite3_stmt *pStmt;
   135905   const char zSql[] = "SELECT fts3_tokenizer(?)";
   135906 
   135907   *pp = 0;
   135908   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
   135909   if( rc!=SQLITE_OK ){
   135910     return rc;
   135911   }
   135912 
   135913   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
   135914   if( SQLITE_ROW==sqlite3_step(pStmt) ){
   135915     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
   135916       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
   135917     }
   135918   }
   135919 
   135920   return sqlite3_finalize(pStmt);
   135921 }
   135922 
   135923 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
   135924 
   135925 /*
   135926 ** Implementation of the scalar function fts3_tokenizer_internal_test().
   135927 ** This function is used for testing only, it is not included in the
   135928 ** build unless SQLITE_TEST is defined.
   135929 **
   135930 ** The purpose of this is to test that the fts3_tokenizer() function
   135931 ** can be used as designed by the C-code in the queryTokenizer and
   135932 ** registerTokenizer() functions above. These two functions are repeated
   135933 ** in the README.tokenizer file as an example, so it is important to
   135934 ** test them.
   135935 **
   135936 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
   135937 ** function with no arguments. An assert() will fail if a problem is
   135938 ** detected. i.e.:
   135939 **
   135940 **     SELECT fts3_tokenizer_internal_test();
   135941 **
   135942 */
   135943 static void intTestFunc(
   135944   sqlite3_context *context,
   135945   int argc,
   135946   sqlite3_value **argv
   135947 ){
   135948   int rc;
   135949   const sqlite3_tokenizer_module *p1;
   135950   const sqlite3_tokenizer_module *p2;
   135951   sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
   135952 
   135953   UNUSED_PARAMETER(argc);
   135954   UNUSED_PARAMETER(argv);
   135955 
   135956   /* Test the query function */
   135957   sqlite3Fts3SimpleTokenizerModule(&p1);
   135958   rc = queryTokenizer(db, "simple", &p2);
   135959   assert( rc==SQLITE_OK );
   135960   assert( p1==p2 );
   135961   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
   135962   assert( rc==SQLITE_ERROR );
   135963   assert( p2==0 );
   135964   assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
   135965 
   135966   /* Test the storage function */
   135967   rc = registerTokenizer(db, "nosuchtokenizer", p1);
   135968   assert( rc==SQLITE_OK );
   135969   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
   135970   assert( rc==SQLITE_OK );
   135971   assert( p2==p1 );
   135972 
   135973   sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
   135974 }
   135975 
   135976 #endif
   135977 
   135978 /*
   135979 ** Set up SQL objects in database db used to access the contents of
   135980 ** the hash table pointed to by argument pHash. The hash table must
   135981 ** been initialized to use string keys, and to take a private copy
   135982 ** of the key when a value is inserted. i.e. by a call similar to:
   135983 **
   135984 **    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
   135985 **
   135986 ** This function adds a scalar function (see header comment above
   135987 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
   135988 ** defined at compilation time, a temporary virtual table (see header
   135989 ** comment above struct HashTableVtab) to the database schema. Both
   135990 ** provide read/write access to the contents of *pHash.
   135991 **
   135992 ** The third argument to this function, zName, is used as the name
   135993 ** of both the scalar and, if created, the virtual table.
   135994 */
   135995 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
   135996   sqlite3 *db,
   135997   Fts3Hash *pHash,
   135998   const char *zName
   135999 ){
   136000   int rc = SQLITE_OK;
   136001   void *p = (void *)pHash;
   136002   const int any = SQLITE_ANY;
   136003 
   136004 #ifdef SQLITE_TEST
   136005   char *zTest = 0;
   136006   char *zTest2 = 0;
   136007   void *pdb = (void *)db;
   136008   zTest = sqlite3_mprintf("%s_test", zName);
   136009   zTest2 = sqlite3_mprintf("%s_internal_test", zName);
   136010   if( !zTest || !zTest2 ){
   136011     rc = SQLITE_NOMEM;
   136012   }
   136013 #endif
   136014 
   136015   if( SQLITE_OK==rc ){
   136016     rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
   136017   }
   136018   if( SQLITE_OK==rc ){
   136019     rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
   136020   }
   136021 #ifdef SQLITE_TEST
   136022   if( SQLITE_OK==rc ){
   136023     rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
   136024   }
   136025   if( SQLITE_OK==rc ){
   136026     rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
   136027   }
   136028 #endif
   136029 
   136030 #ifdef SQLITE_TEST
   136031   sqlite3_free(zTest);
   136032   sqlite3_free(zTest2);
   136033 #endif
   136034 
   136035   return rc;
   136036 }
   136037 
   136038 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   136039 
   136040 /************** End of fts3_tokenizer.c **************************************/
   136041 /************** Begin file fts3_tokenizer1.c *********************************/
   136042 /*
   136043 ** 2006 Oct 10
   136044 **
   136045 ** The author disclaims copyright to this source code.  In place of
   136046 ** a legal notice, here is a blessing:
   136047 **
   136048 **    May you do good and not evil.
   136049 **    May you find forgiveness for yourself and forgive others.
   136050 **    May you share freely, never taking more than you give.
   136051 **
   136052 ******************************************************************************
   136053 **
   136054 ** Implementation of the "simple" full-text-search tokenizer.
   136055 */
   136056 
   136057 /*
   136058 ** The code in this file is only compiled if:
   136059 **
   136060 **     * The FTS3 module is being built as an extension
   136061 **       (in which case SQLITE_CORE is not defined), or
   136062 **
   136063 **     * The FTS3 module is being built into the core of
   136064 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
   136065 */
   136066 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   136067 
   136068 /* #include <assert.h> */
   136069 /* #include <stdlib.h> */
   136070 /* #include <stdio.h> */
   136071 /* #include <string.h> */
   136072 
   136073 
   136074 typedef struct simple_tokenizer {
   136075   sqlite3_tokenizer base;
   136076   char delim[128];             /* flag ASCII delimiters */
   136077 } simple_tokenizer;
   136078 
   136079 typedef struct simple_tokenizer_cursor {
   136080   sqlite3_tokenizer_cursor base;
   136081   const char *pInput;          /* input we are tokenizing */
   136082   int nBytes;                  /* size of the input */
   136083   int iOffset;                 /* current position in pInput */
   136084   int iToken;                  /* index of next token to be returned */
   136085   char *pToken;                /* storage for current token */
   136086   int nTokenAllocated;         /* space allocated to zToken buffer */
   136087 } simple_tokenizer_cursor;
   136088 
   136089 
   136090 static int simpleDelim(simple_tokenizer *t, unsigned char c){
   136091   return c<0x80 && t->delim[c];
   136092 }
   136093 static int fts3_isalnum(int x){
   136094   return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
   136095 }
   136096 
   136097 /*
   136098 ** Create a new tokenizer instance.
   136099 */
   136100 static int simpleCreate(
   136101   int argc, const char * const *argv,
   136102   sqlite3_tokenizer **ppTokenizer
   136103 ){
   136104   simple_tokenizer *t;
   136105 
   136106   t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
   136107   if( t==NULL ) return SQLITE_NOMEM;
   136108   memset(t, 0, sizeof(*t));
   136109 
   136110   /* TODO(shess) Delimiters need to remain the same from run to run,
   136111   ** else we need to reindex.  One solution would be a meta-table to
   136112   ** track such information in the database, then we'd only want this
   136113   ** information on the initial create.
   136114   */
   136115   if( argc>1 ){
   136116     int i, n = (int)strlen(argv[1]);
   136117     for(i=0; i<n; i++){
   136118       unsigned char ch = argv[1][i];
   136119       /* We explicitly don't support UTF-8 delimiters for now. */
   136120       if( ch>=0x80 ){
   136121         sqlite3_free(t);
   136122         return SQLITE_ERROR;
   136123       }
   136124       t->delim[ch] = 1;
   136125     }
   136126   } else {
   136127     /* Mark non-alphanumeric ASCII characters as delimiters */
   136128     int i;
   136129     for(i=1; i<0x80; i++){
   136130       t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
   136131     }
   136132   }
   136133 
   136134   *ppTokenizer = &t->base;
   136135   return SQLITE_OK;
   136136 }
   136137 
   136138 /*
   136139 ** Destroy a tokenizer
   136140 */
   136141 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
   136142   sqlite3_free(pTokenizer);
   136143   return SQLITE_OK;
   136144 }
   136145 
   136146 /*
   136147 ** Prepare to begin tokenizing a particular string.  The input
   136148 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
   136149 ** used to incrementally tokenize this string is returned in
   136150 ** *ppCursor.
   136151 */
   136152 static int simpleOpen(
   136153   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
   136154   const char *pInput, int nBytes,        /* String to be tokenized */
   136155   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
   136156 ){
   136157   simple_tokenizer_cursor *c;
   136158 
   136159   UNUSED_PARAMETER(pTokenizer);
   136160 
   136161   c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
   136162   if( c==NULL ) return SQLITE_NOMEM;
   136163 
   136164   c->pInput = pInput;
   136165   if( pInput==0 ){
   136166     c->nBytes = 0;
   136167   }else if( nBytes<0 ){
   136168     c->nBytes = (int)strlen(pInput);
   136169   }else{
   136170     c->nBytes = nBytes;
   136171   }
   136172   c->iOffset = 0;                 /* start tokenizing at the beginning */
   136173   c->iToken = 0;
   136174   c->pToken = NULL;               /* no space allocated, yet. */
   136175   c->nTokenAllocated = 0;
   136176 
   136177   *ppCursor = &c->base;
   136178   return SQLITE_OK;
   136179 }
   136180 
   136181 /*
   136182 ** Close a tokenization cursor previously opened by a call to
   136183 ** simpleOpen() above.
   136184 */
   136185 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
   136186   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
   136187   sqlite3_free(c->pToken);
   136188   sqlite3_free(c);
   136189   return SQLITE_OK;
   136190 }
   136191 
   136192 /*
   136193 ** Extract the next token from a tokenization cursor.  The cursor must
   136194 ** have been opened by a prior call to simpleOpen().
   136195 */
   136196 static int simpleNext(
   136197   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
   136198   const char **ppToken,               /* OUT: *ppToken is the token text */
   136199   int *pnBytes,                       /* OUT: Number of bytes in token */
   136200   int *piStartOffset,                 /* OUT: Starting offset of token */
   136201   int *piEndOffset,                   /* OUT: Ending offset of token */
   136202   int *piPosition                     /* OUT: Position integer of token */
   136203 ){
   136204   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
   136205   simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
   136206   unsigned char *p = (unsigned char *)c->pInput;
   136207 
   136208   while( c->iOffset<c->nBytes ){
   136209     int iStartOffset;
   136210 
   136211     /* Scan past delimiter characters */
   136212     while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
   136213       c->iOffset++;
   136214     }
   136215 
   136216     /* Count non-delimiter characters. */
   136217     iStartOffset = c->iOffset;
   136218     while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
   136219       c->iOffset++;
   136220     }
   136221 
   136222     if( c->iOffset>iStartOffset ){
   136223       int i, n = c->iOffset-iStartOffset;
   136224       if( n>c->nTokenAllocated ){
   136225         char *pNew;
   136226         c->nTokenAllocated = n+20;
   136227         pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
   136228         if( !pNew ) return SQLITE_NOMEM;
   136229         c->pToken = pNew;
   136230       }
   136231       for(i=0; i<n; i++){
   136232         /* TODO(shess) This needs expansion to handle UTF-8
   136233         ** case-insensitivity.
   136234         */
   136235         unsigned char ch = p[iStartOffset+i];
   136236         c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
   136237       }
   136238       *ppToken = c->pToken;
   136239       *pnBytes = n;
   136240       *piStartOffset = iStartOffset;
   136241       *piEndOffset = c->iOffset;
   136242       *piPosition = c->iToken++;
   136243 
   136244       return SQLITE_OK;
   136245     }
   136246   }
   136247   return SQLITE_DONE;
   136248 }
   136249 
   136250 /*
   136251 ** The set of routines that implement the simple tokenizer
   136252 */
   136253 static const sqlite3_tokenizer_module simpleTokenizerModule = {
   136254   0,
   136255   simpleCreate,
   136256   simpleDestroy,
   136257   simpleOpen,
   136258   simpleClose,
   136259   simpleNext,
   136260   0,
   136261 };
   136262 
   136263 /*
   136264 ** Allocate a new simple tokenizer.  Return a pointer to the new
   136265 ** tokenizer in *ppModule
   136266 */
   136267 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
   136268   sqlite3_tokenizer_module const**ppModule
   136269 ){
   136270   *ppModule = &simpleTokenizerModule;
   136271 }
   136272 
   136273 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   136274 
   136275 /************** End of fts3_tokenizer1.c *************************************/
   136276 /************** Begin file fts3_tokenize_vtab.c ******************************/
   136277 /*
   136278 ** 2013 Apr 22
   136279 **
   136280 ** The author disclaims copyright to this source code.  In place of
   136281 ** a legal notice, here is a blessing:
   136282 **
   136283 **    May you do good and not evil.
   136284 **    May you find forgiveness for yourself and forgive others.
   136285 **    May you share freely, never taking more than you give.
   136286 **
   136287 ******************************************************************************
   136288 **
   136289 ** This file contains code for the "fts3tokenize" virtual table module.
   136290 ** An fts3tokenize virtual table is created as follows:
   136291 **
   136292 **   CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
   136293 **       <tokenizer-name>, <arg-1>, ...
   136294 **   );
   136295 **
   136296 ** The table created has the following schema:
   136297 **
   136298 **   CREATE TABLE <tbl>(input, token, start, end, position)
   136299 **
   136300 ** When queried, the query must include a WHERE clause of type:
   136301 **
   136302 **   input = <string>
   136303 **
   136304 ** The virtual table module tokenizes this <string>, using the FTS3
   136305 ** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
   136306 ** statement and returns one row for each token in the result. With
   136307 ** fields set as follows:
   136308 **
   136309 **   input:   Always set to a copy of <string>
   136310 **   token:   A token from the input.
   136311 **   start:   Byte offset of the token within the input <string>.
   136312 **   end:     Byte offset of the byte immediately following the end of the
   136313 **            token within the input string.
   136314 **   pos:     Token offset of token within input.
   136315 **
   136316 */
   136317 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   136318 
   136319 /* #include <string.h> */
   136320 /* #include <assert.h> */
   136321 
   136322 typedef struct Fts3tokTable Fts3tokTable;
   136323 typedef struct Fts3tokCursor Fts3tokCursor;
   136324 
   136325 /*
   136326 ** Virtual table structure.
   136327 */
   136328 struct Fts3tokTable {
   136329   sqlite3_vtab base;              /* Base class used by SQLite core */
   136330   const sqlite3_tokenizer_module *pMod;
   136331   sqlite3_tokenizer *pTok;
   136332 };
   136333 
   136334 /*
   136335 ** Virtual table cursor structure.
   136336 */
   136337 struct Fts3tokCursor {
   136338   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
   136339   char *zInput;                   /* Input string */
   136340   sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
   136341   int iRowid;                     /* Current 'rowid' value */
   136342   const char *zToken;             /* Current 'token' value */
   136343   int nToken;                     /* Size of zToken in bytes */
   136344   int iStart;                     /* Current 'start' value */
   136345   int iEnd;                       /* Current 'end' value */
   136346   int iPos;                       /* Current 'pos' value */
   136347 };
   136348 
   136349 /*
   136350 ** Query FTS for the tokenizer implementation named zName.
   136351 */
   136352 static int fts3tokQueryTokenizer(
   136353   Fts3Hash *pHash,
   136354   const char *zName,
   136355   const sqlite3_tokenizer_module **pp,
   136356   char **pzErr
   136357 ){
   136358   sqlite3_tokenizer_module *p;
   136359   int nName = (int)strlen(zName);
   136360 
   136361   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
   136362   if( !p ){
   136363     *pzErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
   136364     return SQLITE_ERROR;
   136365   }
   136366 
   136367   *pp = p;
   136368   return SQLITE_OK;
   136369 }
   136370 
   136371 /*
   136372 ** The second argument, argv[], is an array of pointers to nul-terminated
   136373 ** strings. This function makes a copy of the array and strings into a
   136374 ** single block of memory. It then dequotes any of the strings that appear
   136375 ** to be quoted.
   136376 **
   136377 ** If successful, output parameter *pazDequote is set to point at the
   136378 ** array of dequoted strings and SQLITE_OK is returned. The caller is
   136379 ** responsible for eventually calling sqlite3_free() to free the array
   136380 ** in this case. Or, if an error occurs, an SQLite error code is returned.
   136381 ** The final value of *pazDequote is undefined in this case.
   136382 */
   136383 static int fts3tokDequoteArray(
   136384   int argc,                       /* Number of elements in argv[] */
   136385   const char * const *argv,       /* Input array */
   136386   char ***pazDequote              /* Output array */
   136387 ){
   136388   int rc = SQLITE_OK;             /* Return code */
   136389   if( argc==0 ){
   136390     *pazDequote = 0;
   136391   }else{
   136392     int i;
   136393     int nByte = 0;
   136394     char **azDequote;
   136395 
   136396     for(i=0; i<argc; i++){
   136397       nByte += (int)(strlen(argv[i]) + 1);
   136398     }
   136399 
   136400     *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
   136401     if( azDequote==0 ){
   136402       rc = SQLITE_NOMEM;
   136403     }else{
   136404       char *pSpace = (char *)&azDequote[argc];
   136405       for(i=0; i<argc; i++){
   136406         int n = (int)strlen(argv[i]);
   136407         azDequote[i] = pSpace;
   136408         memcpy(pSpace, argv[i], n+1);
   136409         sqlite3Fts3Dequote(pSpace);
   136410         pSpace += (n+1);
   136411       }
   136412     }
   136413   }
   136414 
   136415   return rc;
   136416 }
   136417 
   136418 /*
   136419 ** Schema of the tokenizer table.
   136420 */
   136421 #define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
   136422 
   136423 /*
   136424 ** This function does all the work for both the xConnect and xCreate methods.
   136425 ** These tables have no persistent representation of their own, so xConnect
   136426 ** and xCreate are identical operations.
   136427 **
   136428 **   argv[0]: module name
   136429 **   argv[1]: database name
   136430 **   argv[2]: table name
   136431 **   argv[3]: first argument (tokenizer name)
   136432 */
   136433 static int fts3tokConnectMethod(
   136434   sqlite3 *db,                    /* Database connection */
   136435   void *pHash,                    /* Hash table of tokenizers */
   136436   int argc,                       /* Number of elements in argv array */
   136437   const char * const *argv,       /* xCreate/xConnect argument array */
   136438   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
   136439   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
   136440 ){
   136441   Fts3tokTable *pTab;
   136442   const sqlite3_tokenizer_module *pMod = 0;
   136443   sqlite3_tokenizer *pTok = 0;
   136444   int rc;
   136445   char **azDequote = 0;
   136446   int nDequote;
   136447 
   136448   rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
   136449   if( rc!=SQLITE_OK ) return rc;
   136450 
   136451   nDequote = argc-3;
   136452   rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
   136453 
   136454   if( rc==SQLITE_OK ){
   136455     const char *zModule;
   136456     if( nDequote<1 ){
   136457       zModule = "simple";
   136458     }else{
   136459       zModule = azDequote[0];
   136460     }
   136461     rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
   136462   }
   136463 
   136464   assert( (rc==SQLITE_OK)==(pMod!=0) );
   136465   if( rc==SQLITE_OK ){
   136466     const char * const *azArg = (const char * const *)&azDequote[1];
   136467     rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
   136468   }
   136469 
   136470   if( rc==SQLITE_OK ){
   136471     pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
   136472     if( pTab==0 ){
   136473       rc = SQLITE_NOMEM;
   136474     }
   136475   }
   136476 
   136477   if( rc==SQLITE_OK ){
   136478     memset(pTab, 0, sizeof(Fts3tokTable));
   136479     pTab->pMod = pMod;
   136480     pTab->pTok = pTok;
   136481     *ppVtab = &pTab->base;
   136482   }else{
   136483     if( pTok ){
   136484       pMod->xDestroy(pTok);
   136485     }
   136486   }
   136487 
   136488   sqlite3_free(azDequote);
   136489   return rc;
   136490 }
   136491 
   136492 /*
   136493 ** This function does the work for both the xDisconnect and xDestroy methods.
   136494 ** These tables have no persistent representation of their own, so xDisconnect
   136495 ** and xDestroy are identical operations.
   136496 */
   136497 static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
   136498   Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
   136499 
   136500   pTab->pMod->xDestroy(pTab->pTok);
   136501   sqlite3_free(pTab);
   136502   return SQLITE_OK;
   136503 }
   136504 
   136505 /*
   136506 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
   136507 */
   136508 static int fts3tokBestIndexMethod(
   136509   sqlite3_vtab *pVTab,
   136510   sqlite3_index_info *pInfo
   136511 ){
   136512   int i;
   136513   UNUSED_PARAMETER(pVTab);
   136514 
   136515   for(i=0; i<pInfo->nConstraint; i++){
   136516     if( pInfo->aConstraint[i].usable
   136517      && pInfo->aConstraint[i].iColumn==0
   136518      && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
   136519     ){
   136520       pInfo->idxNum = 1;
   136521       pInfo->aConstraintUsage[i].argvIndex = 1;
   136522       pInfo->aConstraintUsage[i].omit = 1;
   136523       pInfo->estimatedCost = 1;
   136524       return SQLITE_OK;
   136525     }
   136526   }
   136527 
   136528   pInfo->idxNum = 0;
   136529   assert( pInfo->estimatedCost>1000000.0 );
   136530 
   136531   return SQLITE_OK;
   136532 }
   136533 
   136534 /*
   136535 ** xOpen - Open a cursor.
   136536 */
   136537 static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
   136538   Fts3tokCursor *pCsr;
   136539   UNUSED_PARAMETER(pVTab);
   136540 
   136541   pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
   136542   if( pCsr==0 ){
   136543     return SQLITE_NOMEM;
   136544   }
   136545   memset(pCsr, 0, sizeof(Fts3tokCursor));
   136546 
   136547   *ppCsr = (sqlite3_vtab_cursor *)pCsr;
   136548   return SQLITE_OK;
   136549 }
   136550 
   136551 /*
   136552 ** Reset the tokenizer cursor passed as the only argument. As if it had
   136553 ** just been returned by fts3tokOpenMethod().
   136554 */
   136555 static void fts3tokResetCursor(Fts3tokCursor *pCsr){
   136556   if( pCsr->pCsr ){
   136557     Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
   136558     pTab->pMod->xClose(pCsr->pCsr);
   136559     pCsr->pCsr = 0;
   136560   }
   136561   sqlite3_free(pCsr->zInput);
   136562   pCsr->zInput = 0;
   136563   pCsr->zToken = 0;
   136564   pCsr->nToken = 0;
   136565   pCsr->iStart = 0;
   136566   pCsr->iEnd = 0;
   136567   pCsr->iPos = 0;
   136568   pCsr->iRowid = 0;
   136569 }
   136570 
   136571 /*
   136572 ** xClose - Close a cursor.
   136573 */
   136574 static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
   136575   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
   136576 
   136577   fts3tokResetCursor(pCsr);
   136578   sqlite3_free(pCsr);
   136579   return SQLITE_OK;
   136580 }
   136581 
   136582 /*
   136583 ** xNext - Advance the cursor to the next row, if any.
   136584 */
   136585 static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
   136586   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
   136587   Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
   136588   int rc;                         /* Return code */
   136589 
   136590   pCsr->iRowid++;
   136591   rc = pTab->pMod->xNext(pCsr->pCsr,
   136592       &pCsr->zToken, &pCsr->nToken,
   136593       &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
   136594   );
   136595 
   136596   if( rc!=SQLITE_OK ){
   136597     fts3tokResetCursor(pCsr);
   136598     if( rc==SQLITE_DONE ) rc = SQLITE_OK;
   136599   }
   136600 
   136601   return rc;
   136602 }
   136603 
   136604 /*
   136605 ** xFilter - Initialize a cursor to point at the start of its data.
   136606 */
   136607 static int fts3tokFilterMethod(
   136608   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
   136609   int idxNum,                     /* Strategy index */
   136610   const char *idxStr,             /* Unused */
   136611   int nVal,                       /* Number of elements in apVal */
   136612   sqlite3_value **apVal           /* Arguments for the indexing scheme */
   136613 ){
   136614   int rc = SQLITE_ERROR;
   136615   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
   136616   Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
   136617   UNUSED_PARAMETER(idxStr);
   136618   UNUSED_PARAMETER(nVal);
   136619 
   136620   fts3tokResetCursor(pCsr);
   136621   if( idxNum==1 ){
   136622     const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
   136623     int nByte = sqlite3_value_bytes(apVal[0]);
   136624     pCsr->zInput = sqlite3_malloc(nByte+1);
   136625     if( pCsr->zInput==0 ){
   136626       rc = SQLITE_NOMEM;
   136627     }else{
   136628       memcpy(pCsr->zInput, zByte, nByte);
   136629       pCsr->zInput[nByte] = 0;
   136630       rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
   136631       if( rc==SQLITE_OK ){
   136632         pCsr->pCsr->pTokenizer = pTab->pTok;
   136633       }
   136634     }
   136635   }
   136636 
   136637   if( rc!=SQLITE_OK ) return rc;
   136638   return fts3tokNextMethod(pCursor);
   136639 }
   136640 
   136641 /*
   136642 ** xEof - Return true if the cursor is at EOF, or false otherwise.
   136643 */
   136644 static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
   136645   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
   136646   return (pCsr->zToken==0);
   136647 }
   136648 
   136649 /*
   136650 ** xColumn - Return a column value.
   136651 */
   136652 static int fts3tokColumnMethod(
   136653   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
   136654   sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
   136655   int iCol                        /* Index of column to read value from */
   136656 ){
   136657   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
   136658 
   136659   /* CREATE TABLE x(input, token, start, end, position) */
   136660   switch( iCol ){
   136661     case 0:
   136662       sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
   136663       break;
   136664     case 1:
   136665       sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
   136666       break;
   136667     case 2:
   136668       sqlite3_result_int(pCtx, pCsr->iStart);
   136669       break;
   136670     case 3:
   136671       sqlite3_result_int(pCtx, pCsr->iEnd);
   136672       break;
   136673     default:
   136674       assert( iCol==4 );
   136675       sqlite3_result_int(pCtx, pCsr->iPos);
   136676       break;
   136677   }
   136678   return SQLITE_OK;
   136679 }
   136680 
   136681 /*
   136682 ** xRowid - Return the current rowid for the cursor.
   136683 */
   136684 static int fts3tokRowidMethod(
   136685   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
   136686   sqlite_int64 *pRowid            /* OUT: Rowid value */
   136687 ){
   136688   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
   136689   *pRowid = (sqlite3_int64)pCsr->iRowid;
   136690   return SQLITE_OK;
   136691 }
   136692 
   136693 /*
   136694 ** Register the fts3tok module with database connection db. Return SQLITE_OK
   136695 ** if successful or an error code if sqlite3_create_module() fails.
   136696 */
   136697 SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
   136698   static const sqlite3_module fts3tok_module = {
   136699      0,                           /* iVersion      */
   136700      fts3tokConnectMethod,        /* xCreate       */
   136701      fts3tokConnectMethod,        /* xConnect      */
   136702      fts3tokBestIndexMethod,      /* xBestIndex    */
   136703      fts3tokDisconnectMethod,     /* xDisconnect   */
   136704      fts3tokDisconnectMethod,     /* xDestroy      */
   136705      fts3tokOpenMethod,           /* xOpen         */
   136706      fts3tokCloseMethod,          /* xClose        */
   136707      fts3tokFilterMethod,         /* xFilter       */
   136708      fts3tokNextMethod,           /* xNext         */
   136709      fts3tokEofMethod,            /* xEof          */
   136710      fts3tokColumnMethod,         /* xColumn       */
   136711      fts3tokRowidMethod,          /* xRowid        */
   136712      0,                           /* xUpdate       */
   136713      0,                           /* xBegin        */
   136714      0,                           /* xSync         */
   136715      0,                           /* xCommit       */
   136716      0,                           /* xRollback     */
   136717      0,                           /* xFindFunction */
   136718      0,                           /* xRename       */
   136719      0,                           /* xSavepoint    */
   136720      0,                           /* xRelease      */
   136721      0                            /* xRollbackTo   */
   136722   };
   136723   int rc;                         /* Return code */
   136724 
   136725   rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
   136726   return rc;
   136727 }
   136728 
   136729 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   136730 
   136731 /************** End of fts3_tokenize_vtab.c **********************************/
   136732 /************** Begin file fts3_write.c **************************************/
   136733 /*
   136734 ** 2009 Oct 23
   136735 **
   136736 ** The author disclaims copyright to this source code.  In place of
   136737 ** a legal notice, here is a blessing:
   136738 **
   136739 **    May you do good and not evil.
   136740 **    May you find forgiveness for yourself and forgive others.
   136741 **    May you share freely, never taking more than you give.
   136742 **
   136743 ******************************************************************************
   136744 **
   136745 ** This file is part of the SQLite FTS3 extension module. Specifically,
   136746 ** this file contains code to insert, update and delete rows from FTS3
   136747 ** tables. It also contains code to merge FTS3 b-tree segments. Some
   136748 ** of the sub-routines used to merge segments are also used by the query
   136749 ** code in fts3.c.
   136750 */
   136751 
   136752 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   136753 
   136754 /* #include <string.h> */
   136755 /* #include <assert.h> */
   136756 /* #include <stdlib.h> */
   136757 
   136758 
   136759 #define FTS_MAX_APPENDABLE_HEIGHT 16
   136760 
   136761 /*
   136762 ** When full-text index nodes are loaded from disk, the buffer that they
   136763 ** are loaded into has the following number of bytes of padding at the end
   136764 ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
   136765 ** of 920 bytes is allocated for it.
   136766 **
   136767 ** This means that if we have a pointer into a buffer containing node data,
   136768 ** it is always safe to read up to two varints from it without risking an
   136769 ** overread, even if the node data is corrupted.
   136770 */
   136771 #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
   136772 
   136773 /*
   136774 ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
   136775 ** memory incrementally instead of all at once. This can be a big performance
   136776 ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
   136777 ** method before retrieving all query results (as may happen, for example,
   136778 ** if a query has a LIMIT clause).
   136779 **
   136780 ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
   136781 ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
   136782 ** The code is written so that the hard lower-limit for each of these values
   136783 ** is 1. Clearly such small values would be inefficient, but can be useful
   136784 ** for testing purposes.
   136785 **
   136786 ** If this module is built with SQLITE_TEST defined, these constants may
   136787 ** be overridden at runtime for testing purposes. File fts3_test.c contains
   136788 ** a Tcl interface to read and write the values.
   136789 */
   136790 #ifdef SQLITE_TEST
   136791 int test_fts3_node_chunksize = (4*1024);
   136792 int test_fts3_node_chunk_threshold = (4*1024)*4;
   136793 # define FTS3_NODE_CHUNKSIZE       test_fts3_node_chunksize
   136794 # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
   136795 #else
   136796 # define FTS3_NODE_CHUNKSIZE (4*1024)
   136797 # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
   136798 #endif
   136799 
   136800 /*
   136801 ** The two values that may be meaningfully bound to the :1 parameter in
   136802 ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
   136803 */
   136804 #define FTS_STAT_DOCTOTAL      0
   136805 #define FTS_STAT_INCRMERGEHINT 1
   136806 #define FTS_STAT_AUTOINCRMERGE 2
   136807 
   136808 /*
   136809 ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
   136810 ** and incremental merge operation that takes place. This is used for
   136811 ** debugging FTS only, it should not usually be turned on in production
   136812 ** systems.
   136813 */
   136814 #ifdef FTS3_LOG_MERGES
   136815 static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
   136816   sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
   136817 }
   136818 #else
   136819 #define fts3LogMerge(x, y)
   136820 #endif
   136821 
   136822 
   136823 typedef struct PendingList PendingList;
   136824 typedef struct SegmentNode SegmentNode;
   136825 typedef struct SegmentWriter SegmentWriter;
   136826 
   136827 /*
   136828 ** An instance of the following data structure is used to build doclists
   136829 ** incrementally. See function fts3PendingListAppend() for details.
   136830 */
   136831 struct PendingList {
   136832   int nData;
   136833   char *aData;
   136834   int nSpace;
   136835   sqlite3_int64 iLastDocid;
   136836   sqlite3_int64 iLastCol;
   136837   sqlite3_int64 iLastPos;
   136838 };
   136839 
   136840 
   136841 /*
   136842 ** Each cursor has a (possibly empty) linked list of the following objects.
   136843 */
   136844 struct Fts3DeferredToken {
   136845   Fts3PhraseToken *pToken;        /* Pointer to corresponding expr token */
   136846   int iCol;                       /* Column token must occur in */
   136847   Fts3DeferredToken *pNext;       /* Next in list of deferred tokens */
   136848   PendingList *pList;             /* Doclist is assembled here */
   136849 };
   136850 
   136851 /*
   136852 ** An instance of this structure is used to iterate through the terms on
   136853 ** a contiguous set of segment b-tree leaf nodes. Although the details of
   136854 ** this structure are only manipulated by code in this file, opaque handles
   136855 ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
   136856 ** terms when querying the full-text index. See functions:
   136857 **
   136858 **   sqlite3Fts3SegReaderNew()
   136859 **   sqlite3Fts3SegReaderFree()
   136860 **   sqlite3Fts3SegReaderIterate()
   136861 **
   136862 ** Methods used to manipulate Fts3SegReader structures:
   136863 **
   136864 **   fts3SegReaderNext()
   136865 **   fts3SegReaderFirstDocid()
   136866 **   fts3SegReaderNextDocid()
   136867 */
   136868 struct Fts3SegReader {
   136869   int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
   136870   u8 bLookup;                     /* True for a lookup only */
   136871   u8 rootOnly;                    /* True for a root-only reader */
   136872 
   136873   sqlite3_int64 iStartBlock;      /* Rowid of first leaf block to traverse */
   136874   sqlite3_int64 iLeafEndBlock;    /* Rowid of final leaf block to traverse */
   136875   sqlite3_int64 iEndBlock;        /* Rowid of final block in segment (or 0) */
   136876   sqlite3_int64 iCurrentBlock;    /* Current leaf block (or 0) */
   136877 
   136878   char *aNode;                    /* Pointer to node data (or NULL) */
   136879   int nNode;                      /* Size of buffer at aNode (or 0) */
   136880   int nPopulate;                  /* If >0, bytes of buffer aNode[] loaded */
   136881   sqlite3_blob *pBlob;            /* If not NULL, blob handle to read node */
   136882 
   136883   Fts3HashElem **ppNextElem;
   136884 
   136885   /* Variables set by fts3SegReaderNext(). These may be read directly
   136886   ** by the caller. They are valid from the time SegmentReaderNew() returns
   136887   ** until SegmentReaderNext() returns something other than SQLITE_OK
   136888   ** (i.e. SQLITE_DONE).
   136889   */
   136890   int nTerm;                      /* Number of bytes in current term */
   136891   char *zTerm;                    /* Pointer to current term */
   136892   int nTermAlloc;                 /* Allocated size of zTerm buffer */
   136893   char *aDoclist;                 /* Pointer to doclist of current entry */
   136894   int nDoclist;                   /* Size of doclist in current entry */
   136895 
   136896   /* The following variables are used by fts3SegReaderNextDocid() to iterate
   136897   ** through the current doclist (aDoclist/nDoclist).
   136898   */
   136899   char *pOffsetList;
   136900   int nOffsetList;                /* For descending pending seg-readers only */
   136901   sqlite3_int64 iDocid;
   136902 };
   136903 
   136904 #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
   136905 #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
   136906 
   136907 /*
   136908 ** An instance of this structure is used to create a segment b-tree in the
   136909 ** database. The internal details of this type are only accessed by the
   136910 ** following functions:
   136911 **
   136912 **   fts3SegWriterAdd()
   136913 **   fts3SegWriterFlush()
   136914 **   fts3SegWriterFree()
   136915 */
   136916 struct SegmentWriter {
   136917   SegmentNode *pTree;             /* Pointer to interior tree structure */
   136918   sqlite3_int64 iFirst;           /* First slot in %_segments written */
   136919   sqlite3_int64 iFree;            /* Next free slot in %_segments */
   136920   char *zTerm;                    /* Pointer to previous term buffer */
   136921   int nTerm;                      /* Number of bytes in zTerm */
   136922   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
   136923   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
   136924   int nSize;                      /* Size of allocation at aData */
   136925   int nData;                      /* Bytes of data in aData */
   136926   char *aData;                    /* Pointer to block from malloc() */
   136927   i64 nLeafData;                  /* Number of bytes of leaf data written */
   136928 };
   136929 
   136930 /*
   136931 ** Type SegmentNode is used by the following three functions to create
   136932 ** the interior part of the segment b+-tree structures (everything except
   136933 ** the leaf nodes). These functions and type are only ever used by code
   136934 ** within the fts3SegWriterXXX() family of functions described above.
   136935 **
   136936 **   fts3NodeAddTerm()
   136937 **   fts3NodeWrite()
   136938 **   fts3NodeFree()
   136939 **
   136940 ** When a b+tree is written to the database (either as a result of a merge
   136941 ** or the pending-terms table being flushed), leaves are written into the
   136942 ** database file as soon as they are completely populated. The interior of
   136943 ** the tree is assembled in memory and written out only once all leaves have
   136944 ** been populated and stored. This is Ok, as the b+-tree fanout is usually
   136945 ** very large, meaning that the interior of the tree consumes relatively
   136946 ** little memory.
   136947 */
   136948 struct SegmentNode {
   136949   SegmentNode *pParent;           /* Parent node (or NULL for root node) */
   136950   SegmentNode *pRight;            /* Pointer to right-sibling */
   136951   SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
   136952   int nEntry;                     /* Number of terms written to node so far */
   136953   char *zTerm;                    /* Pointer to previous term buffer */
   136954   int nTerm;                      /* Number of bytes in zTerm */
   136955   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
   136956   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
   136957   int nData;                      /* Bytes of valid data so far */
   136958   char *aData;                    /* Node data */
   136959 };
   136960 
   136961 /*
   136962 ** Valid values for the second argument to fts3SqlStmt().
   136963 */
   136964 #define SQL_DELETE_CONTENT             0
   136965 #define SQL_IS_EMPTY                   1
   136966 #define SQL_DELETE_ALL_CONTENT         2
   136967 #define SQL_DELETE_ALL_SEGMENTS        3
   136968 #define SQL_DELETE_ALL_SEGDIR          4
   136969 #define SQL_DELETE_ALL_DOCSIZE         5
   136970 #define SQL_DELETE_ALL_STAT            6
   136971 #define SQL_SELECT_CONTENT_BY_ROWID    7
   136972 #define SQL_NEXT_SEGMENT_INDEX         8
   136973 #define SQL_INSERT_SEGMENTS            9
   136974 #define SQL_NEXT_SEGMENTS_ID          10
   136975 #define SQL_INSERT_SEGDIR             11
   136976 #define SQL_SELECT_LEVEL              12
   136977 #define SQL_SELECT_LEVEL_RANGE        13
   136978 #define SQL_SELECT_LEVEL_COUNT        14
   136979 #define SQL_SELECT_SEGDIR_MAX_LEVEL   15
   136980 #define SQL_DELETE_SEGDIR_LEVEL       16
   136981 #define SQL_DELETE_SEGMENTS_RANGE     17
   136982 #define SQL_CONTENT_INSERT            18
   136983 #define SQL_DELETE_DOCSIZE            19
   136984 #define SQL_REPLACE_DOCSIZE           20
   136985 #define SQL_SELECT_DOCSIZE            21
   136986 #define SQL_SELECT_STAT               22
   136987 #define SQL_REPLACE_STAT              23
   136988 
   136989 #define SQL_SELECT_ALL_PREFIX_LEVEL   24
   136990 #define SQL_DELETE_ALL_TERMS_SEGDIR   25
   136991 #define SQL_DELETE_SEGDIR_RANGE       26
   136992 #define SQL_SELECT_ALL_LANGID         27
   136993 #define SQL_FIND_MERGE_LEVEL          28
   136994 #define SQL_MAX_LEAF_NODE_ESTIMATE    29
   136995 #define SQL_DELETE_SEGDIR_ENTRY       30
   136996 #define SQL_SHIFT_SEGDIR_ENTRY        31
   136997 #define SQL_SELECT_SEGDIR             32
   136998 #define SQL_CHOMP_SEGDIR              33
   136999 #define SQL_SEGMENT_IS_APPENDABLE     34
   137000 #define SQL_SELECT_INDEXES            35
   137001 #define SQL_SELECT_MXLEVEL            36
   137002 
   137003 #define SQL_SELECT_LEVEL_RANGE2       37
   137004 #define SQL_UPDATE_LEVEL_IDX          38
   137005 #define SQL_UPDATE_LEVEL              39
   137006 
   137007 /*
   137008 ** This function is used to obtain an SQLite prepared statement handle
   137009 ** for the statement identified by the second argument. If successful,
   137010 ** *pp is set to the requested statement handle and SQLITE_OK returned.
   137011 ** Otherwise, an SQLite error code is returned and *pp is set to 0.
   137012 **
   137013 ** If argument apVal is not NULL, then it must point to an array with
   137014 ** at least as many entries as the requested statement has bound
   137015 ** parameters. The values are bound to the statements parameters before
   137016 ** returning.
   137017 */
   137018 static int fts3SqlStmt(
   137019   Fts3Table *p,                   /* Virtual table handle */
   137020   int eStmt,                      /* One of the SQL_XXX constants above */
   137021   sqlite3_stmt **pp,              /* OUT: Statement handle */
   137022   sqlite3_value **apVal           /* Values to bind to statement */
   137023 ){
   137024   const char *azSql[] = {
   137025 /* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
   137026 /* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
   137027 /* 2  */  "DELETE FROM %Q.'%q_content'",
   137028 /* 3  */  "DELETE FROM %Q.'%q_segments'",
   137029 /* 4  */  "DELETE FROM %Q.'%q_segdir'",
   137030 /* 5  */  "DELETE FROM %Q.'%q_docsize'",
   137031 /* 6  */  "DELETE FROM %Q.'%q_stat'",
   137032 /* 7  */  "SELECT %s WHERE rowid=?",
   137033 /* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
   137034 /* 9  */  "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
   137035 /* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
   137036 /* 11 */  "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
   137037 
   137038           /* Return segments in order from oldest to newest.*/
   137039 /* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
   137040             "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
   137041 /* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
   137042             "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
   137043             "ORDER BY level DESC, idx ASC",
   137044 
   137045 /* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
   137046 /* 15 */  "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
   137047 
   137048 /* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
   137049 /* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
   137050 /* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%s)",
   137051 /* 19 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
   137052 /* 20 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
   137053 /* 21 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
   137054 /* 22 */  "SELECT value FROM %Q.'%q_stat' WHERE id=?",
   137055 /* 23 */  "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
   137056 /* 24 */  "",
   137057 /* 25 */  "",
   137058 
   137059 /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
   137060 /* 27 */ "SELECT DISTINCT level / (1024 * ?) FROM %Q.'%q_segdir'",
   137061 
   137062 /* This statement is used to determine which level to read the input from
   137063 ** when performing an incremental merge. It returns the absolute level number
   137064 ** of the oldest level in the db that contains at least ? segments. Or,
   137065 ** if no level in the FTS index contains more than ? segments, the statement
   137066 ** returns zero rows.  */
   137067 /* 28 */ "SELECT level FROM %Q.'%q_segdir' GROUP BY level HAVING count(*)>=?"
   137068          "  ORDER BY (level %% 1024) ASC LIMIT 1",
   137069 
   137070 /* Estimate the upper limit on the number of leaf nodes in a new segment
   137071 ** created by merging the oldest :2 segments from absolute level :1. See
   137072 ** function sqlite3Fts3Incrmerge() for details.  */
   137073 /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
   137074          "  FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
   137075 
   137076 /* SQL_DELETE_SEGDIR_ENTRY
   137077 **   Delete the %_segdir entry on absolute level :1 with index :2.  */
   137078 /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
   137079 
   137080 /* SQL_SHIFT_SEGDIR_ENTRY
   137081 **   Modify the idx value for the segment with idx=:3 on absolute level :2
   137082 **   to :1.  */
   137083 /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
   137084 
   137085 /* SQL_SELECT_SEGDIR
   137086 **   Read a single entry from the %_segdir table. The entry from absolute
   137087 **   level :1 with index value :2.  */
   137088 /* 32 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
   137089             "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
   137090 
   137091 /* SQL_CHOMP_SEGDIR
   137092 **   Update the start_block (:1) and root (:2) fields of the %_segdir
   137093 **   entry located on absolute level :3 with index :4.  */
   137094 /* 33 */  "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
   137095             "WHERE level = ? AND idx = ?",
   137096 
   137097 /* SQL_SEGMENT_IS_APPENDABLE
   137098 **   Return a single row if the segment with end_block=? is appendable. Or
   137099 **   no rows otherwise.  */
   137100 /* 34 */  "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
   137101 
   137102 /* SQL_SELECT_INDEXES
   137103 **   Return the list of valid segment indexes for absolute level ?  */
   137104 /* 35 */  "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
   137105 
   137106 /* SQL_SELECT_MXLEVEL
   137107 **   Return the largest relative level in the FTS index or indexes.  */
   137108 /* 36 */  "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'",
   137109 
   137110           /* Return segments in order from oldest to newest.*/
   137111 /* 37 */  "SELECT level, idx, end_block "
   137112             "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? "
   137113             "ORDER BY level DESC, idx ASC",
   137114 
   137115           /* Update statements used while promoting segments */
   137116 /* 38 */  "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? "
   137117             "WHERE level=? AND idx=?",
   137118 /* 39 */  "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1"
   137119 
   137120   };
   137121   int rc = SQLITE_OK;
   137122   sqlite3_stmt *pStmt;
   137123 
   137124   assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
   137125   assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
   137126 
   137127   pStmt = p->aStmt[eStmt];
   137128   if( !pStmt ){
   137129     char *zSql;
   137130     if( eStmt==SQL_CONTENT_INSERT ){
   137131       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
   137132     }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
   137133       zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
   137134     }else{
   137135       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
   137136     }
   137137     if( !zSql ){
   137138       rc = SQLITE_NOMEM;
   137139     }else{
   137140       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
   137141       sqlite3_free(zSql);
   137142       assert( rc==SQLITE_OK || pStmt==0 );
   137143       p->aStmt[eStmt] = pStmt;
   137144     }
   137145   }
   137146   if( apVal ){
   137147     int i;
   137148     int nParam = sqlite3_bind_parameter_count(pStmt);
   137149     for(i=0; rc==SQLITE_OK && i<nParam; i++){
   137150       rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
   137151     }
   137152   }
   137153   *pp = pStmt;
   137154   return rc;
   137155 }
   137156 
   137157 
   137158 static int fts3SelectDocsize(
   137159   Fts3Table *pTab,                /* FTS3 table handle */
   137160   sqlite3_int64 iDocid,           /* Docid to bind for SQL_SELECT_DOCSIZE */
   137161   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
   137162 ){
   137163   sqlite3_stmt *pStmt = 0;        /* Statement requested from fts3SqlStmt() */
   137164   int rc;                         /* Return code */
   137165 
   137166   rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
   137167   if( rc==SQLITE_OK ){
   137168     sqlite3_bind_int64(pStmt, 1, iDocid);
   137169     rc = sqlite3_step(pStmt);
   137170     if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
   137171       rc = sqlite3_reset(pStmt);
   137172       if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
   137173       pStmt = 0;
   137174     }else{
   137175       rc = SQLITE_OK;
   137176     }
   137177   }
   137178 
   137179   *ppStmt = pStmt;
   137180   return rc;
   137181 }
   137182 
   137183 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
   137184   Fts3Table *pTab,                /* Fts3 table handle */
   137185   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
   137186 ){
   137187   sqlite3_stmt *pStmt = 0;
   137188   int rc;
   137189   rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
   137190   if( rc==SQLITE_OK ){
   137191     sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
   137192     if( sqlite3_step(pStmt)!=SQLITE_ROW
   137193      || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
   137194     ){
   137195       rc = sqlite3_reset(pStmt);
   137196       if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
   137197       pStmt = 0;
   137198     }
   137199   }
   137200   *ppStmt = pStmt;
   137201   return rc;
   137202 }
   137203 
   137204 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
   137205   Fts3Table *pTab,                /* Fts3 table handle */
   137206   sqlite3_int64 iDocid,           /* Docid to read size data for */
   137207   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
   137208 ){
   137209   return fts3SelectDocsize(pTab, iDocid, ppStmt);
   137210 }
   137211 
   137212 /*
   137213 ** Similar to fts3SqlStmt(). Except, after binding the parameters in
   137214 ** array apVal[] to the SQL statement identified by eStmt, the statement
   137215 ** is executed.
   137216 **
   137217 ** Returns SQLITE_OK if the statement is successfully executed, or an
   137218 ** SQLite error code otherwise.
   137219 */
   137220 static void fts3SqlExec(
   137221   int *pRC,                /* Result code */
   137222   Fts3Table *p,            /* The FTS3 table */
   137223   int eStmt,               /* Index of statement to evaluate */
   137224   sqlite3_value **apVal    /* Parameters to bind */
   137225 ){
   137226   sqlite3_stmt *pStmt;
   137227   int rc;
   137228   if( *pRC ) return;
   137229   rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
   137230   if( rc==SQLITE_OK ){
   137231     sqlite3_step(pStmt);
   137232     rc = sqlite3_reset(pStmt);
   137233   }
   137234   *pRC = rc;
   137235 }
   137236 
   137237 
   137238 /*
   137239 ** This function ensures that the caller has obtained an exclusive
   137240 ** shared-cache table-lock on the %_segdir table. This is required before
   137241 ** writing data to the fts3 table. If this lock is not acquired first, then
   137242 ** the caller may end up attempting to take this lock as part of committing
   137243 ** a transaction, causing SQLite to return SQLITE_LOCKED or
   137244 ** LOCKED_SHAREDCACHEto a COMMIT command.
   137245 **
   137246 ** It is best to avoid this because if FTS3 returns any error when
   137247 ** committing a transaction, the whole transaction will be rolled back.
   137248 ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
   137249 ** It can still happen if the user locks the underlying tables directly
   137250 ** instead of accessing them via FTS.
   137251 */
   137252 static int fts3Writelock(Fts3Table *p){
   137253   int rc = SQLITE_OK;
   137254 
   137255   if( p->nPendingData==0 ){
   137256     sqlite3_stmt *pStmt;
   137257     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
   137258     if( rc==SQLITE_OK ){
   137259       sqlite3_bind_null(pStmt, 1);
   137260       sqlite3_step(pStmt);
   137261       rc = sqlite3_reset(pStmt);
   137262     }
   137263   }
   137264 
   137265   return rc;
   137266 }
   137267 
   137268 /*
   137269 ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
   137270 ** Within each language id, a separate index is maintained to store the
   137271 ** document terms, and each configured prefix size (configured the FTS
   137272 ** "prefix=" option). And each index consists of multiple levels ("relative
   137273 ** levels").
   137274 **
   137275 ** All three of these values (the language id, the specific index and the
   137276 ** level within the index) are encoded in 64-bit integer values stored
   137277 ** in the %_segdir table on disk. This function is used to convert three
   137278 ** separate component values into the single 64-bit integer value that
   137279 ** can be used to query the %_segdir table.
   137280 **
   137281 ** Specifically, each language-id/index combination is allocated 1024
   137282 ** 64-bit integer level values ("absolute levels"). The main terms index
   137283 ** for language-id 0 is allocate values 0-1023. The first prefix index
   137284 ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
   137285 ** Language 1 indexes are allocated immediately following language 0.
   137286 **
   137287 ** So, for a system with nPrefix prefix indexes configured, the block of
   137288 ** absolute levels that corresponds to language-id iLangid and index
   137289 ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
   137290 */
   137291 static sqlite3_int64 getAbsoluteLevel(
   137292   Fts3Table *p,                   /* FTS3 table handle */
   137293   int iLangid,                    /* Language id */
   137294   int iIndex,                     /* Index in p->aIndex[] */
   137295   int iLevel                      /* Level of segments */
   137296 ){
   137297   sqlite3_int64 iBase;            /* First absolute level for iLangid/iIndex */
   137298   assert( iLangid>=0 );
   137299   assert( p->nIndex>0 );
   137300   assert( iIndex>=0 && iIndex<p->nIndex );
   137301 
   137302   iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
   137303   return iBase + iLevel;
   137304 }
   137305 
   137306 /*
   137307 ** Set *ppStmt to a statement handle that may be used to iterate through
   137308 ** all rows in the %_segdir table, from oldest to newest. If successful,
   137309 ** return SQLITE_OK. If an error occurs while preparing the statement,
   137310 ** return an SQLite error code.
   137311 **
   137312 ** There is only ever one instance of this SQL statement compiled for
   137313 ** each FTS3 table.
   137314 **
   137315 ** The statement returns the following columns from the %_segdir table:
   137316 **
   137317 **   0: idx
   137318 **   1: start_block
   137319 **   2: leaves_end_block
   137320 **   3: end_block
   137321 **   4: root
   137322 */
   137323 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
   137324   Fts3Table *p,                   /* FTS3 table */
   137325   int iLangid,                    /* Language being queried */
   137326   int iIndex,                     /* Index for p->aIndex[] */
   137327   int iLevel,                     /* Level to select (relative level) */
   137328   sqlite3_stmt **ppStmt           /* OUT: Compiled statement */
   137329 ){
   137330   int rc;
   137331   sqlite3_stmt *pStmt = 0;
   137332 
   137333   assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
   137334   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
   137335   assert( iIndex>=0 && iIndex<p->nIndex );
   137336 
   137337   if( iLevel<0 ){
   137338     /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
   137339     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
   137340     if( rc==SQLITE_OK ){
   137341       sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
   137342       sqlite3_bind_int64(pStmt, 2,
   137343           getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
   137344       );
   137345     }
   137346   }else{
   137347     /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
   137348     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
   137349     if( rc==SQLITE_OK ){
   137350       sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
   137351     }
   137352   }
   137353   *ppStmt = pStmt;
   137354   return rc;
   137355 }
   137356 
   137357 
   137358 /*
   137359 ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
   137360 ** if successful, or an SQLite error code otherwise.
   137361 **
   137362 ** This function also serves to allocate the PendingList structure itself.
   137363 ** For example, to create a new PendingList structure containing two
   137364 ** varints:
   137365 **
   137366 **   PendingList *p = 0;
   137367 **   fts3PendingListAppendVarint(&p, 1);
   137368 **   fts3PendingListAppendVarint(&p, 2);
   137369 */
   137370 static int fts3PendingListAppendVarint(
   137371   PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
   137372   sqlite3_int64 i                 /* Value to append to data */
   137373 ){
   137374   PendingList *p = *pp;
   137375 
   137376   /* Allocate or grow the PendingList as required. */
   137377   if( !p ){
   137378     p = sqlite3_malloc(sizeof(*p) + 100);
   137379     if( !p ){
   137380       return SQLITE_NOMEM;
   137381     }
   137382     p->nSpace = 100;
   137383     p->aData = (char *)&p[1];
   137384     p->nData = 0;
   137385   }
   137386   else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
   137387     int nNew = p->nSpace * 2;
   137388     p = sqlite3_realloc(p, sizeof(*p) + nNew);
   137389     if( !p ){
   137390       sqlite3_free(*pp);
   137391       *pp = 0;
   137392       return SQLITE_NOMEM;
   137393     }
   137394     p->nSpace = nNew;
   137395     p->aData = (char *)&p[1];
   137396   }
   137397 
   137398   /* Append the new serialized varint to the end of the list. */
   137399   p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
   137400   p->aData[p->nData] = '\0';
   137401   *pp = p;
   137402   return SQLITE_OK;
   137403 }
   137404 
   137405 /*
   137406 ** Add a docid/column/position entry to a PendingList structure. Non-zero
   137407 ** is returned if the structure is sqlite3_realloced as part of adding
   137408 ** the entry. Otherwise, zero.
   137409 **
   137410 ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
   137411 ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
   137412 ** it is set to SQLITE_OK.
   137413 */
   137414 static int fts3PendingListAppend(
   137415   PendingList **pp,               /* IN/OUT: PendingList structure */
   137416   sqlite3_int64 iDocid,           /* Docid for entry to add */
   137417   sqlite3_int64 iCol,             /* Column for entry to add */
   137418   sqlite3_int64 iPos,             /* Position of term for entry to add */
   137419   int *pRc                        /* OUT: Return code */
   137420 ){
   137421   PendingList *p = *pp;
   137422   int rc = SQLITE_OK;
   137423 
   137424   assert( !p || p->iLastDocid<=iDocid );
   137425 
   137426   if( !p || p->iLastDocid!=iDocid ){
   137427     sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
   137428     if( p ){
   137429       assert( p->nData<p->nSpace );
   137430       assert( p->aData[p->nData]==0 );
   137431       p->nData++;
   137432     }
   137433     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
   137434       goto pendinglistappend_out;
   137435     }
   137436     p->iLastCol = -1;
   137437     p->iLastPos = 0;
   137438     p->iLastDocid = iDocid;
   137439   }
   137440   if( iCol>0 && p->iLastCol!=iCol ){
   137441     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
   137442      || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
   137443     ){
   137444       goto pendinglistappend_out;
   137445     }
   137446     p->iLastCol = iCol;
   137447     p->iLastPos = 0;
   137448   }
   137449   if( iCol>=0 ){
   137450     assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
   137451     rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
   137452     if( rc==SQLITE_OK ){
   137453       p->iLastPos = iPos;
   137454     }
   137455   }
   137456 
   137457  pendinglistappend_out:
   137458   *pRc = rc;
   137459   if( p!=*pp ){
   137460     *pp = p;
   137461     return 1;
   137462   }
   137463   return 0;
   137464 }
   137465 
   137466 /*
   137467 ** Free a PendingList object allocated by fts3PendingListAppend().
   137468 */
   137469 static void fts3PendingListDelete(PendingList *pList){
   137470   sqlite3_free(pList);
   137471 }
   137472 
   137473 /*
   137474 ** Add an entry to one of the pending-terms hash tables.
   137475 */
   137476 static int fts3PendingTermsAddOne(
   137477   Fts3Table *p,
   137478   int iCol,
   137479   int iPos,
   137480   Fts3Hash *pHash,                /* Pending terms hash table to add entry to */
   137481   const char *zToken,
   137482   int nToken
   137483 ){
   137484   PendingList *pList;
   137485   int rc = SQLITE_OK;
   137486 
   137487   pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
   137488   if( pList ){
   137489     p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
   137490   }
   137491   if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
   137492     if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
   137493       /* Malloc failed while inserting the new entry. This can only
   137494       ** happen if there was no previous entry for this token.
   137495       */
   137496       assert( 0==fts3HashFind(pHash, zToken, nToken) );
   137497       sqlite3_free(pList);
   137498       rc = SQLITE_NOMEM;
   137499     }
   137500   }
   137501   if( rc==SQLITE_OK ){
   137502     p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
   137503   }
   137504   return rc;
   137505 }
   137506 
   137507 /*
   137508 ** Tokenize the nul-terminated string zText and add all tokens to the
   137509 ** pending-terms hash-table. The docid used is that currently stored in
   137510 ** p->iPrevDocid, and the column is specified by argument iCol.
   137511 **
   137512 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
   137513 */
   137514 static int fts3PendingTermsAdd(
   137515   Fts3Table *p,                   /* Table into which text will be inserted */
   137516   int iLangid,                    /* Language id to use */
   137517   const char *zText,              /* Text of document to be inserted */
   137518   int iCol,                       /* Column into which text is being inserted */
   137519   u32 *pnWord                     /* IN/OUT: Incr. by number tokens inserted */
   137520 ){
   137521   int rc;
   137522   int iStart = 0;
   137523   int iEnd = 0;
   137524   int iPos = 0;
   137525   int nWord = 0;
   137526 
   137527   char const *zToken;
   137528   int nToken = 0;
   137529 
   137530   sqlite3_tokenizer *pTokenizer = p->pTokenizer;
   137531   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
   137532   sqlite3_tokenizer_cursor *pCsr;
   137533   int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
   137534       const char**,int*,int*,int*,int*);
   137535 
   137536   assert( pTokenizer && pModule );
   137537 
   137538   /* If the user has inserted a NULL value, this function may be called with
   137539   ** zText==0. In this case, add zero token entries to the hash table and
   137540   ** return early. */
   137541   if( zText==0 ){
   137542     *pnWord = 0;
   137543     return SQLITE_OK;
   137544   }
   137545 
   137546   rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
   137547   if( rc!=SQLITE_OK ){
   137548     return rc;
   137549   }
   137550 
   137551   xNext = pModule->xNext;
   137552   while( SQLITE_OK==rc
   137553       && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
   137554   ){
   137555     int i;
   137556     if( iPos>=nWord ) nWord = iPos+1;
   137557 
   137558     /* Positions cannot be negative; we use -1 as a terminator internally.
   137559     ** Tokens must have a non-zero length.
   137560     */
   137561     if( iPos<0 || !zToken || nToken<=0 ){
   137562       rc = SQLITE_ERROR;
   137563       break;
   137564     }
   137565 
   137566     /* Add the term to the terms index */
   137567     rc = fts3PendingTermsAddOne(
   137568         p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
   137569     );
   137570 
   137571     /* Add the term to each of the prefix indexes that it is not too
   137572     ** short for. */
   137573     for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
   137574       struct Fts3Index *pIndex = &p->aIndex[i];
   137575       if( nToken<pIndex->nPrefix ) continue;
   137576       rc = fts3PendingTermsAddOne(
   137577           p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
   137578       );
   137579     }
   137580   }
   137581 
   137582   pModule->xClose(pCsr);
   137583   *pnWord += nWord;
   137584   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
   137585 }
   137586 
   137587 /*
   137588 ** Calling this function indicates that subsequent calls to
   137589 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
   137590 ** contents of the document with docid iDocid.
   137591 */
   137592 static int fts3PendingTermsDocid(
   137593   Fts3Table *p,                   /* Full-text table handle */
   137594   int iLangid,                    /* Language id of row being written */
   137595   sqlite_int64 iDocid             /* Docid of row being written */
   137596 ){
   137597   assert( iLangid>=0 );
   137598 
   137599   /* TODO(shess) Explore whether partially flushing the buffer on
   137600   ** forced-flush would provide better performance.  I suspect that if
   137601   ** we ordered the doclists by size and flushed the largest until the
   137602   ** buffer was half empty, that would let the less frequent terms
   137603   ** generate longer doclists.
   137604   */
   137605   if( iDocid<=p->iPrevDocid
   137606    || p->iPrevLangid!=iLangid
   137607    || p->nPendingData>p->nMaxPendingData
   137608   ){
   137609     int rc = sqlite3Fts3PendingTermsFlush(p);
   137610     if( rc!=SQLITE_OK ) return rc;
   137611   }
   137612   p->iPrevDocid = iDocid;
   137613   p->iPrevLangid = iLangid;
   137614   return SQLITE_OK;
   137615 }
   137616 
   137617 /*
   137618 ** Discard the contents of the pending-terms hash tables.
   137619 */
   137620 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
   137621   int i;
   137622   for(i=0; i<p->nIndex; i++){
   137623     Fts3HashElem *pElem;
   137624     Fts3Hash *pHash = &p->aIndex[i].hPending;
   137625     for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
   137626       PendingList *pList = (PendingList *)fts3HashData(pElem);
   137627       fts3PendingListDelete(pList);
   137628     }
   137629     fts3HashClear(pHash);
   137630   }
   137631   p->nPendingData = 0;
   137632 }
   137633 
   137634 /*
   137635 ** This function is called by the xUpdate() method as part of an INSERT
   137636 ** operation. It adds entries for each term in the new record to the
   137637 ** pendingTerms hash table.
   137638 **
   137639 ** Argument apVal is the same as the similarly named argument passed to
   137640 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
   137641 */
   137642 static int fts3InsertTerms(
   137643   Fts3Table *p,
   137644   int iLangid,
   137645   sqlite3_value **apVal,
   137646   u32 *aSz
   137647 ){
   137648   int i;                          /* Iterator variable */
   137649   for(i=2; i<p->nColumn+2; i++){
   137650     int iCol = i-2;
   137651     if( p->abNotindexed[iCol]==0 ){
   137652       const char *zText = (const char *)sqlite3_value_text(apVal[i]);
   137653       int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
   137654       if( rc!=SQLITE_OK ){
   137655         return rc;
   137656       }
   137657       aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
   137658     }
   137659   }
   137660   return SQLITE_OK;
   137661 }
   137662 
   137663 /*
   137664 ** This function is called by the xUpdate() method for an INSERT operation.
   137665 ** The apVal parameter is passed a copy of the apVal argument passed by
   137666 ** SQLite to the xUpdate() method. i.e:
   137667 **
   137668 **   apVal[0]                Not used for INSERT.
   137669 **   apVal[1]                rowid
   137670 **   apVal[2]                Left-most user-defined column
   137671 **   ...
   137672 **   apVal[p->nColumn+1]     Right-most user-defined column
   137673 **   apVal[p->nColumn+2]     Hidden column with same name as table
   137674 **   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
   137675 **   apVal[p->nColumn+4]     Hidden languageid column
   137676 */
   137677 static int fts3InsertData(
   137678   Fts3Table *p,                   /* Full-text table */
   137679   sqlite3_value **apVal,          /* Array of values to insert */
   137680   sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
   137681 ){
   137682   int rc;                         /* Return code */
   137683   sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
   137684 
   137685   if( p->zContentTbl ){
   137686     sqlite3_value *pRowid = apVal[p->nColumn+3];
   137687     if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
   137688       pRowid = apVal[1];
   137689     }
   137690     if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
   137691       return SQLITE_CONSTRAINT;
   137692     }
   137693     *piDocid = sqlite3_value_int64(pRowid);
   137694     return SQLITE_OK;
   137695   }
   137696 
   137697   /* Locate the statement handle used to insert data into the %_content
   137698   ** table. The SQL for this statement is:
   137699   **
   137700   **   INSERT INTO %_content VALUES(?, ?, ?, ...)
   137701   **
   137702   ** The statement features N '?' variables, where N is the number of user
   137703   ** defined columns in the FTS3 table, plus one for the docid field.
   137704   */
   137705   rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
   137706   if( rc==SQLITE_OK && p->zLanguageid ){
   137707     rc = sqlite3_bind_int(
   137708         pContentInsert, p->nColumn+2,
   137709         sqlite3_value_int(apVal[p->nColumn+4])
   137710     );
   137711   }
   137712   if( rc!=SQLITE_OK ) return rc;
   137713 
   137714   /* There is a quirk here. The users INSERT statement may have specified
   137715   ** a value for the "rowid" field, for the "docid" field, or for both.
   137716   ** Which is a problem, since "rowid" and "docid" are aliases for the
   137717   ** same value. For example:
   137718   **
   137719   **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
   137720   **
   137721   ** In FTS3, this is an error. It is an error to specify non-NULL values
   137722   ** for both docid and some other rowid alias.
   137723   */
   137724   if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
   137725     if( SQLITE_NULL==sqlite3_value_type(apVal[0])
   137726      && SQLITE_NULL!=sqlite3_value_type(apVal[1])
   137727     ){
   137728       /* A rowid/docid conflict. */
   137729       return SQLITE_ERROR;
   137730     }
   137731     rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
   137732     if( rc!=SQLITE_OK ) return rc;
   137733   }
   137734 
   137735   /* Execute the statement to insert the record. Set *piDocid to the
   137736   ** new docid value.
   137737   */
   137738   sqlite3_step(pContentInsert);
   137739   rc = sqlite3_reset(pContentInsert);
   137740 
   137741   *piDocid = sqlite3_last_insert_rowid(p->db);
   137742   return rc;
   137743 }
   137744 
   137745 
   137746 
   137747 /*
   137748 ** Remove all data from the FTS3 table. Clear the hash table containing
   137749 ** pending terms.
   137750 */
   137751 static int fts3DeleteAll(Fts3Table *p, int bContent){
   137752   int rc = SQLITE_OK;             /* Return code */
   137753 
   137754   /* Discard the contents of the pending-terms hash table. */
   137755   sqlite3Fts3PendingTermsClear(p);
   137756 
   137757   /* Delete everything from the shadow tables. Except, leave %_content as
   137758   ** is if bContent is false.  */
   137759   assert( p->zContentTbl==0 || bContent==0 );
   137760   if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
   137761   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
   137762   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
   137763   if( p->bHasDocsize ){
   137764     fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
   137765   }
   137766   if( p->bHasStat ){
   137767     fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
   137768   }
   137769   return rc;
   137770 }
   137771 
   137772 /*
   137773 **
   137774 */
   137775 static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
   137776   int iLangid = 0;
   137777   if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
   137778   return iLangid;
   137779 }
   137780 
   137781 /*
   137782 ** The first element in the apVal[] array is assumed to contain the docid
   137783 ** (an integer) of a row about to be deleted. Remove all terms from the
   137784 ** full-text index.
   137785 */
   137786 static void fts3DeleteTerms(
   137787   int *pRC,               /* Result code */
   137788   Fts3Table *p,           /* The FTS table to delete from */
   137789   sqlite3_value *pRowid,  /* The docid to be deleted */
   137790   u32 *aSz,               /* Sizes of deleted document written here */
   137791   int *pbFound            /* OUT: Set to true if row really does exist */
   137792 ){
   137793   int rc;
   137794   sqlite3_stmt *pSelect;
   137795 
   137796   assert( *pbFound==0 );
   137797   if( *pRC ) return;
   137798   rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
   137799   if( rc==SQLITE_OK ){
   137800     if( SQLITE_ROW==sqlite3_step(pSelect) ){
   137801       int i;
   137802       int iLangid = langidFromSelect(p, pSelect);
   137803       rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pSelect, 0));
   137804       for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
   137805         int iCol = i-1;
   137806         if( p->abNotindexed[iCol]==0 ){
   137807           const char *zText = (const char *)sqlite3_column_text(pSelect, i);
   137808           rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
   137809           aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
   137810         }
   137811       }
   137812       if( rc!=SQLITE_OK ){
   137813         sqlite3_reset(pSelect);
   137814         *pRC = rc;
   137815         return;
   137816       }
   137817       *pbFound = 1;
   137818     }
   137819     rc = sqlite3_reset(pSelect);
   137820   }else{
   137821     sqlite3_reset(pSelect);
   137822   }
   137823   *pRC = rc;
   137824 }
   137825 
   137826 /*
   137827 ** Forward declaration to account for the circular dependency between
   137828 ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
   137829 */
   137830 static int fts3SegmentMerge(Fts3Table *, int, int, int);
   137831 
   137832 /*
   137833 ** This function allocates a new level iLevel index in the segdir table.
   137834 ** Usually, indexes are allocated within a level sequentially starting
   137835 ** with 0, so the allocated index is one greater than the value returned
   137836 ** by:
   137837 **
   137838 **   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
   137839 **
   137840 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
   137841 ** level, they are merged into a single level (iLevel+1) segment and the
   137842 ** allocated index is 0.
   137843 **
   137844 ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
   137845 ** returned. Otherwise, an SQLite error code is returned.
   137846 */
   137847 static int fts3AllocateSegdirIdx(
   137848   Fts3Table *p,
   137849   int iLangid,                    /* Language id */
   137850   int iIndex,                     /* Index for p->aIndex */
   137851   int iLevel,
   137852   int *piIdx
   137853 ){
   137854   int rc;                         /* Return Code */
   137855   sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
   137856   int iNext = 0;                  /* Result of query pNextIdx */
   137857 
   137858   assert( iLangid>=0 );
   137859   assert( p->nIndex>=1 );
   137860 
   137861   /* Set variable iNext to the next available segdir index at level iLevel. */
   137862   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
   137863   if( rc==SQLITE_OK ){
   137864     sqlite3_bind_int64(
   137865         pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
   137866     );
   137867     if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
   137868       iNext = sqlite3_column_int(pNextIdx, 0);
   137869     }
   137870     rc = sqlite3_reset(pNextIdx);
   137871   }
   137872 
   137873   if( rc==SQLITE_OK ){
   137874     /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
   137875     ** full, merge all segments in level iLevel into a single iLevel+1
   137876     ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
   137877     ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
   137878     */
   137879     if( iNext>=FTS3_MERGE_COUNT ){
   137880       fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
   137881       rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
   137882       *piIdx = 0;
   137883     }else{
   137884       *piIdx = iNext;
   137885     }
   137886   }
   137887 
   137888   return rc;
   137889 }
   137890 
   137891 /*
   137892 ** The %_segments table is declared as follows:
   137893 **
   137894 **   CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
   137895 **
   137896 ** This function reads data from a single row of the %_segments table. The
   137897 ** specific row is identified by the iBlockid parameter. If paBlob is not
   137898 ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
   137899 ** with the contents of the blob stored in the "block" column of the
   137900 ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
   137901 ** to the size of the blob in bytes before returning.
   137902 **
   137903 ** If an error occurs, or the table does not contain the specified row,
   137904 ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
   137905 ** paBlob is non-NULL, then it is the responsibility of the caller to
   137906 ** eventually free the returned buffer.
   137907 **
   137908 ** This function may leave an open sqlite3_blob* handle in the
   137909 ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
   137910 ** to this function. The handle may be closed by calling the
   137911 ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
   137912 ** performance improvement, but the blob handle should always be closed
   137913 ** before control is returned to the user (to prevent a lock being held
   137914 ** on the database file for longer than necessary). Thus, any virtual table
   137915 ** method (xFilter etc.) that may directly or indirectly call this function
   137916 ** must call sqlite3Fts3SegmentsClose() before returning.
   137917 */
   137918 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
   137919   Fts3Table *p,                   /* FTS3 table handle */
   137920   sqlite3_int64 iBlockid,         /* Access the row with blockid=$iBlockid */
   137921   char **paBlob,                  /* OUT: Blob data in malloc'd buffer */
   137922   int *pnBlob,                    /* OUT: Size of blob data */
   137923   int *pnLoad                     /* OUT: Bytes actually loaded */
   137924 ){
   137925   int rc;                         /* Return code */
   137926 
   137927   /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
   137928   assert( pnBlob );
   137929 
   137930   if( p->pSegments ){
   137931     rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
   137932   }else{
   137933     if( 0==p->zSegmentsTbl ){
   137934       p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
   137935       if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
   137936     }
   137937     rc = sqlite3_blob_open(
   137938        p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
   137939     );
   137940   }
   137941 
   137942   if( rc==SQLITE_OK ){
   137943     int nByte = sqlite3_blob_bytes(p->pSegments);
   137944     *pnBlob = nByte;
   137945     if( paBlob ){
   137946       char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
   137947       if( !aByte ){
   137948         rc = SQLITE_NOMEM;
   137949       }else{
   137950         if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
   137951           nByte = FTS3_NODE_CHUNKSIZE;
   137952           *pnLoad = nByte;
   137953         }
   137954         rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
   137955         memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
   137956         if( rc!=SQLITE_OK ){
   137957           sqlite3_free(aByte);
   137958           aByte = 0;
   137959         }
   137960       }
   137961       *paBlob = aByte;
   137962     }
   137963   }
   137964 
   137965   return rc;
   137966 }
   137967 
   137968 /*
   137969 ** Close the blob handle at p->pSegments, if it is open. See comments above
   137970 ** the sqlite3Fts3ReadBlock() function for details.
   137971 */
   137972 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
   137973   sqlite3_blob_close(p->pSegments);
   137974   p->pSegments = 0;
   137975 }
   137976 
   137977 static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
   137978   int nRead;                      /* Number of bytes to read */
   137979   int rc;                         /* Return code */
   137980 
   137981   nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
   137982   rc = sqlite3_blob_read(
   137983       pReader->pBlob,
   137984       &pReader->aNode[pReader->nPopulate],
   137985       nRead,
   137986       pReader->nPopulate
   137987   );
   137988 
   137989   if( rc==SQLITE_OK ){
   137990     pReader->nPopulate += nRead;
   137991     memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
   137992     if( pReader->nPopulate==pReader->nNode ){
   137993       sqlite3_blob_close(pReader->pBlob);
   137994       pReader->pBlob = 0;
   137995       pReader->nPopulate = 0;
   137996     }
   137997   }
   137998   return rc;
   137999 }
   138000 
   138001 static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
   138002   int rc = SQLITE_OK;
   138003   assert( !pReader->pBlob
   138004        || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
   138005   );
   138006   while( pReader->pBlob && rc==SQLITE_OK
   138007      &&  (pFrom - pReader->aNode + nByte)>pReader->nPopulate
   138008   ){
   138009     rc = fts3SegReaderIncrRead(pReader);
   138010   }
   138011   return rc;
   138012 }
   138013 
   138014 /*
   138015 ** Set an Fts3SegReader cursor to point at EOF.
   138016 */
   138017 static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
   138018   if( !fts3SegReaderIsRootOnly(pSeg) ){
   138019     sqlite3_free(pSeg->aNode);
   138020     sqlite3_blob_close(pSeg->pBlob);
   138021     pSeg->pBlob = 0;
   138022   }
   138023   pSeg->aNode = 0;
   138024 }
   138025 
   138026 /*
   138027 ** Move the iterator passed as the first argument to the next term in the
   138028 ** segment. If successful, SQLITE_OK is returned. If there is no next term,
   138029 ** SQLITE_DONE. Otherwise, an SQLite error code.
   138030 */
   138031 static int fts3SegReaderNext(
   138032   Fts3Table *p,
   138033   Fts3SegReader *pReader,
   138034   int bIncr
   138035 ){
   138036   int rc;                         /* Return code of various sub-routines */
   138037   char *pNext;                    /* Cursor variable */
   138038   int nPrefix;                    /* Number of bytes in term prefix */
   138039   int nSuffix;                    /* Number of bytes in term suffix */
   138040 
   138041   if( !pReader->aDoclist ){
   138042     pNext = pReader->aNode;
   138043   }else{
   138044     pNext = &pReader->aDoclist[pReader->nDoclist];
   138045   }
   138046 
   138047   if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
   138048 
   138049     if( fts3SegReaderIsPending(pReader) ){
   138050       Fts3HashElem *pElem = *(pReader->ppNextElem);
   138051       if( pElem==0 ){
   138052         pReader->aNode = 0;
   138053       }else{
   138054         PendingList *pList = (PendingList *)fts3HashData(pElem);
   138055         pReader->zTerm = (char *)fts3HashKey(pElem);
   138056         pReader->nTerm = fts3HashKeysize(pElem);
   138057         pReader->nNode = pReader->nDoclist = pList->nData + 1;
   138058         pReader->aNode = pReader->aDoclist = pList->aData;
   138059         pReader->ppNextElem++;
   138060         assert( pReader->aNode );
   138061       }
   138062       return SQLITE_OK;
   138063     }
   138064 
   138065     fts3SegReaderSetEof(pReader);
   138066 
   138067     /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
   138068     ** blocks have already been traversed.  */
   138069     assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
   138070     if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
   138071       return SQLITE_OK;
   138072     }
   138073 
   138074     rc = sqlite3Fts3ReadBlock(
   138075         p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
   138076         (bIncr ? &pReader->nPopulate : 0)
   138077     );
   138078     if( rc!=SQLITE_OK ) return rc;
   138079     assert( pReader->pBlob==0 );
   138080     if( bIncr && pReader->nPopulate<pReader->nNode ){
   138081       pReader->pBlob = p->pSegments;
   138082       p->pSegments = 0;
   138083     }
   138084     pNext = pReader->aNode;
   138085   }
   138086 
   138087   assert( !fts3SegReaderIsPending(pReader) );
   138088 
   138089   rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
   138090   if( rc!=SQLITE_OK ) return rc;
   138091 
   138092   /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
   138093   ** safe (no risk of overread) even if the node data is corrupted. */
   138094   pNext += fts3GetVarint32(pNext, &nPrefix);
   138095   pNext += fts3GetVarint32(pNext, &nSuffix);
   138096   if( nPrefix<0 || nSuffix<=0
   138097    || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
   138098   ){
   138099     return FTS_CORRUPT_VTAB;
   138100   }
   138101 
   138102   if( nPrefix+nSuffix>pReader->nTermAlloc ){
   138103     int nNew = (nPrefix+nSuffix)*2;
   138104     char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
   138105     if( !zNew ){
   138106       return SQLITE_NOMEM;
   138107     }
   138108     pReader->zTerm = zNew;
   138109     pReader->nTermAlloc = nNew;
   138110   }
   138111 
   138112   rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
   138113   if( rc!=SQLITE_OK ) return rc;
   138114 
   138115   memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
   138116   pReader->nTerm = nPrefix+nSuffix;
   138117   pNext += nSuffix;
   138118   pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
   138119   pReader->aDoclist = pNext;
   138120   pReader->pOffsetList = 0;
   138121 
   138122   /* Check that the doclist does not appear to extend past the end of the
   138123   ** b-tree node. And that the final byte of the doclist is 0x00. If either
   138124   ** of these statements is untrue, then the data structure is corrupt.
   138125   */
   138126   if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
   138127    || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
   138128   ){
   138129     return FTS_CORRUPT_VTAB;
   138130   }
   138131   return SQLITE_OK;
   138132 }
   138133 
   138134 /*
   138135 ** Set the SegReader to point to the first docid in the doclist associated
   138136 ** with the current term.
   138137 */
   138138 static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
   138139   int rc = SQLITE_OK;
   138140   assert( pReader->aDoclist );
   138141   assert( !pReader->pOffsetList );
   138142   if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
   138143     u8 bEof = 0;
   138144     pReader->iDocid = 0;
   138145     pReader->nOffsetList = 0;
   138146     sqlite3Fts3DoclistPrev(0,
   138147         pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
   138148         &pReader->iDocid, &pReader->nOffsetList, &bEof
   138149     );
   138150   }else{
   138151     rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
   138152     if( rc==SQLITE_OK ){
   138153       int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
   138154       pReader->pOffsetList = &pReader->aDoclist[n];
   138155     }
   138156   }
   138157   return rc;
   138158 }
   138159 
   138160 /*
   138161 ** Advance the SegReader to point to the next docid in the doclist
   138162 ** associated with the current term.
   138163 **
   138164 ** If arguments ppOffsetList and pnOffsetList are not NULL, then
   138165 ** *ppOffsetList is set to point to the first column-offset list
   138166 ** in the doclist entry (i.e. immediately past the docid varint).
   138167 ** *pnOffsetList is set to the length of the set of column-offset
   138168 ** lists, not including the nul-terminator byte. For example:
   138169 */
   138170 static int fts3SegReaderNextDocid(
   138171   Fts3Table *pTab,
   138172   Fts3SegReader *pReader,         /* Reader to advance to next docid */
   138173   char **ppOffsetList,            /* OUT: Pointer to current position-list */
   138174   int *pnOffsetList               /* OUT: Length of *ppOffsetList in bytes */
   138175 ){
   138176   int rc = SQLITE_OK;
   138177   char *p = pReader->pOffsetList;
   138178   char c = 0;
   138179 
   138180   assert( p );
   138181 
   138182   if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
   138183     /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
   138184     ** Pending-terms doclists are always built up in ascending order, so
   138185     ** we have to iterate through them backwards here. */
   138186     u8 bEof = 0;
   138187     if( ppOffsetList ){
   138188       *ppOffsetList = pReader->pOffsetList;
   138189       *pnOffsetList = pReader->nOffsetList - 1;
   138190     }
   138191     sqlite3Fts3DoclistPrev(0,
   138192         pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
   138193         &pReader->nOffsetList, &bEof
   138194     );
   138195     if( bEof ){
   138196       pReader->pOffsetList = 0;
   138197     }else{
   138198       pReader->pOffsetList = p;
   138199     }
   138200   }else{
   138201     char *pEnd = &pReader->aDoclist[pReader->nDoclist];
   138202 
   138203     /* Pointer p currently points at the first byte of an offset list. The
   138204     ** following block advances it to point one byte past the end of
   138205     ** the same offset list. */
   138206     while( 1 ){
   138207 
   138208       /* The following line of code (and the "p++" below the while() loop) is
   138209       ** normally all that is required to move pointer p to the desired
   138210       ** position. The exception is if this node is being loaded from disk
   138211       ** incrementally and pointer "p" now points to the first byte past
   138212       ** the populated part of pReader->aNode[].
   138213       */
   138214       while( *p | c ) c = *p++ & 0x80;
   138215       assert( *p==0 );
   138216 
   138217       if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
   138218       rc = fts3SegReaderIncrRead(pReader);
   138219       if( rc!=SQLITE_OK ) return rc;
   138220     }
   138221     p++;
   138222 
   138223     /* If required, populate the output variables with a pointer to and the
   138224     ** size of the previous offset-list.
   138225     */
   138226     if( ppOffsetList ){
   138227       *ppOffsetList = pReader->pOffsetList;
   138228       *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
   138229     }
   138230 
   138231     /* List may have been edited in place by fts3EvalNearTrim() */
   138232     while( p<pEnd && *p==0 ) p++;
   138233 
   138234     /* If there are no more entries in the doclist, set pOffsetList to
   138235     ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
   138236     ** Fts3SegReader.pOffsetList to point to the next offset list before
   138237     ** returning.
   138238     */
   138239     if( p>=pEnd ){
   138240       pReader->pOffsetList = 0;
   138241     }else{
   138242       rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
   138243       if( rc==SQLITE_OK ){
   138244         sqlite3_int64 iDelta;
   138245         pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
   138246         if( pTab->bDescIdx ){
   138247           pReader->iDocid -= iDelta;
   138248         }else{
   138249           pReader->iDocid += iDelta;
   138250         }
   138251       }
   138252     }
   138253   }
   138254 
   138255   return SQLITE_OK;
   138256 }
   138257 
   138258 
   138259 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
   138260   Fts3Cursor *pCsr,
   138261   Fts3MultiSegReader *pMsr,
   138262   int *pnOvfl
   138263 ){
   138264   Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
   138265   int nOvfl = 0;
   138266   int ii;
   138267   int rc = SQLITE_OK;
   138268   int pgsz = p->nPgsz;
   138269 
   138270   assert( p->bFts4 );
   138271   assert( pgsz>0 );
   138272 
   138273   for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
   138274     Fts3SegReader *pReader = pMsr->apSegment[ii];
   138275     if( !fts3SegReaderIsPending(pReader)
   138276      && !fts3SegReaderIsRootOnly(pReader)
   138277     ){
   138278       sqlite3_int64 jj;
   138279       for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
   138280         int nBlob;
   138281         rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
   138282         if( rc!=SQLITE_OK ) break;
   138283         if( (nBlob+35)>pgsz ){
   138284           nOvfl += (nBlob + 34)/pgsz;
   138285         }
   138286       }
   138287     }
   138288   }
   138289   *pnOvfl = nOvfl;
   138290   return rc;
   138291 }
   138292 
   138293 /*
   138294 ** Free all allocations associated with the iterator passed as the
   138295 ** second argument.
   138296 */
   138297 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
   138298   if( pReader && !fts3SegReaderIsPending(pReader) ){
   138299     sqlite3_free(pReader->zTerm);
   138300     if( !fts3SegReaderIsRootOnly(pReader) ){
   138301       sqlite3_free(pReader->aNode);
   138302       sqlite3_blob_close(pReader->pBlob);
   138303     }
   138304   }
   138305   sqlite3_free(pReader);
   138306 }
   138307 
   138308 /*
   138309 ** Allocate a new SegReader object.
   138310 */
   138311 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
   138312   int iAge,                       /* Segment "age". */
   138313   int bLookup,                    /* True for a lookup only */
   138314   sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
   138315   sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
   138316   sqlite3_int64 iEndBlock,        /* Final block of segment */
   138317   const char *zRoot,              /* Buffer containing root node */
   138318   int nRoot,                      /* Size of buffer containing root node */
   138319   Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
   138320 ){
   138321   Fts3SegReader *pReader;         /* Newly allocated SegReader object */
   138322   int nExtra = 0;                 /* Bytes to allocate segment root node */
   138323 
   138324   assert( iStartLeaf<=iEndLeaf );
   138325   if( iStartLeaf==0 ){
   138326     nExtra = nRoot + FTS3_NODE_PADDING;
   138327   }
   138328 
   138329   pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
   138330   if( !pReader ){
   138331     return SQLITE_NOMEM;
   138332   }
   138333   memset(pReader, 0, sizeof(Fts3SegReader));
   138334   pReader->iIdx = iAge;
   138335   pReader->bLookup = bLookup!=0;
   138336   pReader->iStartBlock = iStartLeaf;
   138337   pReader->iLeafEndBlock = iEndLeaf;
   138338   pReader->iEndBlock = iEndBlock;
   138339 
   138340   if( nExtra ){
   138341     /* The entire segment is stored in the root node. */
   138342     pReader->aNode = (char *)&pReader[1];
   138343     pReader->rootOnly = 1;
   138344     pReader->nNode = nRoot;
   138345     memcpy(pReader->aNode, zRoot, nRoot);
   138346     memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
   138347   }else{
   138348     pReader->iCurrentBlock = iStartLeaf-1;
   138349   }
   138350   *ppReader = pReader;
   138351   return SQLITE_OK;
   138352 }
   138353 
   138354 /*
   138355 ** This is a comparison function used as a qsort() callback when sorting
   138356 ** an array of pending terms by term. This occurs as part of flushing
   138357 ** the contents of the pending-terms hash table to the database.
   138358 */
   138359 static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
   138360   char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
   138361   char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
   138362   int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
   138363   int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
   138364 
   138365   int n = (n1<n2 ? n1 : n2);
   138366   int c = memcmp(z1, z2, n);
   138367   if( c==0 ){
   138368     c = n1 - n2;
   138369   }
   138370   return c;
   138371 }
   138372 
   138373 /*
   138374 ** This function is used to allocate an Fts3SegReader that iterates through
   138375 ** a subset of the terms stored in the Fts3Table.pendingTerms array.
   138376 **
   138377 ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
   138378 ** through each term in the pending-terms table. Or, if isPrefixIter is
   138379 ** non-zero, it iterates through each term and its prefixes. For example, if
   138380 ** the pending terms hash table contains the terms "sqlite", "mysql" and
   138381 ** "firebird", then the iterator visits the following 'terms' (in the order
   138382 ** shown):
   138383 **
   138384 **   f fi fir fire fireb firebi firebir firebird
   138385 **   m my mys mysq mysql
   138386 **   s sq sql sqli sqlit sqlite
   138387 **
   138388 ** Whereas if isPrefixIter is zero, the terms visited are:
   138389 **
   138390 **   firebird mysql sqlite
   138391 */
   138392 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
   138393   Fts3Table *p,                   /* Virtual table handle */
   138394   int iIndex,                     /* Index for p->aIndex */
   138395   const char *zTerm,              /* Term to search for */
   138396   int nTerm,                      /* Size of buffer zTerm */
   138397   int bPrefix,                    /* True for a prefix iterator */
   138398   Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
   138399 ){
   138400   Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
   138401   Fts3HashElem *pE;               /* Iterator variable */
   138402   Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
   138403   int nElem = 0;                  /* Size of array at aElem */
   138404   int rc = SQLITE_OK;             /* Return Code */
   138405   Fts3Hash *pHash;
   138406 
   138407   pHash = &p->aIndex[iIndex].hPending;
   138408   if( bPrefix ){
   138409     int nAlloc = 0;               /* Size of allocated array at aElem */
   138410 
   138411     for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
   138412       char *zKey = (char *)fts3HashKey(pE);
   138413       int nKey = fts3HashKeysize(pE);
   138414       if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
   138415         if( nElem==nAlloc ){
   138416           Fts3HashElem **aElem2;
   138417           nAlloc += 16;
   138418           aElem2 = (Fts3HashElem **)sqlite3_realloc(
   138419               aElem, nAlloc*sizeof(Fts3HashElem *)
   138420           );
   138421           if( !aElem2 ){
   138422             rc = SQLITE_NOMEM;
   138423             nElem = 0;
   138424             break;
   138425           }
   138426           aElem = aElem2;
   138427         }
   138428 
   138429         aElem[nElem++] = pE;
   138430       }
   138431     }
   138432 
   138433     /* If more than one term matches the prefix, sort the Fts3HashElem
   138434     ** objects in term order using qsort(). This uses the same comparison
   138435     ** callback as is used when flushing terms to disk.
   138436     */
   138437     if( nElem>1 ){
   138438       qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
   138439     }
   138440 
   138441   }else{
   138442     /* The query is a simple term lookup that matches at most one term in
   138443     ** the index. All that is required is a straight hash-lookup.
   138444     **
   138445     ** Because the stack address of pE may be accessed via the aElem pointer
   138446     ** below, the "Fts3HashElem *pE" must be declared so that it is valid
   138447     ** within this entire function, not just this "else{...}" block.
   138448     */
   138449     pE = fts3HashFindElem(pHash, zTerm, nTerm);
   138450     if( pE ){
   138451       aElem = &pE;
   138452       nElem = 1;
   138453     }
   138454   }
   138455 
   138456   if( nElem>0 ){
   138457     int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
   138458     pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
   138459     if( !pReader ){
   138460       rc = SQLITE_NOMEM;
   138461     }else{
   138462       memset(pReader, 0, nByte);
   138463       pReader->iIdx = 0x7FFFFFFF;
   138464       pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
   138465       memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
   138466     }
   138467   }
   138468 
   138469   if( bPrefix ){
   138470     sqlite3_free(aElem);
   138471   }
   138472   *ppReader = pReader;
   138473   return rc;
   138474 }
   138475 
   138476 /*
   138477 ** Compare the entries pointed to by two Fts3SegReader structures.
   138478 ** Comparison is as follows:
   138479 **
   138480 **   1) EOF is greater than not EOF.
   138481 **
   138482 **   2) The current terms (if any) are compared using memcmp(). If one
   138483 **      term is a prefix of another, the longer term is considered the
   138484 **      larger.
   138485 **
   138486 **   3) By segment age. An older segment is considered larger.
   138487 */
   138488 static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
   138489   int rc;
   138490   if( pLhs->aNode && pRhs->aNode ){
   138491     int rc2 = pLhs->nTerm - pRhs->nTerm;
   138492     if( rc2<0 ){
   138493       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
   138494     }else{
   138495       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
   138496     }
   138497     if( rc==0 ){
   138498       rc = rc2;
   138499     }
   138500   }else{
   138501     rc = (pLhs->aNode==0) - (pRhs->aNode==0);
   138502   }
   138503   if( rc==0 ){
   138504     rc = pRhs->iIdx - pLhs->iIdx;
   138505   }
   138506   assert( rc!=0 );
   138507   return rc;
   138508 }
   138509 
   138510 /*
   138511 ** A different comparison function for SegReader structures. In this
   138512 ** version, it is assumed that each SegReader points to an entry in
   138513 ** a doclist for identical terms. Comparison is made as follows:
   138514 **
   138515 **   1) EOF (end of doclist in this case) is greater than not EOF.
   138516 **
   138517 **   2) By current docid.
   138518 **
   138519 **   3) By segment age. An older segment is considered larger.
   138520 */
   138521 static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
   138522   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
   138523   if( rc==0 ){
   138524     if( pLhs->iDocid==pRhs->iDocid ){
   138525       rc = pRhs->iIdx - pLhs->iIdx;
   138526     }else{
   138527       rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
   138528     }
   138529   }
   138530   assert( pLhs->aNode && pRhs->aNode );
   138531   return rc;
   138532 }
   138533 static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
   138534   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
   138535   if( rc==0 ){
   138536     if( pLhs->iDocid==pRhs->iDocid ){
   138537       rc = pRhs->iIdx - pLhs->iIdx;
   138538     }else{
   138539       rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
   138540     }
   138541   }
   138542   assert( pLhs->aNode && pRhs->aNode );
   138543   return rc;
   138544 }
   138545 
   138546 /*
   138547 ** Compare the term that the Fts3SegReader object passed as the first argument
   138548 ** points to with the term specified by arguments zTerm and nTerm.
   138549 **
   138550 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
   138551 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
   138552 ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
   138553 */
   138554 static int fts3SegReaderTermCmp(
   138555   Fts3SegReader *pSeg,            /* Segment reader object */
   138556   const char *zTerm,              /* Term to compare to */
   138557   int nTerm                       /* Size of term zTerm in bytes */
   138558 ){
   138559   int res = 0;
   138560   if( pSeg->aNode ){
   138561     if( pSeg->nTerm>nTerm ){
   138562       res = memcmp(pSeg->zTerm, zTerm, nTerm);
   138563     }else{
   138564       res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
   138565     }
   138566     if( res==0 ){
   138567       res = pSeg->nTerm-nTerm;
   138568     }
   138569   }
   138570   return res;
   138571 }
   138572 
   138573 /*
   138574 ** Argument apSegment is an array of nSegment elements. It is known that
   138575 ** the final (nSegment-nSuspect) members are already in sorted order
   138576 ** (according to the comparison function provided). This function shuffles
   138577 ** the array around until all entries are in sorted order.
   138578 */
   138579 static void fts3SegReaderSort(
   138580   Fts3SegReader **apSegment,                     /* Array to sort entries of */
   138581   int nSegment,                                  /* Size of apSegment array */
   138582   int nSuspect,                                  /* Unsorted entry count */
   138583   int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
   138584 ){
   138585   int i;                          /* Iterator variable */
   138586 
   138587   assert( nSuspect<=nSegment );
   138588 
   138589   if( nSuspect==nSegment ) nSuspect--;
   138590   for(i=nSuspect-1; i>=0; i--){
   138591     int j;
   138592     for(j=i; j<(nSegment-1); j++){
   138593       Fts3SegReader *pTmp;
   138594       if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
   138595       pTmp = apSegment[j+1];
   138596       apSegment[j+1] = apSegment[j];
   138597       apSegment[j] = pTmp;
   138598     }
   138599   }
   138600 
   138601 #ifndef NDEBUG
   138602   /* Check that the list really is sorted now. */
   138603   for(i=0; i<(nSuspect-1); i++){
   138604     assert( xCmp(apSegment[i], apSegment[i+1])<0 );
   138605   }
   138606 #endif
   138607 }
   138608 
   138609 /*
   138610 ** Insert a record into the %_segments table.
   138611 */
   138612 static int fts3WriteSegment(
   138613   Fts3Table *p,                   /* Virtual table handle */
   138614   sqlite3_int64 iBlock,           /* Block id for new block */
   138615   char *z,                        /* Pointer to buffer containing block data */
   138616   int n                           /* Size of buffer z in bytes */
   138617 ){
   138618   sqlite3_stmt *pStmt;
   138619   int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
   138620   if( rc==SQLITE_OK ){
   138621     sqlite3_bind_int64(pStmt, 1, iBlock);
   138622     sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
   138623     sqlite3_step(pStmt);
   138624     rc = sqlite3_reset(pStmt);
   138625   }
   138626   return rc;
   138627 }
   138628 
   138629 /*
   138630 ** Find the largest relative level number in the table. If successful, set
   138631 ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
   138632 ** set *pnMax to zero and return an SQLite error code.
   138633 */
   138634 SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
   138635   int rc;
   138636   int mxLevel = 0;
   138637   sqlite3_stmt *pStmt = 0;
   138638 
   138639   rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
   138640   if( rc==SQLITE_OK ){
   138641     if( SQLITE_ROW==sqlite3_step(pStmt) ){
   138642       mxLevel = sqlite3_column_int(pStmt, 0);
   138643     }
   138644     rc = sqlite3_reset(pStmt);
   138645   }
   138646   *pnMax = mxLevel;
   138647   return rc;
   138648 }
   138649 
   138650 /*
   138651 ** Insert a record into the %_segdir table.
   138652 */
   138653 static int fts3WriteSegdir(
   138654   Fts3Table *p,                   /* Virtual table handle */
   138655   sqlite3_int64 iLevel,           /* Value for "level" field (absolute level) */
   138656   int iIdx,                       /* Value for "idx" field */
   138657   sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
   138658   sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
   138659   sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
   138660   sqlite3_int64 nLeafData,        /* Bytes of leaf data in segment */
   138661   char *zRoot,                    /* Blob value for "root" field */
   138662   int nRoot                       /* Number of bytes in buffer zRoot */
   138663 ){
   138664   sqlite3_stmt *pStmt;
   138665   int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
   138666   if( rc==SQLITE_OK ){
   138667     sqlite3_bind_int64(pStmt, 1, iLevel);
   138668     sqlite3_bind_int(pStmt, 2, iIdx);
   138669     sqlite3_bind_int64(pStmt, 3, iStartBlock);
   138670     sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
   138671     if( nLeafData==0 ){
   138672       sqlite3_bind_int64(pStmt, 5, iEndBlock);
   138673     }else{
   138674       char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData);
   138675       if( !zEnd ) return SQLITE_NOMEM;
   138676       sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free);
   138677     }
   138678     sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
   138679     sqlite3_step(pStmt);
   138680     rc = sqlite3_reset(pStmt);
   138681   }
   138682   return rc;
   138683 }
   138684 
   138685 /*
   138686 ** Return the size of the common prefix (if any) shared by zPrev and
   138687 ** zNext, in bytes. For example,
   138688 **
   138689 **   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
   138690 **   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
   138691 **   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
   138692 */
   138693 static int fts3PrefixCompress(
   138694   const char *zPrev,              /* Buffer containing previous term */
   138695   int nPrev,                      /* Size of buffer zPrev in bytes */
   138696   const char *zNext,              /* Buffer containing next term */
   138697   int nNext                       /* Size of buffer zNext in bytes */
   138698 ){
   138699   int n;
   138700   UNUSED_PARAMETER(nNext);
   138701   for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
   138702   return n;
   138703 }
   138704 
   138705 /*
   138706 ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
   138707 ** (according to memcmp) than the previous term.
   138708 */
   138709 static int fts3NodeAddTerm(
   138710   Fts3Table *p,                   /* Virtual table handle */
   138711   SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */
   138712   int isCopyTerm,                 /* True if zTerm/nTerm is transient */
   138713   const char *zTerm,              /* Pointer to buffer containing term */
   138714   int nTerm                       /* Size of term in bytes */
   138715 ){
   138716   SegmentNode *pTree = *ppTree;
   138717   int rc;
   138718   SegmentNode *pNew;
   138719 
   138720   /* First try to append the term to the current node. Return early if
   138721   ** this is possible.
   138722   */
   138723   if( pTree ){
   138724     int nData = pTree->nData;     /* Current size of node in bytes */
   138725     int nReq = nData;             /* Required space after adding zTerm */
   138726     int nPrefix;                  /* Number of bytes of prefix compression */
   138727     int nSuffix;                  /* Suffix length */
   138728 
   138729     nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
   138730     nSuffix = nTerm-nPrefix;
   138731 
   138732     nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
   138733     if( nReq<=p->nNodeSize || !pTree->zTerm ){
   138734 
   138735       if( nReq>p->nNodeSize ){
   138736         /* An unusual case: this is the first term to be added to the node
   138737         ** and the static node buffer (p->nNodeSize bytes) is not large
   138738         ** enough. Use a separately malloced buffer instead This wastes
   138739         ** p->nNodeSize bytes, but since this scenario only comes about when
   138740         ** the database contain two terms that share a prefix of almost 2KB,
   138741         ** this is not expected to be a serious problem.
   138742         */
   138743         assert( pTree->aData==(char *)&pTree[1] );
   138744         pTree->aData = (char *)sqlite3_malloc(nReq);
   138745         if( !pTree->aData ){
   138746           return SQLITE_NOMEM;
   138747         }
   138748       }
   138749 
   138750       if( pTree->zTerm ){
   138751         /* There is no prefix-length field for first term in a node */
   138752         nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
   138753       }
   138754 
   138755       nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
   138756       memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
   138757       pTree->nData = nData + nSuffix;
   138758       pTree->nEntry++;
   138759 
   138760       if( isCopyTerm ){
   138761         if( pTree->nMalloc<nTerm ){
   138762           char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
   138763           if( !zNew ){
   138764             return SQLITE_NOMEM;
   138765           }
   138766           pTree->nMalloc = nTerm*2;
   138767           pTree->zMalloc = zNew;
   138768         }
   138769         pTree->zTerm = pTree->zMalloc;
   138770         memcpy(pTree->zTerm, zTerm, nTerm);
   138771         pTree->nTerm = nTerm;
   138772       }else{
   138773         pTree->zTerm = (char *)zTerm;
   138774         pTree->nTerm = nTerm;
   138775       }
   138776       return SQLITE_OK;
   138777     }
   138778   }
   138779 
   138780   /* If control flows to here, it was not possible to append zTerm to the
   138781   ** current node. Create a new node (a right-sibling of the current node).
   138782   ** If this is the first node in the tree, the term is added to it.
   138783   **
   138784   ** Otherwise, the term is not added to the new node, it is left empty for
   138785   ** now. Instead, the term is inserted into the parent of pTree. If pTree
   138786   ** has no parent, one is created here.
   138787   */
   138788   pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
   138789   if( !pNew ){
   138790     return SQLITE_NOMEM;
   138791   }
   138792   memset(pNew, 0, sizeof(SegmentNode));
   138793   pNew->nData = 1 + FTS3_VARINT_MAX;
   138794   pNew->aData = (char *)&pNew[1];
   138795 
   138796   if( pTree ){
   138797     SegmentNode *pParent = pTree->pParent;
   138798     rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
   138799     if( pTree->pParent==0 ){
   138800       pTree->pParent = pParent;
   138801     }
   138802     pTree->pRight = pNew;
   138803     pNew->pLeftmost = pTree->pLeftmost;
   138804     pNew->pParent = pParent;
   138805     pNew->zMalloc = pTree->zMalloc;
   138806     pNew->nMalloc = pTree->nMalloc;
   138807     pTree->zMalloc = 0;
   138808   }else{
   138809     pNew->pLeftmost = pNew;
   138810     rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
   138811   }
   138812 
   138813   *ppTree = pNew;
   138814   return rc;
   138815 }
   138816 
   138817 /*
   138818 ** Helper function for fts3NodeWrite().
   138819 */
   138820 static int fts3TreeFinishNode(
   138821   SegmentNode *pTree,
   138822   int iHeight,
   138823   sqlite3_int64 iLeftChild
   138824 ){
   138825   int nStart;
   138826   assert( iHeight>=1 && iHeight<128 );
   138827   nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
   138828   pTree->aData[nStart] = (char)iHeight;
   138829   sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
   138830   return nStart;
   138831 }
   138832 
   138833 /*
   138834 ** Write the buffer for the segment node pTree and all of its peers to the
   138835 ** database. Then call this function recursively to write the parent of
   138836 ** pTree and its peers to the database.
   138837 **
   138838 ** Except, if pTree is a root node, do not write it to the database. Instead,
   138839 ** set output variables *paRoot and *pnRoot to contain the root node.
   138840 **
   138841 ** If successful, SQLITE_OK is returned and output variable *piLast is
   138842 ** set to the largest blockid written to the database (or zero if no
   138843 ** blocks were written to the db). Otherwise, an SQLite error code is
   138844 ** returned.
   138845 */
   138846 static int fts3NodeWrite(
   138847   Fts3Table *p,                   /* Virtual table handle */
   138848   SegmentNode *pTree,             /* SegmentNode handle */
   138849   int iHeight,                    /* Height of this node in tree */
   138850   sqlite3_int64 iLeaf,            /* Block id of first leaf node */
   138851   sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
   138852   sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
   138853   char **paRoot,                  /* OUT: Data for root node */
   138854   int *pnRoot                     /* OUT: Size of root node in bytes */
   138855 ){
   138856   int rc = SQLITE_OK;
   138857 
   138858   if( !pTree->pParent ){
   138859     /* Root node of the tree. */
   138860     int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
   138861     *piLast = iFree-1;
   138862     *pnRoot = pTree->nData - nStart;
   138863     *paRoot = &pTree->aData[nStart];
   138864   }else{
   138865     SegmentNode *pIter;
   138866     sqlite3_int64 iNextFree = iFree;
   138867     sqlite3_int64 iNextLeaf = iLeaf;
   138868     for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
   138869       int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
   138870       int nWrite = pIter->nData - nStart;
   138871 
   138872       rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
   138873       iNextFree++;
   138874       iNextLeaf += (pIter->nEntry+1);
   138875     }
   138876     if( rc==SQLITE_OK ){
   138877       assert( iNextLeaf==iFree );
   138878       rc = fts3NodeWrite(
   138879           p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
   138880       );
   138881     }
   138882   }
   138883 
   138884   return rc;
   138885 }
   138886 
   138887 /*
   138888 ** Free all memory allocations associated with the tree pTree.
   138889 */
   138890 static void fts3NodeFree(SegmentNode *pTree){
   138891   if( pTree ){
   138892     SegmentNode *p = pTree->pLeftmost;
   138893     fts3NodeFree(p->pParent);
   138894     while( p ){
   138895       SegmentNode *pRight = p->pRight;
   138896       if( p->aData!=(char *)&p[1] ){
   138897         sqlite3_free(p->aData);
   138898       }
   138899       assert( pRight==0 || p->zMalloc==0 );
   138900       sqlite3_free(p->zMalloc);
   138901       sqlite3_free(p);
   138902       p = pRight;
   138903     }
   138904   }
   138905 }
   138906 
   138907 /*
   138908 ** Add a term to the segment being constructed by the SegmentWriter object
   138909 ** *ppWriter. When adding the first term to a segment, *ppWriter should
   138910 ** be passed NULL. This function will allocate a new SegmentWriter object
   138911 ** and return it via the input/output variable *ppWriter in this case.
   138912 **
   138913 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
   138914 */
   138915 static int fts3SegWriterAdd(
   138916   Fts3Table *p,                   /* Virtual table handle */
   138917   SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */
   138918   int isCopyTerm,                 /* True if buffer zTerm must be copied */
   138919   const char *zTerm,              /* Pointer to buffer containing term */
   138920   int nTerm,                      /* Size of term in bytes */
   138921   const char *aDoclist,           /* Pointer to buffer containing doclist */
   138922   int nDoclist                    /* Size of doclist in bytes */
   138923 ){
   138924   int nPrefix;                    /* Size of term prefix in bytes */
   138925   int nSuffix;                    /* Size of term suffix in bytes */
   138926   int nReq;                       /* Number of bytes required on leaf page */
   138927   int nData;
   138928   SegmentWriter *pWriter = *ppWriter;
   138929 
   138930   if( !pWriter ){
   138931     int rc;
   138932     sqlite3_stmt *pStmt;
   138933 
   138934     /* Allocate the SegmentWriter structure */
   138935     pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
   138936     if( !pWriter ) return SQLITE_NOMEM;
   138937     memset(pWriter, 0, sizeof(SegmentWriter));
   138938     *ppWriter = pWriter;
   138939 
   138940     /* Allocate a buffer in which to accumulate data */
   138941     pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
   138942     if( !pWriter->aData ) return SQLITE_NOMEM;
   138943     pWriter->nSize = p->nNodeSize;
   138944 
   138945     /* Find the next free blockid in the %_segments table */
   138946     rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
   138947     if( rc!=SQLITE_OK ) return rc;
   138948     if( SQLITE_ROW==sqlite3_step(pStmt) ){
   138949       pWriter->iFree = sqlite3_column_int64(pStmt, 0);
   138950       pWriter->iFirst = pWriter->iFree;
   138951     }
   138952     rc = sqlite3_reset(pStmt);
   138953     if( rc!=SQLITE_OK ) return rc;
   138954   }
   138955   nData = pWriter->nData;
   138956 
   138957   nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
   138958   nSuffix = nTerm-nPrefix;
   138959 
   138960   /* Figure out how many bytes are required by this new entry */
   138961   nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
   138962     sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
   138963     nSuffix +                               /* Term suffix */
   138964     sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
   138965     nDoclist;                               /* Doclist data */
   138966 
   138967   if( nData>0 && nData+nReq>p->nNodeSize ){
   138968     int rc;
   138969 
   138970     /* The current leaf node is full. Write it out to the database. */
   138971     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
   138972     if( rc!=SQLITE_OK ) return rc;
   138973     p->nLeafAdd++;
   138974 
   138975     /* Add the current term to the interior node tree. The term added to
   138976     ** the interior tree must:
   138977     **
   138978     **   a) be greater than the largest term on the leaf node just written
   138979     **      to the database (still available in pWriter->zTerm), and
   138980     **
   138981     **   b) be less than or equal to the term about to be added to the new
   138982     **      leaf node (zTerm/nTerm).
   138983     **
   138984     ** In other words, it must be the prefix of zTerm 1 byte longer than
   138985     ** the common prefix (if any) of zTerm and pWriter->zTerm.
   138986     */
   138987     assert( nPrefix<nTerm );
   138988     rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
   138989     if( rc!=SQLITE_OK ) return rc;
   138990 
   138991     nData = 0;
   138992     pWriter->nTerm = 0;
   138993 
   138994     nPrefix = 0;
   138995     nSuffix = nTerm;
   138996     nReq = 1 +                              /* varint containing prefix size */
   138997       sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
   138998       nTerm +                               /* Term suffix */
   138999       sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
   139000       nDoclist;                             /* Doclist data */
   139001   }
   139002 
   139003   /* Increase the total number of bytes written to account for the new entry. */
   139004   pWriter->nLeafData += nReq;
   139005 
   139006   /* If the buffer currently allocated is too small for this entry, realloc
   139007   ** the buffer to make it large enough.
   139008   */
   139009   if( nReq>pWriter->nSize ){
   139010     char *aNew = sqlite3_realloc(pWriter->aData, nReq);
   139011     if( !aNew ) return SQLITE_NOMEM;
   139012     pWriter->aData = aNew;
   139013     pWriter->nSize = nReq;
   139014   }
   139015   assert( nData+nReq<=pWriter->nSize );
   139016 
   139017   /* Append the prefix-compressed term and doclist to the buffer. */
   139018   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
   139019   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
   139020   memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
   139021   nData += nSuffix;
   139022   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
   139023   memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
   139024   pWriter->nData = nData + nDoclist;
   139025 
   139026   /* Save the current term so that it can be used to prefix-compress the next.
   139027   ** If the isCopyTerm parameter is true, then the buffer pointed to by
   139028   ** zTerm is transient, so take a copy of the term data. Otherwise, just
   139029   ** store a copy of the pointer.
   139030   */
   139031   if( isCopyTerm ){
   139032     if( nTerm>pWriter->nMalloc ){
   139033       char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
   139034       if( !zNew ){
   139035         return SQLITE_NOMEM;
   139036       }
   139037       pWriter->nMalloc = nTerm*2;
   139038       pWriter->zMalloc = zNew;
   139039       pWriter->zTerm = zNew;
   139040     }
   139041     assert( pWriter->zTerm==pWriter->zMalloc );
   139042     memcpy(pWriter->zTerm, zTerm, nTerm);
   139043   }else{
   139044     pWriter->zTerm = (char *)zTerm;
   139045   }
   139046   pWriter->nTerm = nTerm;
   139047 
   139048   return SQLITE_OK;
   139049 }
   139050 
   139051 /*
   139052 ** Flush all data associated with the SegmentWriter object pWriter to the
   139053 ** database. This function must be called after all terms have been added
   139054 ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
   139055 ** returned. Otherwise, an SQLite error code.
   139056 */
   139057 static int fts3SegWriterFlush(
   139058   Fts3Table *p,                   /* Virtual table handle */
   139059   SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
   139060   sqlite3_int64 iLevel,           /* Value for 'level' column of %_segdir */
   139061   int iIdx                        /* Value for 'idx' column of %_segdir */
   139062 ){
   139063   int rc;                         /* Return code */
   139064   if( pWriter->pTree ){
   139065     sqlite3_int64 iLast = 0;      /* Largest block id written to database */
   139066     sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
   139067     char *zRoot = NULL;           /* Pointer to buffer containing root node */
   139068     int nRoot = 0;                /* Size of buffer zRoot */
   139069 
   139070     iLastLeaf = pWriter->iFree;
   139071     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
   139072     if( rc==SQLITE_OK ){
   139073       rc = fts3NodeWrite(p, pWriter->pTree, 1,
   139074           pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
   139075     }
   139076     if( rc==SQLITE_OK ){
   139077       rc = fts3WriteSegdir(p, iLevel, iIdx,
   139078           pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
   139079     }
   139080   }else{
   139081     /* The entire tree fits on the root node. Write it to the segdir table. */
   139082     rc = fts3WriteSegdir(p, iLevel, iIdx,
   139083         0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
   139084   }
   139085   p->nLeafAdd++;
   139086   return rc;
   139087 }
   139088 
   139089 /*
   139090 ** Release all memory held by the SegmentWriter object passed as the
   139091 ** first argument.
   139092 */
   139093 static void fts3SegWriterFree(SegmentWriter *pWriter){
   139094   if( pWriter ){
   139095     sqlite3_free(pWriter->aData);
   139096     sqlite3_free(pWriter->zMalloc);
   139097     fts3NodeFree(pWriter->pTree);
   139098     sqlite3_free(pWriter);
   139099   }
   139100 }
   139101 
   139102 /*
   139103 ** The first value in the apVal[] array is assumed to contain an integer.
   139104 ** This function tests if there exist any documents with docid values that
   139105 ** are different from that integer. i.e. if deleting the document with docid
   139106 ** pRowid would mean the FTS3 table were empty.
   139107 **
   139108 ** If successful, *pisEmpty is set to true if the table is empty except for
   139109 ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
   139110 ** error occurs, an SQLite error code is returned.
   139111 */
   139112 static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
   139113   sqlite3_stmt *pStmt;
   139114   int rc;
   139115   if( p->zContentTbl ){
   139116     /* If using the content=xxx option, assume the table is never empty */
   139117     *pisEmpty = 0;
   139118     rc = SQLITE_OK;
   139119   }else{
   139120     rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
   139121     if( rc==SQLITE_OK ){
   139122       if( SQLITE_ROW==sqlite3_step(pStmt) ){
   139123         *pisEmpty = sqlite3_column_int(pStmt, 0);
   139124       }
   139125       rc = sqlite3_reset(pStmt);
   139126     }
   139127   }
   139128   return rc;
   139129 }
   139130 
   139131 /*
   139132 ** Set *pnMax to the largest segment level in the database for the index
   139133 ** iIndex.
   139134 **
   139135 ** Segment levels are stored in the 'level' column of the %_segdir table.
   139136 **
   139137 ** Return SQLITE_OK if successful, or an SQLite error code if not.
   139138 */
   139139 static int fts3SegmentMaxLevel(
   139140   Fts3Table *p,
   139141   int iLangid,
   139142   int iIndex,
   139143   sqlite3_int64 *pnMax
   139144 ){
   139145   sqlite3_stmt *pStmt;
   139146   int rc;
   139147   assert( iIndex>=0 && iIndex<p->nIndex );
   139148 
   139149   /* Set pStmt to the compiled version of:
   139150   **
   139151   **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
   139152   **
   139153   ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
   139154   */
   139155   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
   139156   if( rc!=SQLITE_OK ) return rc;
   139157   sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
   139158   sqlite3_bind_int64(pStmt, 2,
   139159       getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
   139160   );
   139161   if( SQLITE_ROW==sqlite3_step(pStmt) ){
   139162     *pnMax = sqlite3_column_int64(pStmt, 0);
   139163   }
   139164   return sqlite3_reset(pStmt);
   139165 }
   139166 
   139167 /*
   139168 ** iAbsLevel is an absolute level that may be assumed to exist within
   139169 ** the database. This function checks if it is the largest level number
   139170 ** within its index. Assuming no error occurs, *pbMax is set to 1 if
   139171 ** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK
   139172 ** is returned. If an error occurs, an error code is returned and the
   139173 ** final value of *pbMax is undefined.
   139174 */
   139175 static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
   139176 
   139177   /* Set pStmt to the compiled version of:
   139178   **
   139179   **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
   139180   **
   139181   ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
   139182   */
   139183   sqlite3_stmt *pStmt;
   139184   int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
   139185   if( rc!=SQLITE_OK ) return rc;
   139186   sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
   139187   sqlite3_bind_int64(pStmt, 2,
   139188       ((iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
   139189   );
   139190 
   139191   *pbMax = 0;
   139192   if( SQLITE_ROW==sqlite3_step(pStmt) ){
   139193     *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;
   139194   }
   139195   return sqlite3_reset(pStmt);
   139196 }
   139197 
   139198 /*
   139199 ** Delete all entries in the %_segments table associated with the segment
   139200 ** opened with seg-reader pSeg. This function does not affect the contents
   139201 ** of the %_segdir table.
   139202 */
   139203 static int fts3DeleteSegment(
   139204   Fts3Table *p,                   /* FTS table handle */
   139205   Fts3SegReader *pSeg             /* Segment to delete */
   139206 ){
   139207   int rc = SQLITE_OK;             /* Return code */
   139208   if( pSeg->iStartBlock ){
   139209     sqlite3_stmt *pDelete;        /* SQL statement to delete rows */
   139210     rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
   139211     if( rc==SQLITE_OK ){
   139212       sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
   139213       sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
   139214       sqlite3_step(pDelete);
   139215       rc = sqlite3_reset(pDelete);
   139216     }
   139217   }
   139218   return rc;
   139219 }
   139220 
   139221 /*
   139222 ** This function is used after merging multiple segments into a single large
   139223 ** segment to delete the old, now redundant, segment b-trees. Specifically,
   139224 ** it:
   139225 **
   139226 **   1) Deletes all %_segments entries for the segments associated with
   139227 **      each of the SegReader objects in the array passed as the third
   139228 **      argument, and
   139229 **
   139230 **   2) deletes all %_segdir entries with level iLevel, or all %_segdir
   139231 **      entries regardless of level if (iLevel<0).
   139232 **
   139233 ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
   139234 */
   139235 static int fts3DeleteSegdir(
   139236   Fts3Table *p,                   /* Virtual table handle */
   139237   int iLangid,                    /* Language id */
   139238   int iIndex,                     /* Index for p->aIndex */
   139239   int iLevel,                     /* Level of %_segdir entries to delete */
   139240   Fts3SegReader **apSegment,      /* Array of SegReader objects */
   139241   int nReader                     /* Size of array apSegment */
   139242 ){
   139243   int rc = SQLITE_OK;             /* Return Code */
   139244   int i;                          /* Iterator variable */
   139245   sqlite3_stmt *pDelete = 0;      /* SQL statement to delete rows */
   139246 
   139247   for(i=0; rc==SQLITE_OK && i<nReader; i++){
   139248     rc = fts3DeleteSegment(p, apSegment[i]);
   139249   }
   139250   if( rc!=SQLITE_OK ){
   139251     return rc;
   139252   }
   139253 
   139254   assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
   139255   if( iLevel==FTS3_SEGCURSOR_ALL ){
   139256     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
   139257     if( rc==SQLITE_OK ){
   139258       sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
   139259       sqlite3_bind_int64(pDelete, 2,
   139260           getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
   139261       );
   139262     }
   139263   }else{
   139264     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
   139265     if( rc==SQLITE_OK ){
   139266       sqlite3_bind_int64(
   139267           pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
   139268       );
   139269     }
   139270   }
   139271 
   139272   if( rc==SQLITE_OK ){
   139273     sqlite3_step(pDelete);
   139274     rc = sqlite3_reset(pDelete);
   139275   }
   139276 
   139277   return rc;
   139278 }
   139279 
   139280 /*
   139281 ** When this function is called, buffer *ppList (size *pnList bytes) contains
   139282 ** a position list that may (or may not) feature multiple columns. This
   139283 ** function adjusts the pointer *ppList and the length *pnList so that they
   139284 ** identify the subset of the position list that corresponds to column iCol.
   139285 **
   139286 ** If there are no entries in the input position list for column iCol, then
   139287 ** *pnList is set to zero before returning.
   139288 **
   139289 ** If parameter bZero is non-zero, then any part of the input list following
   139290 ** the end of the output list is zeroed before returning.
   139291 */
   139292 static void fts3ColumnFilter(
   139293   int iCol,                       /* Column to filter on */
   139294   int bZero,                      /* Zero out anything following *ppList */
   139295   char **ppList,                  /* IN/OUT: Pointer to position list */
   139296   int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
   139297 ){
   139298   char *pList = *ppList;
   139299   int nList = *pnList;
   139300   char *pEnd = &pList[nList];
   139301   int iCurrent = 0;
   139302   char *p = pList;
   139303 
   139304   assert( iCol>=0 );
   139305   while( 1 ){
   139306     char c = 0;
   139307     while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
   139308 
   139309     if( iCol==iCurrent ){
   139310       nList = (int)(p - pList);
   139311       break;
   139312     }
   139313 
   139314     nList -= (int)(p - pList);
   139315     pList = p;
   139316     if( nList==0 ){
   139317       break;
   139318     }
   139319     p = &pList[1];
   139320     p += fts3GetVarint32(p, &iCurrent);
   139321   }
   139322 
   139323   if( bZero && &pList[nList]!=pEnd ){
   139324     memset(&pList[nList], 0, pEnd - &pList[nList]);
   139325   }
   139326   *ppList = pList;
   139327   *pnList = nList;
   139328 }
   139329 
   139330 /*
   139331 ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
   139332 ** existing data). Grow the buffer if required.
   139333 **
   139334 ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
   139335 ** trying to resize the buffer, return SQLITE_NOMEM.
   139336 */
   139337 static int fts3MsrBufferData(
   139338   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
   139339   char *pList,
   139340   int nList
   139341 ){
   139342   if( nList>pMsr->nBuffer ){
   139343     char *pNew;
   139344     pMsr->nBuffer = nList*2;
   139345     pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
   139346     if( !pNew ) return SQLITE_NOMEM;
   139347     pMsr->aBuffer = pNew;
   139348   }
   139349 
   139350   memcpy(pMsr->aBuffer, pList, nList);
   139351   return SQLITE_OK;
   139352 }
   139353 
   139354 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
   139355   Fts3Table *p,                   /* Virtual table handle */
   139356   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
   139357   sqlite3_int64 *piDocid,         /* OUT: Docid value */
   139358   char **paPoslist,               /* OUT: Pointer to position list */
   139359   int *pnPoslist                  /* OUT: Size of position list in bytes */
   139360 ){
   139361   int nMerge = pMsr->nAdvance;
   139362   Fts3SegReader **apSegment = pMsr->apSegment;
   139363   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
   139364     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
   139365   );
   139366 
   139367   if( nMerge==0 ){
   139368     *paPoslist = 0;
   139369     return SQLITE_OK;
   139370   }
   139371 
   139372   while( 1 ){
   139373     Fts3SegReader *pSeg;
   139374     pSeg = pMsr->apSegment[0];
   139375 
   139376     if( pSeg->pOffsetList==0 ){
   139377       *paPoslist = 0;
   139378       break;
   139379     }else{
   139380       int rc;
   139381       char *pList;
   139382       int nList;
   139383       int j;
   139384       sqlite3_int64 iDocid = apSegment[0]->iDocid;
   139385 
   139386       rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
   139387       j = 1;
   139388       while( rc==SQLITE_OK
   139389         && j<nMerge
   139390         && apSegment[j]->pOffsetList
   139391         && apSegment[j]->iDocid==iDocid
   139392       ){
   139393         rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
   139394         j++;
   139395       }
   139396       if( rc!=SQLITE_OK ) return rc;
   139397       fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
   139398 
   139399       if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
   139400         rc = fts3MsrBufferData(pMsr, pList, nList+1);
   139401         if( rc!=SQLITE_OK ) return rc;
   139402         assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
   139403         pList = pMsr->aBuffer;
   139404       }
   139405 
   139406       if( pMsr->iColFilter>=0 ){
   139407         fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
   139408       }
   139409 
   139410       if( nList>0 ){
   139411         *paPoslist = pList;
   139412         *piDocid = iDocid;
   139413         *pnPoslist = nList;
   139414         break;
   139415       }
   139416     }
   139417   }
   139418 
   139419   return SQLITE_OK;
   139420 }
   139421 
   139422 static int fts3SegReaderStart(
   139423   Fts3Table *p,                   /* Virtual table handle */
   139424   Fts3MultiSegReader *pCsr,       /* Cursor object */
   139425   const char *zTerm,              /* Term searched for (or NULL) */
   139426   int nTerm                       /* Length of zTerm in bytes */
   139427 ){
   139428   int i;
   139429   int nSeg = pCsr->nSegment;
   139430 
   139431   /* If the Fts3SegFilter defines a specific term (or term prefix) to search
   139432   ** for, then advance each segment iterator until it points to a term of
   139433   ** equal or greater value than the specified term. This prevents many
   139434   ** unnecessary merge/sort operations for the case where single segment
   139435   ** b-tree leaf nodes contain more than one term.
   139436   */
   139437   for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
   139438     int res = 0;
   139439     Fts3SegReader *pSeg = pCsr->apSegment[i];
   139440     do {
   139441       int rc = fts3SegReaderNext(p, pSeg, 0);
   139442       if( rc!=SQLITE_OK ) return rc;
   139443     }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
   139444 
   139445     if( pSeg->bLookup && res!=0 ){
   139446       fts3SegReaderSetEof(pSeg);
   139447     }
   139448   }
   139449   fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
   139450 
   139451   return SQLITE_OK;
   139452 }
   139453 
   139454 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
   139455   Fts3Table *p,                   /* Virtual table handle */
   139456   Fts3MultiSegReader *pCsr,       /* Cursor object */
   139457   Fts3SegFilter *pFilter          /* Restrictions on range of iteration */
   139458 ){
   139459   pCsr->pFilter = pFilter;
   139460   return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
   139461 }
   139462 
   139463 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
   139464   Fts3Table *p,                   /* Virtual table handle */
   139465   Fts3MultiSegReader *pCsr,       /* Cursor object */
   139466   int iCol,                       /* Column to match on. */
   139467   const char *zTerm,              /* Term to iterate through a doclist for */
   139468   int nTerm                       /* Number of bytes in zTerm */
   139469 ){
   139470   int i;
   139471   int rc;
   139472   int nSegment = pCsr->nSegment;
   139473   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
   139474     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
   139475   );
   139476 
   139477   assert( pCsr->pFilter==0 );
   139478   assert( zTerm && nTerm>0 );
   139479 
   139480   /* Advance each segment iterator until it points to the term zTerm/nTerm. */
   139481   rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
   139482   if( rc!=SQLITE_OK ) return rc;
   139483 
   139484   /* Determine how many of the segments actually point to zTerm/nTerm. */
   139485   for(i=0; i<nSegment; i++){
   139486     Fts3SegReader *pSeg = pCsr->apSegment[i];
   139487     if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
   139488       break;
   139489     }
   139490   }
   139491   pCsr->nAdvance = i;
   139492 
   139493   /* Advance each of the segments to point to the first docid. */
   139494   for(i=0; i<pCsr->nAdvance; i++){
   139495     rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
   139496     if( rc!=SQLITE_OK ) return rc;
   139497   }
   139498   fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
   139499 
   139500   assert( iCol<0 || iCol<p->nColumn );
   139501   pCsr->iColFilter = iCol;
   139502 
   139503   return SQLITE_OK;
   139504 }
   139505 
   139506 /*
   139507 ** This function is called on a MultiSegReader that has been started using
   139508 ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
   139509 ** have been made. Calling this function puts the MultiSegReader in such
   139510 ** a state that if the next two calls are:
   139511 **
   139512 **   sqlite3Fts3SegReaderStart()
   139513 **   sqlite3Fts3SegReaderStep()
   139514 **
   139515 ** then the entire doclist for the term is available in
   139516 ** MultiSegReader.aDoclist/nDoclist.
   139517 */
   139518 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
   139519   int i;                          /* Used to iterate through segment-readers */
   139520 
   139521   assert( pCsr->zTerm==0 );
   139522   assert( pCsr->nTerm==0 );
   139523   assert( pCsr->aDoclist==0 );
   139524   assert( pCsr->nDoclist==0 );
   139525 
   139526   pCsr->nAdvance = 0;
   139527   pCsr->bRestart = 1;
   139528   for(i=0; i<pCsr->nSegment; i++){
   139529     pCsr->apSegment[i]->pOffsetList = 0;
   139530     pCsr->apSegment[i]->nOffsetList = 0;
   139531     pCsr->apSegment[i]->iDocid = 0;
   139532   }
   139533 
   139534   return SQLITE_OK;
   139535 }
   139536 
   139537 
   139538 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
   139539   Fts3Table *p,                   /* Virtual table handle */
   139540   Fts3MultiSegReader *pCsr        /* Cursor object */
   139541 ){
   139542   int rc = SQLITE_OK;
   139543 
   139544   int isIgnoreEmpty =  (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
   139545   int isRequirePos =   (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
   139546   int isColFilter =    (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
   139547   int isPrefix =       (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
   139548   int isScan =         (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
   139549   int isFirst =        (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
   139550 
   139551   Fts3SegReader **apSegment = pCsr->apSegment;
   139552   int nSegment = pCsr->nSegment;
   139553   Fts3SegFilter *pFilter = pCsr->pFilter;
   139554   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
   139555     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
   139556   );
   139557 
   139558   if( pCsr->nSegment==0 ) return SQLITE_OK;
   139559 
   139560   do {
   139561     int nMerge;
   139562     int i;
   139563 
   139564     /* Advance the first pCsr->nAdvance entries in the apSegment[] array
   139565     ** forward. Then sort the list in order of current term again.
   139566     */
   139567     for(i=0; i<pCsr->nAdvance; i++){
   139568       Fts3SegReader *pSeg = apSegment[i];
   139569       if( pSeg->bLookup ){
   139570         fts3SegReaderSetEof(pSeg);
   139571       }else{
   139572         rc = fts3SegReaderNext(p, pSeg, 0);
   139573       }
   139574       if( rc!=SQLITE_OK ) return rc;
   139575     }
   139576     fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
   139577     pCsr->nAdvance = 0;
   139578 
   139579     /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
   139580     assert( rc==SQLITE_OK );
   139581     if( apSegment[0]->aNode==0 ) break;
   139582 
   139583     pCsr->nTerm = apSegment[0]->nTerm;
   139584     pCsr->zTerm = apSegment[0]->zTerm;
   139585 
   139586     /* If this is a prefix-search, and if the term that apSegment[0] points
   139587     ** to does not share a suffix with pFilter->zTerm/nTerm, then all
   139588     ** required callbacks have been made. In this case exit early.
   139589     **
   139590     ** Similarly, if this is a search for an exact match, and the first term
   139591     ** of segment apSegment[0] is not a match, exit early.
   139592     */
   139593     if( pFilter->zTerm && !isScan ){
   139594       if( pCsr->nTerm<pFilter->nTerm
   139595        || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
   139596        || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
   139597       ){
   139598         break;
   139599       }
   139600     }
   139601 
   139602     nMerge = 1;
   139603     while( nMerge<nSegment
   139604         && apSegment[nMerge]->aNode
   139605         && apSegment[nMerge]->nTerm==pCsr->nTerm
   139606         && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
   139607     ){
   139608       nMerge++;
   139609     }
   139610 
   139611     assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
   139612     if( nMerge==1
   139613      && !isIgnoreEmpty
   139614      && !isFirst
   139615      && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
   139616     ){
   139617       pCsr->nDoclist = apSegment[0]->nDoclist;
   139618       if( fts3SegReaderIsPending(apSegment[0]) ){
   139619         rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
   139620         pCsr->aDoclist = pCsr->aBuffer;
   139621       }else{
   139622         pCsr->aDoclist = apSegment[0]->aDoclist;
   139623       }
   139624       if( rc==SQLITE_OK ) rc = SQLITE_ROW;
   139625     }else{
   139626       int nDoclist = 0;           /* Size of doclist */
   139627       sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
   139628 
   139629       /* The current term of the first nMerge entries in the array
   139630       ** of Fts3SegReader objects is the same. The doclists must be merged
   139631       ** and a single term returned with the merged doclist.
   139632       */
   139633       for(i=0; i<nMerge; i++){
   139634         fts3SegReaderFirstDocid(p, apSegment[i]);
   139635       }
   139636       fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
   139637       while( apSegment[0]->pOffsetList ){
   139638         int j;                    /* Number of segments that share a docid */
   139639         char *pList = 0;
   139640         int nList = 0;
   139641         int nByte;
   139642         sqlite3_int64 iDocid = apSegment[0]->iDocid;
   139643         fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
   139644         j = 1;
   139645         while( j<nMerge
   139646             && apSegment[j]->pOffsetList
   139647             && apSegment[j]->iDocid==iDocid
   139648         ){
   139649           fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
   139650           j++;
   139651         }
   139652 
   139653         if( isColFilter ){
   139654           fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
   139655         }
   139656 
   139657         if( !isIgnoreEmpty || nList>0 ){
   139658 
   139659           /* Calculate the 'docid' delta value to write into the merged
   139660           ** doclist. */
   139661           sqlite3_int64 iDelta;
   139662           if( p->bDescIdx && nDoclist>0 ){
   139663             iDelta = iPrev - iDocid;
   139664           }else{
   139665             iDelta = iDocid - iPrev;
   139666           }
   139667           assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
   139668           assert( nDoclist>0 || iDelta==iDocid );
   139669 
   139670           nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
   139671           if( nDoclist+nByte>pCsr->nBuffer ){
   139672             char *aNew;
   139673             pCsr->nBuffer = (nDoclist+nByte)*2;
   139674             aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
   139675             if( !aNew ){
   139676               return SQLITE_NOMEM;
   139677             }
   139678             pCsr->aBuffer = aNew;
   139679           }
   139680 
   139681           if( isFirst ){
   139682             char *a = &pCsr->aBuffer[nDoclist];
   139683             int nWrite;
   139684 
   139685             nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
   139686             if( nWrite ){
   139687               iPrev = iDocid;
   139688               nDoclist += nWrite;
   139689             }
   139690           }else{
   139691             nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
   139692             iPrev = iDocid;
   139693             if( isRequirePos ){
   139694               memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
   139695               nDoclist += nList;
   139696               pCsr->aBuffer[nDoclist++] = '\0';
   139697             }
   139698           }
   139699         }
   139700 
   139701         fts3SegReaderSort(apSegment, nMerge, j, xCmp);
   139702       }
   139703       if( nDoclist>0 ){
   139704         pCsr->aDoclist = pCsr->aBuffer;
   139705         pCsr->nDoclist = nDoclist;
   139706         rc = SQLITE_ROW;
   139707       }
   139708     }
   139709     pCsr->nAdvance = nMerge;
   139710   }while( rc==SQLITE_OK );
   139711 
   139712   return rc;
   139713 }
   139714 
   139715 
   139716 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
   139717   Fts3MultiSegReader *pCsr       /* Cursor object */
   139718 ){
   139719   if( pCsr ){
   139720     int i;
   139721     for(i=0; i<pCsr->nSegment; i++){
   139722       sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
   139723     }
   139724     sqlite3_free(pCsr->apSegment);
   139725     sqlite3_free(pCsr->aBuffer);
   139726 
   139727     pCsr->nSegment = 0;
   139728     pCsr->apSegment = 0;
   139729     pCsr->aBuffer = 0;
   139730   }
   139731 }
   139732 
   139733 /*
   139734 ** Decode the "end_block" field, selected by column iCol of the SELECT
   139735 ** statement passed as the first argument.
   139736 **
   139737 ** The "end_block" field may contain either an integer, or a text field
   139738 ** containing the text representation of two non-negative integers separated
   139739 ** by one or more space (0x20) characters. In the first case, set *piEndBlock
   139740 ** to the integer value and *pnByte to zero before returning. In the second,
   139741 ** set *piEndBlock to the first value and *pnByte to the second.
   139742 */
   139743 static void fts3ReadEndBlockField(
   139744   sqlite3_stmt *pStmt,
   139745   int iCol,
   139746   i64 *piEndBlock,
   139747   i64 *pnByte
   139748 ){
   139749   const unsigned char *zText = sqlite3_column_text(pStmt, iCol);
   139750   if( zText ){
   139751     int i;
   139752     int iMul = 1;
   139753     i64 iVal = 0;
   139754     for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
   139755       iVal = iVal*10 + (zText[i] - '0');
   139756     }
   139757     *piEndBlock = iVal;
   139758     while( zText[i]==' ' ) i++;
   139759     iVal = 0;
   139760     if( zText[i]=='-' ){
   139761       i++;
   139762       iMul = -1;
   139763     }
   139764     for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
   139765       iVal = iVal*10 + (zText[i] - '0');
   139766     }
   139767     *pnByte = (iVal * (i64)iMul);
   139768   }
   139769 }
   139770 
   139771 
   139772 /*
   139773 ** A segment of size nByte bytes has just been written to absolute level
   139774 ** iAbsLevel. Promote any segments that should be promoted as a result.
   139775 */
   139776 static int fts3PromoteSegments(
   139777   Fts3Table *p,                   /* FTS table handle */
   139778   sqlite3_int64 iAbsLevel,        /* Absolute level just updated */
   139779   sqlite3_int64 nByte             /* Size of new segment at iAbsLevel */
   139780 ){
   139781   int rc = SQLITE_OK;
   139782   sqlite3_stmt *pRange;
   139783 
   139784   rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);
   139785 
   139786   if( rc==SQLITE_OK ){
   139787     int bOk = 0;
   139788     i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
   139789     i64 nLimit = (nByte*3)/2;
   139790 
   139791     /* Loop through all entries in the %_segdir table corresponding to
   139792     ** segments in this index on levels greater than iAbsLevel. If there is
   139793     ** at least one such segment, and it is possible to determine that all
   139794     ** such segments are smaller than nLimit bytes in size, they will be
   139795     ** promoted to level iAbsLevel.  */
   139796     sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
   139797     sqlite3_bind_int64(pRange, 2, iLast);
   139798     while( SQLITE_ROW==sqlite3_step(pRange) ){
   139799       i64 nSize = 0, dummy;
   139800       fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
   139801       if( nSize<=0 || nSize>nLimit ){
   139802         /* If nSize==0, then the %_segdir.end_block field does not not
   139803         ** contain a size value. This happens if it was written by an
   139804         ** old version of FTS. In this case it is not possible to determine
   139805         ** the size of the segment, and so segment promotion does not
   139806         ** take place.  */
   139807         bOk = 0;
   139808         break;
   139809       }
   139810       bOk = 1;
   139811     }
   139812     rc = sqlite3_reset(pRange);
   139813 
   139814     if( bOk ){
   139815       int iIdx = 0;
   139816       sqlite3_stmt *pUpdate1;
   139817       sqlite3_stmt *pUpdate2;
   139818 
   139819       if( rc==SQLITE_OK ){
   139820         rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);
   139821       }
   139822       if( rc==SQLITE_OK ){
   139823         rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);
   139824       }
   139825 
   139826       if( rc==SQLITE_OK ){
   139827 
   139828         /* Loop through all %_segdir entries for segments in this index with
   139829         ** levels equal to or greater than iAbsLevel. As each entry is visited,
   139830         ** updated it to set (level = -1) and (idx = N), where N is 0 for the
   139831         ** oldest segment in the range, 1 for the next oldest, and so on.
   139832         **
   139833         ** In other words, move all segments being promoted to level -1,
   139834         ** setting the "idx" fields as appropriate to keep them in the same
   139835         ** order. The contents of level -1 (which is never used, except
   139836         ** transiently here), will be moved back to level iAbsLevel below.  */
   139837         sqlite3_bind_int64(pRange, 1, iAbsLevel);
   139838         while( SQLITE_ROW==sqlite3_step(pRange) ){
   139839           sqlite3_bind_int(pUpdate1, 1, iIdx++);
   139840           sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));
   139841           sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));
   139842           sqlite3_step(pUpdate1);
   139843           rc = sqlite3_reset(pUpdate1);
   139844           if( rc!=SQLITE_OK ){
   139845             sqlite3_reset(pRange);
   139846             break;
   139847           }
   139848         }
   139849       }
   139850       if( rc==SQLITE_OK ){
   139851         rc = sqlite3_reset(pRange);
   139852       }
   139853 
   139854       /* Move level -1 to level iAbsLevel */
   139855       if( rc==SQLITE_OK ){
   139856         sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);
   139857         sqlite3_step(pUpdate2);
   139858         rc = sqlite3_reset(pUpdate2);
   139859       }
   139860     }
   139861   }
   139862 
   139863 
   139864   return rc;
   139865 }
   139866 
   139867 /*
   139868 ** Merge all level iLevel segments in the database into a single
   139869 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
   139870 ** single segment with a level equal to the numerically largest level
   139871 ** currently present in the database.
   139872 **
   139873 ** If this function is called with iLevel<0, but there is only one
   139874 ** segment in the database, SQLITE_DONE is returned immediately.
   139875 ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
   139876 ** an SQLite error code is returned.
   139877 */
   139878 static int fts3SegmentMerge(
   139879   Fts3Table *p,
   139880   int iLangid,                    /* Language id to merge */
   139881   int iIndex,                     /* Index in p->aIndex[] to merge */
   139882   int iLevel                      /* Level to merge */
   139883 ){
   139884   int rc;                         /* Return code */
   139885   int iIdx = 0;                   /* Index of new segment */
   139886   sqlite3_int64 iNewLevel = 0;    /* Level/index to create new segment at */
   139887   SegmentWriter *pWriter = 0;     /* Used to write the new, merged, segment */
   139888   Fts3SegFilter filter;           /* Segment term filter condition */
   139889   Fts3MultiSegReader csr;         /* Cursor to iterate through level(s) */
   139890   int bIgnoreEmpty = 0;           /* True to ignore empty segments */
   139891   i64 iMaxLevel = 0;              /* Max level number for this index/langid */
   139892 
   139893   assert( iLevel==FTS3_SEGCURSOR_ALL
   139894        || iLevel==FTS3_SEGCURSOR_PENDING
   139895        || iLevel>=0
   139896   );
   139897   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
   139898   assert( iIndex>=0 && iIndex<p->nIndex );
   139899 
   139900   rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
   139901   if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
   139902 
   139903   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
   139904     rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);
   139905     if( rc!=SQLITE_OK ) goto finished;
   139906   }
   139907 
   139908   if( iLevel==FTS3_SEGCURSOR_ALL ){
   139909     /* This call is to merge all segments in the database to a single
   139910     ** segment. The level of the new segment is equal to the numerically
   139911     ** greatest segment level currently present in the database for this
   139912     ** index. The idx of the new segment is always 0.  */
   139913     if( csr.nSegment==1 ){
   139914       rc = SQLITE_DONE;
   139915       goto finished;
   139916     }
   139917     iNewLevel = iMaxLevel;
   139918     bIgnoreEmpty = 1;
   139919 
   139920   }else{
   139921     /* This call is to merge all segments at level iLevel. find the next
   139922     ** available segment index at level iLevel+1. The call to
   139923     ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
   139924     ** a single iLevel+2 segment if necessary.  */
   139925     assert( FTS3_SEGCURSOR_PENDING==-1 );
   139926     iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
   139927     rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
   139928     bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);
   139929   }
   139930   if( rc!=SQLITE_OK ) goto finished;
   139931 
   139932   assert( csr.nSegment>0 );
   139933   assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
   139934   assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
   139935 
   139936   memset(&filter, 0, sizeof(Fts3SegFilter));
   139937   filter.flags = FTS3_SEGMENT_REQUIRE_POS;
   139938   filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
   139939 
   139940   rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
   139941   while( SQLITE_OK==rc ){
   139942     rc = sqlite3Fts3SegReaderStep(p, &csr);
   139943     if( rc!=SQLITE_ROW ) break;
   139944     rc = fts3SegWriterAdd(p, &pWriter, 1,
   139945         csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
   139946   }
   139947   if( rc!=SQLITE_OK ) goto finished;
   139948   assert( pWriter || bIgnoreEmpty );
   139949 
   139950   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
   139951     rc = fts3DeleteSegdir(
   139952         p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
   139953     );
   139954     if( rc!=SQLITE_OK ) goto finished;
   139955   }
   139956   if( pWriter ){
   139957     rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
   139958     if( rc==SQLITE_OK ){
   139959       if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){
   139960         rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);
   139961       }
   139962     }
   139963   }
   139964 
   139965  finished:
   139966   fts3SegWriterFree(pWriter);
   139967   sqlite3Fts3SegReaderFinish(&csr);
   139968   return rc;
   139969 }
   139970 
   139971 
   139972 /*
   139973 ** Flush the contents of pendingTerms to level 0 segments.
   139974 */
   139975 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
   139976   int rc = SQLITE_OK;
   139977   int i;
   139978 
   139979   for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
   139980     rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
   139981     if( rc==SQLITE_DONE ) rc = SQLITE_OK;
   139982   }
   139983   sqlite3Fts3PendingTermsClear(p);
   139984 
   139985   /* Determine the auto-incr-merge setting if unknown.  If enabled,
   139986   ** estimate the number of leaf blocks of content to be written
   139987   */
   139988   if( rc==SQLITE_OK && p->bHasStat
   139989    && p->nAutoincrmerge==0xff && p->nLeafAdd>0
   139990   ){
   139991     sqlite3_stmt *pStmt = 0;
   139992     rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
   139993     if( rc==SQLITE_OK ){
   139994       sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
   139995       rc = sqlite3_step(pStmt);
   139996       if( rc==SQLITE_ROW ){
   139997         p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);
   139998         if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;
   139999       }else if( rc==SQLITE_DONE ){
   140000         p->nAutoincrmerge = 0;
   140001       }
   140002       rc = sqlite3_reset(pStmt);
   140003     }
   140004   }
   140005   return rc;
   140006 }
   140007 
   140008 /*
   140009 ** Encode N integers as varints into a blob.
   140010 */
   140011 static void fts3EncodeIntArray(
   140012   int N,             /* The number of integers to encode */
   140013   u32 *a,            /* The integer values */
   140014   char *zBuf,        /* Write the BLOB here */
   140015   int *pNBuf         /* Write number of bytes if zBuf[] used here */
   140016 ){
   140017   int i, j;
   140018   for(i=j=0; i<N; i++){
   140019     j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
   140020   }
   140021   *pNBuf = j;
   140022 }
   140023 
   140024 /*
   140025 ** Decode a blob of varints into N integers
   140026 */
   140027 static void fts3DecodeIntArray(
   140028   int N,             /* The number of integers to decode */
   140029   u32 *a,            /* Write the integer values */
   140030   const char *zBuf,  /* The BLOB containing the varints */
   140031   int nBuf           /* size of the BLOB */
   140032 ){
   140033   int i, j;
   140034   UNUSED_PARAMETER(nBuf);
   140035   for(i=j=0; i<N; i++){
   140036     sqlite3_int64 x;
   140037     j += sqlite3Fts3GetVarint(&zBuf[j], &x);
   140038     assert(j<=nBuf);
   140039     a[i] = (u32)(x & 0xffffffff);
   140040   }
   140041 }
   140042 
   140043 /*
   140044 ** Insert the sizes (in tokens) for each column of the document
   140045 ** with docid equal to p->iPrevDocid.  The sizes are encoded as
   140046 ** a blob of varints.
   140047 */
   140048 static void fts3InsertDocsize(
   140049   int *pRC,                       /* Result code */
   140050   Fts3Table *p,                   /* Table into which to insert */
   140051   u32 *aSz                        /* Sizes of each column, in tokens */
   140052 ){
   140053   char *pBlob;             /* The BLOB encoding of the document size */
   140054   int nBlob;               /* Number of bytes in the BLOB */
   140055   sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
   140056   int rc;                  /* Result code from subfunctions */
   140057 
   140058   if( *pRC ) return;
   140059   pBlob = sqlite3_malloc( 10*p->nColumn );
   140060   if( pBlob==0 ){
   140061     *pRC = SQLITE_NOMEM;
   140062     return;
   140063   }
   140064   fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
   140065   rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
   140066   if( rc ){
   140067     sqlite3_free(pBlob);
   140068     *pRC = rc;
   140069     return;
   140070   }
   140071   sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
   140072   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
   140073   sqlite3_step(pStmt);
   140074   *pRC = sqlite3_reset(pStmt);
   140075 }
   140076 
   140077 /*
   140078 ** Record 0 of the %_stat table contains a blob consisting of N varints,
   140079 ** where N is the number of user defined columns in the fts3 table plus
   140080 ** two. If nCol is the number of user defined columns, then values of the
   140081 ** varints are set as follows:
   140082 **
   140083 **   Varint 0:       Total number of rows in the table.
   140084 **
   140085 **   Varint 1..nCol: For each column, the total number of tokens stored in
   140086 **                   the column for all rows of the table.
   140087 **
   140088 **   Varint 1+nCol:  The total size, in bytes, of all text values in all
   140089 **                   columns of all rows of the table.
   140090 **
   140091 */
   140092 static void fts3UpdateDocTotals(
   140093   int *pRC,                       /* The result code */
   140094   Fts3Table *p,                   /* Table being updated */
   140095   u32 *aSzIns,                    /* Size increases */
   140096   u32 *aSzDel,                    /* Size decreases */
   140097   int nChng                       /* Change in the number of documents */
   140098 ){
   140099   char *pBlob;             /* Storage for BLOB written into %_stat */
   140100   int nBlob;               /* Size of BLOB written into %_stat */
   140101   u32 *a;                  /* Array of integers that becomes the BLOB */
   140102   sqlite3_stmt *pStmt;     /* Statement for reading and writing */
   140103   int i;                   /* Loop counter */
   140104   int rc;                  /* Result code from subfunctions */
   140105 
   140106   const int nStat = p->nColumn+2;
   140107 
   140108   if( *pRC ) return;
   140109   a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
   140110   if( a==0 ){
   140111     *pRC = SQLITE_NOMEM;
   140112     return;
   140113   }
   140114   pBlob = (char*)&a[nStat];
   140115   rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
   140116   if( rc ){
   140117     sqlite3_free(a);
   140118     *pRC = rc;
   140119     return;
   140120   }
   140121   sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
   140122   if( sqlite3_step(pStmt)==SQLITE_ROW ){
   140123     fts3DecodeIntArray(nStat, a,
   140124          sqlite3_column_blob(pStmt, 0),
   140125          sqlite3_column_bytes(pStmt, 0));
   140126   }else{
   140127     memset(a, 0, sizeof(u32)*(nStat) );
   140128   }
   140129   rc = sqlite3_reset(pStmt);
   140130   if( rc!=SQLITE_OK ){
   140131     sqlite3_free(a);
   140132     *pRC = rc;
   140133     return;
   140134   }
   140135   if( nChng<0 && a[0]<(u32)(-nChng) ){
   140136     a[0] = 0;
   140137   }else{
   140138     a[0] += nChng;
   140139   }
   140140   for(i=0; i<p->nColumn+1; i++){
   140141     u32 x = a[i+1];
   140142     if( x+aSzIns[i] < aSzDel[i] ){
   140143       x = 0;
   140144     }else{
   140145       x = x + aSzIns[i] - aSzDel[i];
   140146     }
   140147     a[i+1] = x;
   140148   }
   140149   fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
   140150   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
   140151   if( rc ){
   140152     sqlite3_free(a);
   140153     *pRC = rc;
   140154     return;
   140155   }
   140156   sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
   140157   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
   140158   sqlite3_step(pStmt);
   140159   *pRC = sqlite3_reset(pStmt);
   140160   sqlite3_free(a);
   140161 }
   140162 
   140163 /*
   140164 ** Merge the entire database so that there is one segment for each
   140165 ** iIndex/iLangid combination.
   140166 */
   140167 static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
   140168   int bSeenDone = 0;
   140169   int rc;
   140170   sqlite3_stmt *pAllLangid = 0;
   140171 
   140172   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
   140173   if( rc==SQLITE_OK ){
   140174     int rc2;
   140175     sqlite3_bind_int(pAllLangid, 1, p->nIndex);
   140176     while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
   140177       int i;
   140178       int iLangid = sqlite3_column_int(pAllLangid, 0);
   140179       for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
   140180         rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
   140181         if( rc==SQLITE_DONE ){
   140182           bSeenDone = 1;
   140183           rc = SQLITE_OK;
   140184         }
   140185       }
   140186     }
   140187     rc2 = sqlite3_reset(pAllLangid);
   140188     if( rc==SQLITE_OK ) rc = rc2;
   140189   }
   140190 
   140191   sqlite3Fts3SegmentsClose(p);
   140192   sqlite3Fts3PendingTermsClear(p);
   140193 
   140194   return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
   140195 }
   140196 
   140197 /*
   140198 ** This function is called when the user executes the following statement:
   140199 **
   140200 **     INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
   140201 **
   140202 ** The entire FTS index is discarded and rebuilt. If the table is one
   140203 ** created using the content=xxx option, then the new index is based on
   140204 ** the current contents of the xxx table. Otherwise, it is rebuilt based
   140205 ** on the contents of the %_content table.
   140206 */
   140207 static int fts3DoRebuild(Fts3Table *p){
   140208   int rc;                         /* Return Code */
   140209 
   140210   rc = fts3DeleteAll(p, 0);
   140211   if( rc==SQLITE_OK ){
   140212     u32 *aSz = 0;
   140213     u32 *aSzIns = 0;
   140214     u32 *aSzDel = 0;
   140215     sqlite3_stmt *pStmt = 0;
   140216     int nEntry = 0;
   140217 
   140218     /* Compose and prepare an SQL statement to loop through the content table */
   140219     char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
   140220     if( !zSql ){
   140221       rc = SQLITE_NOMEM;
   140222     }else{
   140223       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
   140224       sqlite3_free(zSql);
   140225     }
   140226 
   140227     if( rc==SQLITE_OK ){
   140228       int nByte = sizeof(u32) * (p->nColumn+1)*3;
   140229       aSz = (u32 *)sqlite3_malloc(nByte);
   140230       if( aSz==0 ){
   140231         rc = SQLITE_NOMEM;
   140232       }else{
   140233         memset(aSz, 0, nByte);
   140234         aSzIns = &aSz[p->nColumn+1];
   140235         aSzDel = &aSzIns[p->nColumn+1];
   140236       }
   140237     }
   140238 
   140239     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
   140240       int iCol;
   140241       int iLangid = langidFromSelect(p, pStmt);
   140242       rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pStmt, 0));
   140243       memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
   140244       for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
   140245         if( p->abNotindexed[iCol]==0 ){
   140246           const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
   140247           rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
   140248           aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
   140249         }
   140250       }
   140251       if( p->bHasDocsize ){
   140252         fts3InsertDocsize(&rc, p, aSz);
   140253       }
   140254       if( rc!=SQLITE_OK ){
   140255         sqlite3_finalize(pStmt);
   140256         pStmt = 0;
   140257       }else{
   140258         nEntry++;
   140259         for(iCol=0; iCol<=p->nColumn; iCol++){
   140260           aSzIns[iCol] += aSz[iCol];
   140261         }
   140262       }
   140263     }
   140264     if( p->bFts4 ){
   140265       fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
   140266     }
   140267     sqlite3_free(aSz);
   140268 
   140269     if( pStmt ){
   140270       int rc2 = sqlite3_finalize(pStmt);
   140271       if( rc==SQLITE_OK ){
   140272         rc = rc2;
   140273       }
   140274     }
   140275   }
   140276 
   140277   return rc;
   140278 }
   140279 
   140280 
   140281 /*
   140282 ** This function opens a cursor used to read the input data for an
   140283 ** incremental merge operation. Specifically, it opens a cursor to scan
   140284 ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
   140285 ** level iAbsLevel.
   140286 */
   140287 static int fts3IncrmergeCsr(
   140288   Fts3Table *p,                   /* FTS3 table handle */
   140289   sqlite3_int64 iAbsLevel,        /* Absolute level to open */
   140290   int nSeg,                       /* Number of segments to merge */
   140291   Fts3MultiSegReader *pCsr        /* Cursor object to populate */
   140292 ){
   140293   int rc;                         /* Return Code */
   140294   sqlite3_stmt *pStmt = 0;        /* Statement used to read %_segdir entry */
   140295   int nByte;                      /* Bytes allocated at pCsr->apSegment[] */
   140296 
   140297   /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
   140298   memset(pCsr, 0, sizeof(*pCsr));
   140299   nByte = sizeof(Fts3SegReader *) * nSeg;
   140300   pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
   140301 
   140302   if( pCsr->apSegment==0 ){
   140303     rc = SQLITE_NOMEM;
   140304   }else{
   140305     memset(pCsr->apSegment, 0, nByte);
   140306     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
   140307   }
   140308   if( rc==SQLITE_OK ){
   140309     int i;
   140310     int rc2;
   140311     sqlite3_bind_int64(pStmt, 1, iAbsLevel);
   140312     assert( pCsr->nSegment==0 );
   140313     for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
   140314       rc = sqlite3Fts3SegReaderNew(i, 0,
   140315           sqlite3_column_int64(pStmt, 1),        /* segdir.start_block */
   140316           sqlite3_column_int64(pStmt, 2),        /* segdir.leaves_end_block */
   140317           sqlite3_column_int64(pStmt, 3),        /* segdir.end_block */
   140318           sqlite3_column_blob(pStmt, 4),         /* segdir.root */
   140319           sqlite3_column_bytes(pStmt, 4),        /* segdir.root */
   140320           &pCsr->apSegment[i]
   140321       );
   140322       pCsr->nSegment++;
   140323     }
   140324     rc2 = sqlite3_reset(pStmt);
   140325     if( rc==SQLITE_OK ) rc = rc2;
   140326   }
   140327 
   140328   return rc;
   140329 }
   140330 
   140331 typedef struct IncrmergeWriter IncrmergeWriter;
   140332 typedef struct NodeWriter NodeWriter;
   140333 typedef struct Blob Blob;
   140334 typedef struct NodeReader NodeReader;
   140335 
   140336 /*
   140337 ** An instance of the following structure is used as a dynamic buffer
   140338 ** to build up nodes or other blobs of data in.
   140339 **
   140340 ** The function blobGrowBuffer() is used to extend the allocation.
   140341 */
   140342 struct Blob {
   140343   char *a;                        /* Pointer to allocation */
   140344   int n;                          /* Number of valid bytes of data in a[] */
   140345   int nAlloc;                     /* Allocated size of a[] (nAlloc>=n) */
   140346 };
   140347 
   140348 /*
   140349 ** This structure is used to build up buffers containing segment b-tree
   140350 ** nodes (blocks).
   140351 */
   140352 struct NodeWriter {
   140353   sqlite3_int64 iBlock;           /* Current block id */
   140354   Blob key;                       /* Last key written to the current block */
   140355   Blob block;                     /* Current block image */
   140356 };
   140357 
   140358 /*
   140359 ** An object of this type contains the state required to create or append
   140360 ** to an appendable b-tree segment.
   140361 */
   140362 struct IncrmergeWriter {
   140363   int nLeafEst;                   /* Space allocated for leaf blocks */
   140364   int nWork;                      /* Number of leaf pages flushed */
   140365   sqlite3_int64 iAbsLevel;        /* Absolute level of input segments */
   140366   int iIdx;                       /* Index of *output* segment in iAbsLevel+1 */
   140367   sqlite3_int64 iStart;           /* Block number of first allocated block */
   140368   sqlite3_int64 iEnd;             /* Block number of last allocated block */
   140369   sqlite3_int64 nLeafData;        /* Bytes of leaf page data so far */
   140370   u8 bNoLeafData;                 /* If true, store 0 for segment size */
   140371   NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
   140372 };
   140373 
   140374 /*
   140375 ** An object of the following type is used to read data from a single
   140376 ** FTS segment node. See the following functions:
   140377 **
   140378 **     nodeReaderInit()
   140379 **     nodeReaderNext()
   140380 **     nodeReaderRelease()
   140381 */
   140382 struct NodeReader {
   140383   const char *aNode;
   140384   int nNode;
   140385   int iOff;                       /* Current offset within aNode[] */
   140386 
   140387   /* Output variables. Containing the current node entry. */
   140388   sqlite3_int64 iChild;           /* Pointer to child node */
   140389   Blob term;                      /* Current term */
   140390   const char *aDoclist;           /* Pointer to doclist */
   140391   int nDoclist;                   /* Size of doclist in bytes */
   140392 };
   140393 
   140394 /*
   140395 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
   140396 ** Otherwise, if the allocation at pBlob->a is not already at least nMin
   140397 ** bytes in size, extend (realloc) it to be so.
   140398 **
   140399 ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
   140400 ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
   140401 ** to reflect the new size of the pBlob->a[] buffer.
   140402 */
   140403 static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
   140404   if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
   140405     int nAlloc = nMin;
   140406     char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
   140407     if( a ){
   140408       pBlob->nAlloc = nAlloc;
   140409       pBlob->a = a;
   140410     }else{
   140411       *pRc = SQLITE_NOMEM;
   140412     }
   140413   }
   140414 }
   140415 
   140416 /*
   140417 ** Attempt to advance the node-reader object passed as the first argument to
   140418 ** the next entry on the node.
   140419 **
   140420 ** Return an error code if an error occurs (SQLITE_NOMEM is possible).
   140421 ** Otherwise return SQLITE_OK. If there is no next entry on the node
   140422 ** (e.g. because the current entry is the last) set NodeReader->aNode to
   140423 ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
   140424 ** variables for the new entry.
   140425 */
   140426 static int nodeReaderNext(NodeReader *p){
   140427   int bFirst = (p->term.n==0);    /* True for first term on the node */
   140428   int nPrefix = 0;                /* Bytes to copy from previous term */
   140429   int nSuffix = 0;                /* Bytes to append to the prefix */
   140430   int rc = SQLITE_OK;             /* Return code */
   140431 
   140432   assert( p->aNode );
   140433   if( p->iChild && bFirst==0 ) p->iChild++;
   140434   if( p->iOff>=p->nNode ){
   140435     /* EOF */
   140436     p->aNode = 0;
   140437   }else{
   140438     if( bFirst==0 ){
   140439       p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
   140440     }
   140441     p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
   140442 
   140443     blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
   140444     if( rc==SQLITE_OK ){
   140445       memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
   140446       p->term.n = nPrefix+nSuffix;
   140447       p->iOff += nSuffix;
   140448       if( p->iChild==0 ){
   140449         p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
   140450         p->aDoclist = &p->aNode[p->iOff];
   140451         p->iOff += p->nDoclist;
   140452       }
   140453     }
   140454   }
   140455 
   140456   assert( p->iOff<=p->nNode );
   140457 
   140458   return rc;
   140459 }
   140460 
   140461 /*
   140462 ** Release all dynamic resources held by node-reader object *p.
   140463 */
   140464 static void nodeReaderRelease(NodeReader *p){
   140465   sqlite3_free(p->term.a);
   140466 }
   140467 
   140468 /*
   140469 ** Initialize a node-reader object to read the node in buffer aNode/nNode.
   140470 **
   140471 ** If successful, SQLITE_OK is returned and the NodeReader object set to
   140472 ** point to the first entry on the node (if any). Otherwise, an SQLite
   140473 ** error code is returned.
   140474 */
   140475 static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
   140476   memset(p, 0, sizeof(NodeReader));
   140477   p->aNode = aNode;
   140478   p->nNode = nNode;
   140479 
   140480   /* Figure out if this is a leaf or an internal node. */
   140481   if( p->aNode[0] ){
   140482     /* An internal node. */
   140483     p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
   140484   }else{
   140485     p->iOff = 1;
   140486   }
   140487 
   140488   return nodeReaderNext(p);
   140489 }
   140490 
   140491 /*
   140492 ** This function is called while writing an FTS segment each time a leaf o
   140493 ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
   140494 ** to be greater than the largest key on the node just written, but smaller
   140495 ** than or equal to the first key that will be written to the next leaf
   140496 ** node.
   140497 **
   140498 ** The block id of the leaf node just written to disk may be found in
   140499 ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
   140500 */
   140501 static int fts3IncrmergePush(
   140502   Fts3Table *p,                   /* Fts3 table handle */
   140503   IncrmergeWriter *pWriter,       /* Writer object */
   140504   const char *zTerm,              /* Term to write to internal node */
   140505   int nTerm                       /* Bytes at zTerm */
   140506 ){
   140507   sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
   140508   int iLayer;
   140509 
   140510   assert( nTerm>0 );
   140511   for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
   140512     sqlite3_int64 iNextPtr = 0;
   140513     NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
   140514     int rc = SQLITE_OK;
   140515     int nPrefix;
   140516     int nSuffix;
   140517     int nSpace;
   140518 
   140519     /* Figure out how much space the key will consume if it is written to
   140520     ** the current node of layer iLayer. Due to the prefix compression,
   140521     ** the space required changes depending on which node the key is to
   140522     ** be added to.  */
   140523     nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
   140524     nSuffix = nTerm - nPrefix;
   140525     nSpace  = sqlite3Fts3VarintLen(nPrefix);
   140526     nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
   140527 
   140528     if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
   140529       /* If the current node of layer iLayer contains zero keys, or if adding
   140530       ** the key to it will not cause it to grow to larger than nNodeSize
   140531       ** bytes in size, write the key here.  */
   140532 
   140533       Blob *pBlk = &pNode->block;
   140534       if( pBlk->n==0 ){
   140535         blobGrowBuffer(pBlk, p->nNodeSize, &rc);
   140536         if( rc==SQLITE_OK ){
   140537           pBlk->a[0] = (char)iLayer;
   140538           pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
   140539         }
   140540       }
   140541       blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
   140542       blobGrowBuffer(&pNode->key, nTerm, &rc);
   140543 
   140544       if( rc==SQLITE_OK ){
   140545         if( pNode->key.n ){
   140546           pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
   140547         }
   140548         pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
   140549         memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
   140550         pBlk->n += nSuffix;
   140551 
   140552         memcpy(pNode->key.a, zTerm, nTerm);
   140553         pNode->key.n = nTerm;
   140554       }
   140555     }else{
   140556       /* Otherwise, flush the current node of layer iLayer to disk.
   140557       ** Then allocate a new, empty sibling node. The key will be written
   140558       ** into the parent of this node. */
   140559       rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
   140560 
   140561       assert( pNode->block.nAlloc>=p->nNodeSize );
   140562       pNode->block.a[0] = (char)iLayer;
   140563       pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
   140564 
   140565       iNextPtr = pNode->iBlock;
   140566       pNode->iBlock++;
   140567       pNode->key.n = 0;
   140568     }
   140569 
   140570     if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
   140571     iPtr = iNextPtr;
   140572   }
   140573 
   140574   assert( 0 );
   140575   return 0;
   140576 }
   140577 
   140578 /*
   140579 ** Append a term and (optionally) doclist to the FTS segment node currently
   140580 ** stored in blob *pNode. The node need not contain any terms, but the
   140581 ** header must be written before this function is called.
   140582 **
   140583 ** A node header is a single 0x00 byte for a leaf node, or a height varint
   140584 ** followed by the left-hand-child varint for an internal node.
   140585 **
   140586 ** The term to be appended is passed via arguments zTerm/nTerm. For a
   140587 ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
   140588 ** node, both aDoclist and nDoclist must be passed 0.
   140589 **
   140590 ** If the size of the value in blob pPrev is zero, then this is the first
   140591 ** term written to the node. Otherwise, pPrev contains a copy of the
   140592 ** previous term. Before this function returns, it is updated to contain a
   140593 ** copy of zTerm/nTerm.
   140594 **
   140595 ** It is assumed that the buffer associated with pNode is already large
   140596 ** enough to accommodate the new entry. The buffer associated with pPrev
   140597 ** is extended by this function if requrired.
   140598 **
   140599 ** If an error (i.e. OOM condition) occurs, an SQLite error code is
   140600 ** returned. Otherwise, SQLITE_OK.
   140601 */
   140602 static int fts3AppendToNode(
   140603   Blob *pNode,                    /* Current node image to append to */
   140604   Blob *pPrev,                    /* Buffer containing previous term written */
   140605   const char *zTerm,              /* New term to write */
   140606   int nTerm,                      /* Size of zTerm in bytes */
   140607   const char *aDoclist,           /* Doclist (or NULL) to write */
   140608   int nDoclist                    /* Size of aDoclist in bytes */
   140609 ){
   140610   int rc = SQLITE_OK;             /* Return code */
   140611   int bFirst = (pPrev->n==0);     /* True if this is the first term written */
   140612   int nPrefix;                    /* Size of term prefix in bytes */
   140613   int nSuffix;                    /* Size of term suffix in bytes */
   140614 
   140615   /* Node must have already been started. There must be a doclist for a
   140616   ** leaf node, and there must not be a doclist for an internal node.  */
   140617   assert( pNode->n>0 );
   140618   assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
   140619 
   140620   blobGrowBuffer(pPrev, nTerm, &rc);
   140621   if( rc!=SQLITE_OK ) return rc;
   140622 
   140623   nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
   140624   nSuffix = nTerm - nPrefix;
   140625   memcpy(pPrev->a, zTerm, nTerm);
   140626   pPrev->n = nTerm;
   140627 
   140628   if( bFirst==0 ){
   140629     pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
   140630   }
   140631   pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
   140632   memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
   140633   pNode->n += nSuffix;
   140634 
   140635   if( aDoclist ){
   140636     pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
   140637     memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
   140638     pNode->n += nDoclist;
   140639   }
   140640 
   140641   assert( pNode->n<=pNode->nAlloc );
   140642 
   140643   return SQLITE_OK;
   140644 }
   140645 
   140646 /*
   140647 ** Append the current term and doclist pointed to by cursor pCsr to the
   140648 ** appendable b-tree segment opened for writing by pWriter.
   140649 **
   140650 ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
   140651 */
   140652 static int fts3IncrmergeAppend(
   140653   Fts3Table *p,                   /* Fts3 table handle */
   140654   IncrmergeWriter *pWriter,       /* Writer object */
   140655   Fts3MultiSegReader *pCsr        /* Cursor containing term and doclist */
   140656 ){
   140657   const char *zTerm = pCsr->zTerm;
   140658   int nTerm = pCsr->nTerm;
   140659   const char *aDoclist = pCsr->aDoclist;
   140660   int nDoclist = pCsr->nDoclist;
   140661   int rc = SQLITE_OK;           /* Return code */
   140662   int nSpace;                   /* Total space in bytes required on leaf */
   140663   int nPrefix;                  /* Size of prefix shared with previous term */
   140664   int nSuffix;                  /* Size of suffix (nTerm - nPrefix) */
   140665   NodeWriter *pLeaf;            /* Object used to write leaf nodes */
   140666 
   140667   pLeaf = &pWriter->aNodeWriter[0];
   140668   nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
   140669   nSuffix = nTerm - nPrefix;
   140670 
   140671   nSpace  = sqlite3Fts3VarintLen(nPrefix);
   140672   nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
   140673   nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
   140674 
   140675   /* If the current block is not empty, and if adding this term/doclist
   140676   ** to the current block would make it larger than Fts3Table.nNodeSize
   140677   ** bytes, write this block out to the database. */
   140678   if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
   140679     rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
   140680     pWriter->nWork++;
   140681 
   140682     /* Add the current term to the parent node. The term added to the
   140683     ** parent must:
   140684     **
   140685     **   a) be greater than the largest term on the leaf node just written
   140686     **      to the database (still available in pLeaf->key), and
   140687     **
   140688     **   b) be less than or equal to the term about to be added to the new
   140689     **      leaf node (zTerm/nTerm).
   140690     **
   140691     ** In other words, it must be the prefix of zTerm 1 byte longer than
   140692     ** the common prefix (if any) of zTerm and pWriter->zTerm.
   140693     */
   140694     if( rc==SQLITE_OK ){
   140695       rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
   140696     }
   140697 
   140698     /* Advance to the next output block */
   140699     pLeaf->iBlock++;
   140700     pLeaf->key.n = 0;
   140701     pLeaf->block.n = 0;
   140702 
   140703     nSuffix = nTerm;
   140704     nSpace  = 1;
   140705     nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
   140706     nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
   140707   }
   140708 
   140709   pWriter->nLeafData += nSpace;
   140710   blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
   140711   if( rc==SQLITE_OK ){
   140712     if( pLeaf->block.n==0 ){
   140713       pLeaf->block.n = 1;
   140714       pLeaf->block.a[0] = '\0';
   140715     }
   140716     rc = fts3AppendToNode(
   140717         &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
   140718     );
   140719   }
   140720 
   140721   return rc;
   140722 }
   140723 
   140724 /*
   140725 ** This function is called to release all dynamic resources held by the
   140726 ** merge-writer object pWriter, and if no error has occurred, to flush
   140727 ** all outstanding node buffers held by pWriter to disk.
   140728 **
   140729 ** If *pRc is not SQLITE_OK when this function is called, then no attempt
   140730 ** is made to write any data to disk. Instead, this function serves only
   140731 ** to release outstanding resources.
   140732 **
   140733 ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
   140734 ** flushing buffers to disk, *pRc is set to an SQLite error code before
   140735 ** returning.
   140736 */
   140737 static void fts3IncrmergeRelease(
   140738   Fts3Table *p,                   /* FTS3 table handle */
   140739   IncrmergeWriter *pWriter,       /* Merge-writer object */
   140740   int *pRc                        /* IN/OUT: Error code */
   140741 ){
   140742   int i;                          /* Used to iterate through non-root layers */
   140743   int iRoot;                      /* Index of root in pWriter->aNodeWriter */
   140744   NodeWriter *pRoot;              /* NodeWriter for root node */
   140745   int rc = *pRc;                  /* Error code */
   140746 
   140747   /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
   140748   ** root node. If the segment fits entirely on a single leaf node, iRoot
   140749   ** will be set to 0. If the root node is the parent of the leaves, iRoot
   140750   ** will be 1. And so on.  */
   140751   for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
   140752     NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
   140753     if( pNode->block.n>0 ) break;
   140754     assert( *pRc || pNode->block.nAlloc==0 );
   140755     assert( *pRc || pNode->key.nAlloc==0 );
   140756     sqlite3_free(pNode->block.a);
   140757     sqlite3_free(pNode->key.a);
   140758   }
   140759 
   140760   /* Empty output segment. This is a no-op. */
   140761   if( iRoot<0 ) return;
   140762 
   140763   /* The entire output segment fits on a single node. Normally, this means
   140764   ** the node would be stored as a blob in the "root" column of the %_segdir
   140765   ** table. However, this is not permitted in this case. The problem is that
   140766   ** space has already been reserved in the %_segments table, and so the
   140767   ** start_block and end_block fields of the %_segdir table must be populated.
   140768   ** And, by design or by accident, released versions of FTS cannot handle
   140769   ** segments that fit entirely on the root node with start_block!=0.
   140770   **
   140771   ** Instead, create a synthetic root node that contains nothing but a
   140772   ** pointer to the single content node. So that the segment consists of a
   140773   ** single leaf and a single interior (root) node.
   140774   **
   140775   ** Todo: Better might be to defer allocating space in the %_segments
   140776   ** table until we are sure it is needed.
   140777   */
   140778   if( iRoot==0 ){
   140779     Blob *pBlock = &pWriter->aNodeWriter[1].block;
   140780     blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
   140781     if( rc==SQLITE_OK ){
   140782       pBlock->a[0] = 0x01;
   140783       pBlock->n = 1 + sqlite3Fts3PutVarint(
   140784           &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
   140785       );
   140786     }
   140787     iRoot = 1;
   140788   }
   140789   pRoot = &pWriter->aNodeWriter[iRoot];
   140790 
   140791   /* Flush all currently outstanding nodes to disk. */
   140792   for(i=0; i<iRoot; i++){
   140793     NodeWriter *pNode = &pWriter->aNodeWriter[i];
   140794     if( pNode->block.n>0 && rc==SQLITE_OK ){
   140795       rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
   140796     }
   140797     sqlite3_free(pNode->block.a);
   140798     sqlite3_free(pNode->key.a);
   140799   }
   140800 
   140801   /* Write the %_segdir record. */
   140802   if( rc==SQLITE_OK ){
   140803     rc = fts3WriteSegdir(p,
   140804         pWriter->iAbsLevel+1,               /* level */
   140805         pWriter->iIdx,                      /* idx */
   140806         pWriter->iStart,                    /* start_block */
   140807         pWriter->aNodeWriter[0].iBlock,     /* leaves_end_block */
   140808         pWriter->iEnd,                      /* end_block */
   140809         (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0),   /* end_block */
   140810         pRoot->block.a, pRoot->block.n      /* root */
   140811     );
   140812   }
   140813   sqlite3_free(pRoot->block.a);
   140814   sqlite3_free(pRoot->key.a);
   140815 
   140816   *pRc = rc;
   140817 }
   140818 
   140819 /*
   140820 ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
   140821 ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
   140822 ** the other, it is considered to be smaller than the other.
   140823 **
   140824 ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
   140825 ** if it is greater.
   140826 */
   140827 static int fts3TermCmp(
   140828   const char *zLhs, int nLhs,     /* LHS of comparison */
   140829   const char *zRhs, int nRhs      /* RHS of comparison */
   140830 ){
   140831   int nCmp = MIN(nLhs, nRhs);
   140832   int res;
   140833 
   140834   res = memcmp(zLhs, zRhs, nCmp);
   140835   if( res==0 ) res = nLhs - nRhs;
   140836 
   140837   return res;
   140838 }
   140839 
   140840 
   140841 /*
   140842 ** Query to see if the entry in the %_segments table with blockid iEnd is
   140843 ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
   140844 ** returning. Otherwise, set *pbRes to 0.
   140845 **
   140846 ** Or, if an error occurs while querying the database, return an SQLite
   140847 ** error code. The final value of *pbRes is undefined in this case.
   140848 **
   140849 ** This is used to test if a segment is an "appendable" segment. If it
   140850 ** is, then a NULL entry has been inserted into the %_segments table
   140851 ** with blockid %_segdir.end_block.
   140852 */
   140853 static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
   140854   int bRes = 0;                   /* Result to set *pbRes to */
   140855   sqlite3_stmt *pCheck = 0;       /* Statement to query database with */
   140856   int rc;                         /* Return code */
   140857 
   140858   rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
   140859   if( rc==SQLITE_OK ){
   140860     sqlite3_bind_int64(pCheck, 1, iEnd);
   140861     if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
   140862     rc = sqlite3_reset(pCheck);
   140863   }
   140864 
   140865   *pbRes = bRes;
   140866   return rc;
   140867 }
   140868 
   140869 /*
   140870 ** This function is called when initializing an incremental-merge operation.
   140871 ** It checks if the existing segment with index value iIdx at absolute level
   140872 ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
   140873 ** merge-writer object *pWriter is initialized to write to it.
   140874 **
   140875 ** An existing segment can be appended to by an incremental merge if:
   140876 **
   140877 **   * It was initially created as an appendable segment (with all required
   140878 **     space pre-allocated), and
   140879 **
   140880 **   * The first key read from the input (arguments zKey and nKey) is
   140881 **     greater than the largest key currently stored in the potential
   140882 **     output segment.
   140883 */
   140884 static int fts3IncrmergeLoad(
   140885   Fts3Table *p,                   /* Fts3 table handle */
   140886   sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
   140887   int iIdx,                       /* Index of candidate output segment */
   140888   const char *zKey,               /* First key to write */
   140889   int nKey,                       /* Number of bytes in nKey */
   140890   IncrmergeWriter *pWriter        /* Populate this object */
   140891 ){
   140892   int rc;                         /* Return code */
   140893   sqlite3_stmt *pSelect = 0;      /* SELECT to read %_segdir entry */
   140894 
   140895   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
   140896   if( rc==SQLITE_OK ){
   140897     sqlite3_int64 iStart = 0;     /* Value of %_segdir.start_block */
   140898     sqlite3_int64 iLeafEnd = 0;   /* Value of %_segdir.leaves_end_block */
   140899     sqlite3_int64 iEnd = 0;       /* Value of %_segdir.end_block */
   140900     const char *aRoot = 0;        /* Pointer to %_segdir.root buffer */
   140901     int nRoot = 0;                /* Size of aRoot[] in bytes */
   140902     int rc2;                      /* Return code from sqlite3_reset() */
   140903     int bAppendable = 0;          /* Set to true if segment is appendable */
   140904 
   140905     /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
   140906     sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
   140907     sqlite3_bind_int(pSelect, 2, iIdx);
   140908     if( sqlite3_step(pSelect)==SQLITE_ROW ){
   140909       iStart = sqlite3_column_int64(pSelect, 1);
   140910       iLeafEnd = sqlite3_column_int64(pSelect, 2);
   140911       fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);
   140912       if( pWriter->nLeafData<0 ){
   140913         pWriter->nLeafData = pWriter->nLeafData * -1;
   140914       }
   140915       pWriter->bNoLeafData = (pWriter->nLeafData==0);
   140916       nRoot = sqlite3_column_bytes(pSelect, 4);
   140917       aRoot = sqlite3_column_blob(pSelect, 4);
   140918     }else{
   140919       return sqlite3_reset(pSelect);
   140920     }
   140921 
   140922     /* Check for the zero-length marker in the %_segments table */
   140923     rc = fts3IsAppendable(p, iEnd, &bAppendable);
   140924 
   140925     /* Check that zKey/nKey is larger than the largest key the candidate */
   140926     if( rc==SQLITE_OK && bAppendable ){
   140927       char *aLeaf = 0;
   140928       int nLeaf = 0;
   140929 
   140930       rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
   140931       if( rc==SQLITE_OK ){
   140932         NodeReader reader;
   140933         for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
   140934             rc==SQLITE_OK && reader.aNode;
   140935             rc = nodeReaderNext(&reader)
   140936         ){
   140937           assert( reader.aNode );
   140938         }
   140939         if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
   140940           bAppendable = 0;
   140941         }
   140942         nodeReaderRelease(&reader);
   140943       }
   140944       sqlite3_free(aLeaf);
   140945     }
   140946 
   140947     if( rc==SQLITE_OK && bAppendable ){
   140948       /* It is possible to append to this segment. Set up the IncrmergeWriter
   140949       ** object to do so.  */
   140950       int i;
   140951       int nHeight = (int)aRoot[0];
   140952       NodeWriter *pNode;
   140953 
   140954       pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
   140955       pWriter->iStart = iStart;
   140956       pWriter->iEnd = iEnd;
   140957       pWriter->iAbsLevel = iAbsLevel;
   140958       pWriter->iIdx = iIdx;
   140959 
   140960       for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
   140961         pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
   140962       }
   140963 
   140964       pNode = &pWriter->aNodeWriter[nHeight];
   140965       pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
   140966       blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
   140967       if( rc==SQLITE_OK ){
   140968         memcpy(pNode->block.a, aRoot, nRoot);
   140969         pNode->block.n = nRoot;
   140970       }
   140971 
   140972       for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
   140973         NodeReader reader;
   140974         pNode = &pWriter->aNodeWriter[i];
   140975 
   140976         rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
   140977         while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
   140978         blobGrowBuffer(&pNode->key, reader.term.n, &rc);
   140979         if( rc==SQLITE_OK ){
   140980           memcpy(pNode->key.a, reader.term.a, reader.term.n);
   140981           pNode->key.n = reader.term.n;
   140982           if( i>0 ){
   140983             char *aBlock = 0;
   140984             int nBlock = 0;
   140985             pNode = &pWriter->aNodeWriter[i-1];
   140986             pNode->iBlock = reader.iChild;
   140987             rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
   140988             blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
   140989             if( rc==SQLITE_OK ){
   140990               memcpy(pNode->block.a, aBlock, nBlock);
   140991               pNode->block.n = nBlock;
   140992             }
   140993             sqlite3_free(aBlock);
   140994           }
   140995         }
   140996         nodeReaderRelease(&reader);
   140997       }
   140998     }
   140999 
   141000     rc2 = sqlite3_reset(pSelect);
   141001     if( rc==SQLITE_OK ) rc = rc2;
   141002   }
   141003 
   141004   return rc;
   141005 }
   141006 
   141007 /*
   141008 ** Determine the largest segment index value that exists within absolute
   141009 ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
   141010 ** one before returning SQLITE_OK. Or, if there are no segments at all
   141011 ** within level iAbsLevel, set *piIdx to zero.
   141012 **
   141013 ** If an error occurs, return an SQLite error code. The final value of
   141014 ** *piIdx is undefined in this case.
   141015 */
   141016 static int fts3IncrmergeOutputIdx(
   141017   Fts3Table *p,                   /* FTS Table handle */
   141018   sqlite3_int64 iAbsLevel,        /* Absolute index of input segments */
   141019   int *piIdx                      /* OUT: Next free index at iAbsLevel+1 */
   141020 ){
   141021   int rc;
   141022   sqlite3_stmt *pOutputIdx = 0;   /* SQL used to find output index */
   141023 
   141024   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
   141025   if( rc==SQLITE_OK ){
   141026     sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
   141027     sqlite3_step(pOutputIdx);
   141028     *piIdx = sqlite3_column_int(pOutputIdx, 0);
   141029     rc = sqlite3_reset(pOutputIdx);
   141030   }
   141031 
   141032   return rc;
   141033 }
   141034 
   141035 /*
   141036 ** Allocate an appendable output segment on absolute level iAbsLevel+1
   141037 ** with idx value iIdx.
   141038 **
   141039 ** In the %_segdir table, a segment is defined by the values in three
   141040 ** columns:
   141041 **
   141042 **     start_block
   141043 **     leaves_end_block
   141044 **     end_block
   141045 **
   141046 ** When an appendable segment is allocated, it is estimated that the
   141047 ** maximum number of leaf blocks that may be required is the sum of the
   141048 ** number of leaf blocks consumed by the input segments, plus the number
   141049 ** of input segments, multiplied by two. This value is stored in stack
   141050 ** variable nLeafEst.
   141051 **
   141052 ** A total of 16*nLeafEst blocks are allocated when an appendable segment
   141053 ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
   141054 ** array of leaf nodes starts at the first block allocated. The array
   141055 ** of interior nodes that are parents of the leaf nodes start at block
   141056 ** (start_block + (1 + end_block - start_block) / 16). And so on.
   141057 **
   141058 ** In the actual code below, the value "16" is replaced with the
   141059 ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
   141060 */
   141061 static int fts3IncrmergeWriter(
   141062   Fts3Table *p,                   /* Fts3 table handle */
   141063   sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
   141064   int iIdx,                       /* Index of new output segment */
   141065   Fts3MultiSegReader *pCsr,       /* Cursor that data will be read from */
   141066   IncrmergeWriter *pWriter        /* Populate this object */
   141067 ){
   141068   int rc;                         /* Return Code */
   141069   int i;                          /* Iterator variable */
   141070   int nLeafEst = 0;               /* Blocks allocated for leaf nodes */
   141071   sqlite3_stmt *pLeafEst = 0;     /* SQL used to determine nLeafEst */
   141072   sqlite3_stmt *pFirstBlock = 0;  /* SQL used to determine first block */
   141073 
   141074   /* Calculate nLeafEst. */
   141075   rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
   141076   if( rc==SQLITE_OK ){
   141077     sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
   141078     sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
   141079     if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
   141080       nLeafEst = sqlite3_column_int(pLeafEst, 0);
   141081     }
   141082     rc = sqlite3_reset(pLeafEst);
   141083   }
   141084   if( rc!=SQLITE_OK ) return rc;
   141085 
   141086   /* Calculate the first block to use in the output segment */
   141087   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
   141088   if( rc==SQLITE_OK ){
   141089     if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
   141090       pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
   141091       pWriter->iEnd = pWriter->iStart - 1;
   141092       pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
   141093     }
   141094     rc = sqlite3_reset(pFirstBlock);
   141095   }
   141096   if( rc!=SQLITE_OK ) return rc;
   141097 
   141098   /* Insert the marker in the %_segments table to make sure nobody tries
   141099   ** to steal the space just allocated. This is also used to identify
   141100   ** appendable segments.  */
   141101   rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
   141102   if( rc!=SQLITE_OK ) return rc;
   141103 
   141104   pWriter->iAbsLevel = iAbsLevel;
   141105   pWriter->nLeafEst = nLeafEst;
   141106   pWriter->iIdx = iIdx;
   141107 
   141108   /* Set up the array of NodeWriter objects */
   141109   for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
   141110     pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
   141111   }
   141112   return SQLITE_OK;
   141113 }
   141114 
   141115 /*
   141116 ** Remove an entry from the %_segdir table. This involves running the
   141117 ** following two statements:
   141118 **
   141119 **   DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
   141120 **   UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
   141121 **
   141122 ** The DELETE statement removes the specific %_segdir level. The UPDATE
   141123 ** statement ensures that the remaining segments have contiguously allocated
   141124 ** idx values.
   141125 */
   141126 static int fts3RemoveSegdirEntry(
   141127   Fts3Table *p,                   /* FTS3 table handle */
   141128   sqlite3_int64 iAbsLevel,        /* Absolute level to delete from */
   141129   int iIdx                        /* Index of %_segdir entry to delete */
   141130 ){
   141131   int rc;                         /* Return code */
   141132   sqlite3_stmt *pDelete = 0;      /* DELETE statement */
   141133 
   141134   rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
   141135   if( rc==SQLITE_OK ){
   141136     sqlite3_bind_int64(pDelete, 1, iAbsLevel);
   141137     sqlite3_bind_int(pDelete, 2, iIdx);
   141138     sqlite3_step(pDelete);
   141139     rc = sqlite3_reset(pDelete);
   141140   }
   141141 
   141142   return rc;
   141143 }
   141144 
   141145 /*
   141146 ** One or more segments have just been removed from absolute level iAbsLevel.
   141147 ** Update the 'idx' values of the remaining segments in the level so that
   141148 ** the idx values are a contiguous sequence starting from 0.
   141149 */
   141150 static int fts3RepackSegdirLevel(
   141151   Fts3Table *p,                   /* FTS3 table handle */
   141152   sqlite3_int64 iAbsLevel         /* Absolute level to repack */
   141153 ){
   141154   int rc;                         /* Return code */
   141155   int *aIdx = 0;                  /* Array of remaining idx values */
   141156   int nIdx = 0;                   /* Valid entries in aIdx[] */
   141157   int nAlloc = 0;                 /* Allocated size of aIdx[] */
   141158   int i;                          /* Iterator variable */
   141159   sqlite3_stmt *pSelect = 0;      /* Select statement to read idx values */
   141160   sqlite3_stmt *pUpdate = 0;      /* Update statement to modify idx values */
   141161 
   141162   rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
   141163   if( rc==SQLITE_OK ){
   141164     int rc2;
   141165     sqlite3_bind_int64(pSelect, 1, iAbsLevel);
   141166     while( SQLITE_ROW==sqlite3_step(pSelect) ){
   141167       if( nIdx>=nAlloc ){
   141168         int *aNew;
   141169         nAlloc += 16;
   141170         aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
   141171         if( !aNew ){
   141172           rc = SQLITE_NOMEM;
   141173           break;
   141174         }
   141175         aIdx = aNew;
   141176       }
   141177       aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
   141178     }
   141179     rc2 = sqlite3_reset(pSelect);
   141180     if( rc==SQLITE_OK ) rc = rc2;
   141181   }
   141182 
   141183   if( rc==SQLITE_OK ){
   141184     rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
   141185   }
   141186   if( rc==SQLITE_OK ){
   141187     sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
   141188   }
   141189 
   141190   assert( p->bIgnoreSavepoint==0 );
   141191   p->bIgnoreSavepoint = 1;
   141192   for(i=0; rc==SQLITE_OK && i<nIdx; i++){
   141193     if( aIdx[i]!=i ){
   141194       sqlite3_bind_int(pUpdate, 3, aIdx[i]);
   141195       sqlite3_bind_int(pUpdate, 1, i);
   141196       sqlite3_step(pUpdate);
   141197       rc = sqlite3_reset(pUpdate);
   141198     }
   141199   }
   141200   p->bIgnoreSavepoint = 0;
   141201 
   141202   sqlite3_free(aIdx);
   141203   return rc;
   141204 }
   141205 
   141206 static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
   141207   pNode->a[0] = (char)iHeight;
   141208   if( iChild ){
   141209     assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
   141210     pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
   141211   }else{
   141212     assert( pNode->nAlloc>=1 );
   141213     pNode->n = 1;
   141214   }
   141215 }
   141216 
   141217 /*
   141218 ** The first two arguments are a pointer to and the size of a segment b-tree
   141219 ** node. The node may be a leaf or an internal node.
   141220 **
   141221 ** This function creates a new node image in blob object *pNew by copying
   141222 ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
   141223 ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
   141224 */
   141225 static int fts3TruncateNode(
   141226   const char *aNode,              /* Current node image */
   141227   int nNode,                      /* Size of aNode in bytes */
   141228   Blob *pNew,                     /* OUT: Write new node image here */
   141229   const char *zTerm,              /* Omit all terms smaller than this */
   141230   int nTerm,                      /* Size of zTerm in bytes */
   141231   sqlite3_int64 *piBlock          /* OUT: Block number in next layer down */
   141232 ){
   141233   NodeReader reader;              /* Reader object */
   141234   Blob prev = {0, 0, 0};          /* Previous term written to new node */
   141235   int rc = SQLITE_OK;             /* Return code */
   141236   int bLeaf = aNode[0]=='\0';     /* True for a leaf node */
   141237 
   141238   /* Allocate required output space */
   141239   blobGrowBuffer(pNew, nNode, &rc);
   141240   if( rc!=SQLITE_OK ) return rc;
   141241   pNew->n = 0;
   141242 
   141243   /* Populate new node buffer */
   141244   for(rc = nodeReaderInit(&reader, aNode, nNode);
   141245       rc==SQLITE_OK && reader.aNode;
   141246       rc = nodeReaderNext(&reader)
   141247   ){
   141248     if( pNew->n==0 ){
   141249       int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
   141250       if( res<0 || (bLeaf==0 && res==0) ) continue;
   141251       fts3StartNode(pNew, (int)aNode[0], reader.iChild);
   141252       *piBlock = reader.iChild;
   141253     }
   141254     rc = fts3AppendToNode(
   141255         pNew, &prev, reader.term.a, reader.term.n,
   141256         reader.aDoclist, reader.nDoclist
   141257     );
   141258     if( rc!=SQLITE_OK ) break;
   141259   }
   141260   if( pNew->n==0 ){
   141261     fts3StartNode(pNew, (int)aNode[0], reader.iChild);
   141262     *piBlock = reader.iChild;
   141263   }
   141264   assert( pNew->n<=pNew->nAlloc );
   141265 
   141266   nodeReaderRelease(&reader);
   141267   sqlite3_free(prev.a);
   141268   return rc;
   141269 }
   141270 
   141271 /*
   141272 ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
   141273 ** level iAbsLevel. This may involve deleting entries from the %_segments
   141274 ** table, and modifying existing entries in both the %_segments and %_segdir
   141275 ** tables.
   141276 **
   141277 ** SQLITE_OK is returned if the segment is updated successfully. Or an
   141278 ** SQLite error code otherwise.
   141279 */
   141280 static int fts3TruncateSegment(
   141281   Fts3Table *p,                   /* FTS3 table handle */
   141282   sqlite3_int64 iAbsLevel,        /* Absolute level of segment to modify */
   141283   int iIdx,                       /* Index within level of segment to modify */
   141284   const char *zTerm,              /* Remove terms smaller than this */
   141285   int nTerm                      /* Number of bytes in buffer zTerm */
   141286 ){
   141287   int rc = SQLITE_OK;             /* Return code */
   141288   Blob root = {0,0,0};            /* New root page image */
   141289   Blob block = {0,0,0};           /* Buffer used for any other block */
   141290   sqlite3_int64 iBlock = 0;       /* Block id */
   141291   sqlite3_int64 iNewStart = 0;    /* New value for iStartBlock */
   141292   sqlite3_int64 iOldStart = 0;    /* Old value for iStartBlock */
   141293   sqlite3_stmt *pFetch = 0;       /* Statement used to fetch segdir */
   141294 
   141295   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
   141296   if( rc==SQLITE_OK ){
   141297     int rc2;                      /* sqlite3_reset() return code */
   141298     sqlite3_bind_int64(pFetch, 1, iAbsLevel);
   141299     sqlite3_bind_int(pFetch, 2, iIdx);
   141300     if( SQLITE_ROW==sqlite3_step(pFetch) ){
   141301       const char *aRoot = sqlite3_column_blob(pFetch, 4);
   141302       int nRoot = sqlite3_column_bytes(pFetch, 4);
   141303       iOldStart = sqlite3_column_int64(pFetch, 1);
   141304       rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
   141305     }
   141306     rc2 = sqlite3_reset(pFetch);
   141307     if( rc==SQLITE_OK ) rc = rc2;
   141308   }
   141309 
   141310   while( rc==SQLITE_OK && iBlock ){
   141311     char *aBlock = 0;
   141312     int nBlock = 0;
   141313     iNewStart = iBlock;
   141314 
   141315     rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
   141316     if( rc==SQLITE_OK ){
   141317       rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
   141318     }
   141319     if( rc==SQLITE_OK ){
   141320       rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
   141321     }
   141322     sqlite3_free(aBlock);
   141323   }
   141324 
   141325   /* Variable iNewStart now contains the first valid leaf node. */
   141326   if( rc==SQLITE_OK && iNewStart ){
   141327     sqlite3_stmt *pDel = 0;
   141328     rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
   141329     if( rc==SQLITE_OK ){
   141330       sqlite3_bind_int64(pDel, 1, iOldStart);
   141331       sqlite3_bind_int64(pDel, 2, iNewStart-1);
   141332       sqlite3_step(pDel);
   141333       rc = sqlite3_reset(pDel);
   141334     }
   141335   }
   141336 
   141337   if( rc==SQLITE_OK ){
   141338     sqlite3_stmt *pChomp = 0;
   141339     rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
   141340     if( rc==SQLITE_OK ){
   141341       sqlite3_bind_int64(pChomp, 1, iNewStart);
   141342       sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
   141343       sqlite3_bind_int64(pChomp, 3, iAbsLevel);
   141344       sqlite3_bind_int(pChomp, 4, iIdx);
   141345       sqlite3_step(pChomp);
   141346       rc = sqlite3_reset(pChomp);
   141347     }
   141348   }
   141349 
   141350   sqlite3_free(root.a);
   141351   sqlite3_free(block.a);
   141352   return rc;
   141353 }
   141354 
   141355 /*
   141356 ** This function is called after an incrmental-merge operation has run to
   141357 ** merge (or partially merge) two or more segments from absolute level
   141358 ** iAbsLevel.
   141359 **
   141360 ** Each input segment is either removed from the db completely (if all of
   141361 ** its data was copied to the output segment by the incrmerge operation)
   141362 ** or modified in place so that it no longer contains those entries that
   141363 ** have been duplicated in the output segment.
   141364 */
   141365 static int fts3IncrmergeChomp(
   141366   Fts3Table *p,                   /* FTS table handle */
   141367   sqlite3_int64 iAbsLevel,        /* Absolute level containing segments */
   141368   Fts3MultiSegReader *pCsr,       /* Chomp all segments opened by this cursor */
   141369   int *pnRem                      /* Number of segments not deleted */
   141370 ){
   141371   int i;
   141372   int nRem = 0;
   141373   int rc = SQLITE_OK;
   141374 
   141375   for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
   141376     Fts3SegReader *pSeg = 0;
   141377     int j;
   141378 
   141379     /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
   141380     ** somewhere in the pCsr->apSegment[] array.  */
   141381     for(j=0; ALWAYS(j<pCsr->nSegment); j++){
   141382       pSeg = pCsr->apSegment[j];
   141383       if( pSeg->iIdx==i ) break;
   141384     }
   141385     assert( j<pCsr->nSegment && pSeg->iIdx==i );
   141386 
   141387     if( pSeg->aNode==0 ){
   141388       /* Seg-reader is at EOF. Remove the entire input segment. */
   141389       rc = fts3DeleteSegment(p, pSeg);
   141390       if( rc==SQLITE_OK ){
   141391         rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
   141392       }
   141393       *pnRem = 0;
   141394     }else{
   141395       /* The incremental merge did not copy all the data from this
   141396       ** segment to the upper level. The segment is modified in place
   141397       ** so that it contains no keys smaller than zTerm/nTerm. */
   141398       const char *zTerm = pSeg->zTerm;
   141399       int nTerm = pSeg->nTerm;
   141400       rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
   141401       nRem++;
   141402     }
   141403   }
   141404 
   141405   if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
   141406     rc = fts3RepackSegdirLevel(p, iAbsLevel);
   141407   }
   141408 
   141409   *pnRem = nRem;
   141410   return rc;
   141411 }
   141412 
   141413 /*
   141414 ** Store an incr-merge hint in the database.
   141415 */
   141416 static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
   141417   sqlite3_stmt *pReplace = 0;
   141418   int rc;                         /* Return code */
   141419 
   141420   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
   141421   if( rc==SQLITE_OK ){
   141422     sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
   141423     sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
   141424     sqlite3_step(pReplace);
   141425     rc = sqlite3_reset(pReplace);
   141426   }
   141427 
   141428   return rc;
   141429 }
   141430 
   141431 /*
   141432 ** Load an incr-merge hint from the database. The incr-merge hint, if one
   141433 ** exists, is stored in the rowid==1 row of the %_stat table.
   141434 **
   141435 ** If successful, populate blob *pHint with the value read from the %_stat
   141436 ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
   141437 ** SQLite error code.
   141438 */
   141439 static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
   141440   sqlite3_stmt *pSelect = 0;
   141441   int rc;
   141442 
   141443   pHint->n = 0;
   141444   rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
   141445   if( rc==SQLITE_OK ){
   141446     int rc2;
   141447     sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
   141448     if( SQLITE_ROW==sqlite3_step(pSelect) ){
   141449       const char *aHint = sqlite3_column_blob(pSelect, 0);
   141450       int nHint = sqlite3_column_bytes(pSelect, 0);
   141451       if( aHint ){
   141452         blobGrowBuffer(pHint, nHint, &rc);
   141453         if( rc==SQLITE_OK ){
   141454           memcpy(pHint->a, aHint, nHint);
   141455           pHint->n = nHint;
   141456         }
   141457       }
   141458     }
   141459     rc2 = sqlite3_reset(pSelect);
   141460     if( rc==SQLITE_OK ) rc = rc2;
   141461   }
   141462 
   141463   return rc;
   141464 }
   141465 
   141466 /*
   141467 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
   141468 ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
   141469 ** consists of two varints, the absolute level number of the input segments
   141470 ** and the number of input segments.
   141471 **
   141472 ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
   141473 ** set *pRc to an SQLite error code before returning.
   141474 */
   141475 static void fts3IncrmergeHintPush(
   141476   Blob *pHint,                    /* Hint blob to append to */
   141477   i64 iAbsLevel,                  /* First varint to store in hint */
   141478   int nInput,                     /* Second varint to store in hint */
   141479   int *pRc                        /* IN/OUT: Error code */
   141480 ){
   141481   blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
   141482   if( *pRc==SQLITE_OK ){
   141483     pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
   141484     pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
   141485   }
   141486 }
   141487 
   141488 /*
   141489 ** Read the last entry (most recently pushed) from the hint blob *pHint
   141490 ** and then remove the entry. Write the two values read to *piAbsLevel and
   141491 ** *pnInput before returning.
   141492 **
   141493 ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
   141494 ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
   141495 */
   141496 static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
   141497   const int nHint = pHint->n;
   141498   int i;
   141499 
   141500   i = pHint->n-2;
   141501   while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
   141502   while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
   141503 
   141504   pHint->n = i;
   141505   i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
   141506   i += fts3GetVarint32(&pHint->a[i], pnInput);
   141507   if( i!=nHint ) return SQLITE_CORRUPT_VTAB;
   141508 
   141509   return SQLITE_OK;
   141510 }
   141511 
   141512 
   141513 /*
   141514 ** Attempt an incremental merge that writes nMerge leaf blocks.
   141515 **
   141516 ** Incremental merges happen nMin segments at a time. The segments
   141517 ** to be merged are the nMin oldest segments (the ones with the smallest
   141518 ** values for the _segdir.idx field) in the highest level that contains
   141519 ** at least nMin segments. Multiple merges might occur in an attempt to
   141520 ** write the quota of nMerge leaf blocks.
   141521 */
   141522 SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
   141523   int rc;                         /* Return code */
   141524   int nRem = nMerge;              /* Number of leaf pages yet to  be written */
   141525   Fts3MultiSegReader *pCsr;       /* Cursor used to read input data */
   141526   Fts3SegFilter *pFilter;         /* Filter used with cursor pCsr */
   141527   IncrmergeWriter *pWriter;       /* Writer object */
   141528   int nSeg = 0;                   /* Number of input segments */
   141529   sqlite3_int64 iAbsLevel = 0;    /* Absolute level number to work on */
   141530   Blob hint = {0, 0, 0};          /* Hint read from %_stat table */
   141531   int bDirtyHint = 0;             /* True if blob 'hint' has been modified */
   141532 
   141533   /* Allocate space for the cursor, filter and writer objects */
   141534   const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
   141535   pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
   141536   if( !pWriter ) return SQLITE_NOMEM;
   141537   pFilter = (Fts3SegFilter *)&pWriter[1];
   141538   pCsr = (Fts3MultiSegReader *)&pFilter[1];
   141539 
   141540   rc = fts3IncrmergeHintLoad(p, &hint);
   141541   while( rc==SQLITE_OK && nRem>0 ){
   141542     const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
   141543     sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
   141544     int bUseHint = 0;             /* True if attempting to append */
   141545     int iIdx = 0;                 /* Largest idx in level (iAbsLevel+1) */
   141546 
   141547     /* Search the %_segdir table for the absolute level with the smallest
   141548     ** relative level number that contains at least nMin segments, if any.
   141549     ** If one is found, set iAbsLevel to the absolute level number and
   141550     ** nSeg to nMin. If no level with at least nMin segments can be found,
   141551     ** set nSeg to -1.
   141552     */
   141553     rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
   141554     sqlite3_bind_int(pFindLevel, 1, nMin);
   141555     if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
   141556       iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
   141557       nSeg = nMin;
   141558     }else{
   141559       nSeg = -1;
   141560     }
   141561     rc = sqlite3_reset(pFindLevel);
   141562 
   141563     /* If the hint read from the %_stat table is not empty, check if the
   141564     ** last entry in it specifies a relative level smaller than or equal
   141565     ** to the level identified by the block above (if any). If so, this
   141566     ** iteration of the loop will work on merging at the hinted level.
   141567     */
   141568     if( rc==SQLITE_OK && hint.n ){
   141569       int nHint = hint.n;
   141570       sqlite3_int64 iHintAbsLevel = 0;      /* Hint level */
   141571       int nHintSeg = 0;                     /* Hint number of segments */
   141572 
   141573       rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
   141574       if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
   141575         iAbsLevel = iHintAbsLevel;
   141576         nSeg = nHintSeg;
   141577         bUseHint = 1;
   141578         bDirtyHint = 1;
   141579       }else{
   141580         /* This undoes the effect of the HintPop() above - so that no entry
   141581         ** is removed from the hint blob.  */
   141582         hint.n = nHint;
   141583       }
   141584     }
   141585 
   141586     /* If nSeg is less that zero, then there is no level with at least
   141587     ** nMin segments and no hint in the %_stat table. No work to do.
   141588     ** Exit early in this case.  */
   141589     if( nSeg<0 ) break;
   141590 
   141591     /* Open a cursor to iterate through the contents of the oldest nSeg
   141592     ** indexes of absolute level iAbsLevel. If this cursor is opened using
   141593     ** the 'hint' parameters, it is possible that there are less than nSeg
   141594     ** segments available in level iAbsLevel. In this case, no work is
   141595     ** done on iAbsLevel - fall through to the next iteration of the loop
   141596     ** to start work on some other level.  */
   141597     memset(pWriter, 0, nAlloc);
   141598     pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
   141599 
   141600     if( rc==SQLITE_OK ){
   141601       rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
   141602       assert( bUseHint==1 || bUseHint==0 );
   141603       if( iIdx==0 || (bUseHint && iIdx==1) ){
   141604         int bIgnore = 0;
   141605         rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
   141606         if( bIgnore ){
   141607           pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
   141608         }
   141609       }
   141610     }
   141611 
   141612     if( rc==SQLITE_OK ){
   141613       rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
   141614     }
   141615     if( SQLITE_OK==rc && pCsr->nSegment==nSeg
   141616      && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
   141617      && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
   141618     ){
   141619       if( bUseHint && iIdx>0 ){
   141620         const char *zKey = pCsr->zTerm;
   141621         int nKey = pCsr->nTerm;
   141622         rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
   141623       }else{
   141624         rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
   141625       }
   141626 
   141627       if( rc==SQLITE_OK && pWriter->nLeafEst ){
   141628         fts3LogMerge(nSeg, iAbsLevel);
   141629         do {
   141630           rc = fts3IncrmergeAppend(p, pWriter, pCsr);
   141631           if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
   141632           if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
   141633         }while( rc==SQLITE_ROW );
   141634 
   141635         /* Update or delete the input segments */
   141636         if( rc==SQLITE_OK ){
   141637           nRem -= (1 + pWriter->nWork);
   141638           rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
   141639           if( nSeg!=0 ){
   141640             bDirtyHint = 1;
   141641             fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
   141642           }
   141643         }
   141644       }
   141645 
   141646       if( nSeg!=0 ){
   141647         pWriter->nLeafData = pWriter->nLeafData * -1;
   141648       }
   141649       fts3IncrmergeRelease(p, pWriter, &rc);
   141650       if( nSeg==0 && pWriter->bNoLeafData==0 ){
   141651         fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);
   141652       }
   141653     }
   141654 
   141655     sqlite3Fts3SegReaderFinish(pCsr);
   141656   }
   141657 
   141658   /* Write the hint values into the %_stat table for the next incr-merger */
   141659   if( bDirtyHint && rc==SQLITE_OK ){
   141660     rc = fts3IncrmergeHintStore(p, &hint);
   141661   }
   141662 
   141663   sqlite3_free(pWriter);
   141664   sqlite3_free(hint.a);
   141665   return rc;
   141666 }
   141667 
   141668 /*
   141669 ** Convert the text beginning at *pz into an integer and return
   141670 ** its value.  Advance *pz to point to the first character past
   141671 ** the integer.
   141672 */
   141673 static int fts3Getint(const char **pz){
   141674   const char *z = *pz;
   141675   int i = 0;
   141676   while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0';
   141677   *pz = z;
   141678   return i;
   141679 }
   141680 
   141681 /*
   141682 ** Process statements of the form:
   141683 **
   141684 **    INSERT INTO table(table) VALUES('merge=A,B');
   141685 **
   141686 ** A and B are integers that decode to be the number of leaf pages
   141687 ** written for the merge, and the minimum number of segments on a level
   141688 ** before it will be selected for a merge, respectively.
   141689 */
   141690 static int fts3DoIncrmerge(
   141691   Fts3Table *p,                   /* FTS3 table handle */
   141692   const char *zParam              /* Nul-terminated string containing "A,B" */
   141693 ){
   141694   int rc;
   141695   int nMin = (FTS3_MERGE_COUNT / 2);
   141696   int nMerge = 0;
   141697   const char *z = zParam;
   141698 
   141699   /* Read the first integer value */
   141700   nMerge = fts3Getint(&z);
   141701 
   141702   /* If the first integer value is followed by a ',',  read the second
   141703   ** integer value. */
   141704   if( z[0]==',' && z[1]!='\0' ){
   141705     z++;
   141706     nMin = fts3Getint(&z);
   141707   }
   141708 
   141709   if( z[0]!='\0' || nMin<2 ){
   141710     rc = SQLITE_ERROR;
   141711   }else{
   141712     rc = SQLITE_OK;
   141713     if( !p->bHasStat ){
   141714       assert( p->bFts4==0 );
   141715       sqlite3Fts3CreateStatTable(&rc, p);
   141716     }
   141717     if( rc==SQLITE_OK ){
   141718       rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
   141719     }
   141720     sqlite3Fts3SegmentsClose(p);
   141721   }
   141722   return rc;
   141723 }
   141724 
   141725 /*
   141726 ** Process statements of the form:
   141727 **
   141728 **    INSERT INTO table(table) VALUES('automerge=X');
   141729 **
   141730 ** where X is an integer.  X==0 means to turn automerge off.  X!=0 means
   141731 ** turn it on.  The setting is persistent.
   141732 */
   141733 static int fts3DoAutoincrmerge(
   141734   Fts3Table *p,                   /* FTS3 table handle */
   141735   const char *zParam              /* Nul-terminated string containing boolean */
   141736 ){
   141737   int rc = SQLITE_OK;
   141738   sqlite3_stmt *pStmt = 0;
   141739   p->nAutoincrmerge = fts3Getint(&zParam);
   141740   if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){
   141741     p->nAutoincrmerge = 8;
   141742   }
   141743   if( !p->bHasStat ){
   141744     assert( p->bFts4==0 );
   141745     sqlite3Fts3CreateStatTable(&rc, p);
   141746     if( rc ) return rc;
   141747   }
   141748   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
   141749   if( rc ) return rc;
   141750   sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
   141751   sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);
   141752   sqlite3_step(pStmt);
   141753   rc = sqlite3_reset(pStmt);
   141754   return rc;
   141755 }
   141756 
   141757 /*
   141758 ** Return a 64-bit checksum for the FTS index entry specified by the
   141759 ** arguments to this function.
   141760 */
   141761 static u64 fts3ChecksumEntry(
   141762   const char *zTerm,              /* Pointer to buffer containing term */
   141763   int nTerm,                      /* Size of zTerm in bytes */
   141764   int iLangid,                    /* Language id for current row */
   141765   int iIndex,                     /* Index (0..Fts3Table.nIndex-1) */
   141766   i64 iDocid,                     /* Docid for current row. */
   141767   int iCol,                       /* Column number */
   141768   int iPos                        /* Position */
   141769 ){
   141770   int i;
   141771   u64 ret = (u64)iDocid;
   141772 
   141773   ret += (ret<<3) + iLangid;
   141774   ret += (ret<<3) + iIndex;
   141775   ret += (ret<<3) + iCol;
   141776   ret += (ret<<3) + iPos;
   141777   for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
   141778 
   141779   return ret;
   141780 }
   141781 
   141782 /*
   141783 ** Return a checksum of all entries in the FTS index that correspond to
   141784 ** language id iLangid. The checksum is calculated by XORing the checksums
   141785 ** of each individual entry (see fts3ChecksumEntry()) together.
   141786 **
   141787 ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
   141788 ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
   141789 ** return value is undefined in this case.
   141790 */
   141791 static u64 fts3ChecksumIndex(
   141792   Fts3Table *p,                   /* FTS3 table handle */
   141793   int iLangid,                    /* Language id to return cksum for */
   141794   int iIndex,                     /* Index to cksum (0..p->nIndex-1) */
   141795   int *pRc                        /* OUT: Return code */
   141796 ){
   141797   Fts3SegFilter filter;
   141798   Fts3MultiSegReader csr;
   141799   int rc;
   141800   u64 cksum = 0;
   141801 
   141802   assert( *pRc==SQLITE_OK );
   141803 
   141804   memset(&filter, 0, sizeof(filter));
   141805   memset(&csr, 0, sizeof(csr));
   141806   filter.flags =  FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
   141807   filter.flags |= FTS3_SEGMENT_SCAN;
   141808 
   141809   rc = sqlite3Fts3SegReaderCursor(
   141810       p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
   141811   );
   141812   if( rc==SQLITE_OK ){
   141813     rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
   141814   }
   141815 
   141816   if( rc==SQLITE_OK ){
   141817     while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
   141818       char *pCsr = csr.aDoclist;
   141819       char *pEnd = &pCsr[csr.nDoclist];
   141820 
   141821       i64 iDocid = 0;
   141822       i64 iCol = 0;
   141823       i64 iPos = 0;
   141824 
   141825       pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
   141826       while( pCsr<pEnd ){
   141827         i64 iVal = 0;
   141828         pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
   141829         if( pCsr<pEnd ){
   141830           if( iVal==0 || iVal==1 ){
   141831             iCol = 0;
   141832             iPos = 0;
   141833             if( iVal ){
   141834               pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
   141835             }else{
   141836               pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
   141837               iDocid += iVal;
   141838             }
   141839           }else{
   141840             iPos += (iVal - 2);
   141841             cksum = cksum ^ fts3ChecksumEntry(
   141842                 csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
   141843                 (int)iCol, (int)iPos
   141844             );
   141845           }
   141846         }
   141847       }
   141848     }
   141849   }
   141850   sqlite3Fts3SegReaderFinish(&csr);
   141851 
   141852   *pRc = rc;
   141853   return cksum;
   141854 }
   141855 
   141856 /*
   141857 ** Check if the contents of the FTS index match the current contents of the
   141858 ** content table. If no error occurs and the contents do match, set *pbOk
   141859 ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
   141860 ** to false before returning.
   141861 **
   141862 ** If an error occurs (e.g. an OOM or IO error), return an SQLite error
   141863 ** code. The final value of *pbOk is undefined in this case.
   141864 */
   141865 static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
   141866   int rc = SQLITE_OK;             /* Return code */
   141867   u64 cksum1 = 0;                 /* Checksum based on FTS index contents */
   141868   u64 cksum2 = 0;                 /* Checksum based on %_content contents */
   141869   sqlite3_stmt *pAllLangid = 0;   /* Statement to return all language-ids */
   141870 
   141871   /* This block calculates the checksum according to the FTS index. */
   141872   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
   141873   if( rc==SQLITE_OK ){
   141874     int rc2;
   141875     sqlite3_bind_int(pAllLangid, 1, p->nIndex);
   141876     while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
   141877       int iLangid = sqlite3_column_int(pAllLangid, 0);
   141878       int i;
   141879       for(i=0; i<p->nIndex; i++){
   141880         cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
   141881       }
   141882     }
   141883     rc2 = sqlite3_reset(pAllLangid);
   141884     if( rc==SQLITE_OK ) rc = rc2;
   141885   }
   141886 
   141887   /* This block calculates the checksum according to the %_content table */
   141888   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
   141889   if( rc==SQLITE_OK ){
   141890     sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
   141891     sqlite3_stmt *pStmt = 0;
   141892     char *zSql;
   141893 
   141894     zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
   141895     if( !zSql ){
   141896       rc = SQLITE_NOMEM;
   141897     }else{
   141898       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
   141899       sqlite3_free(zSql);
   141900     }
   141901 
   141902     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
   141903       i64 iDocid = sqlite3_column_int64(pStmt, 0);
   141904       int iLang = langidFromSelect(p, pStmt);
   141905       int iCol;
   141906 
   141907       for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
   141908         if( p->abNotindexed[iCol]==0 ){
   141909           const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
   141910           int nText = sqlite3_column_bytes(pStmt, iCol+1);
   141911           sqlite3_tokenizer_cursor *pT = 0;
   141912 
   141913           rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText,&pT);
   141914           while( rc==SQLITE_OK ){
   141915             char const *zToken;       /* Buffer containing token */
   141916             int nToken = 0;           /* Number of bytes in token */
   141917             int iDum1 = 0, iDum2 = 0; /* Dummy variables */
   141918             int iPos = 0;             /* Position of token in zText */
   141919 
   141920             rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
   141921             if( rc==SQLITE_OK ){
   141922               int i;
   141923               cksum2 = cksum2 ^ fts3ChecksumEntry(
   141924                   zToken, nToken, iLang, 0, iDocid, iCol, iPos
   141925               );
   141926               for(i=1; i<p->nIndex; i++){
   141927                 if( p->aIndex[i].nPrefix<=nToken ){
   141928                   cksum2 = cksum2 ^ fts3ChecksumEntry(
   141929                       zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
   141930                   );
   141931                 }
   141932               }
   141933             }
   141934           }
   141935           if( pT ) pModule->xClose(pT);
   141936           if( rc==SQLITE_DONE ) rc = SQLITE_OK;
   141937         }
   141938       }
   141939     }
   141940 
   141941     sqlite3_finalize(pStmt);
   141942   }
   141943 
   141944   *pbOk = (cksum1==cksum2);
   141945   return rc;
   141946 }
   141947 
   141948 /*
   141949 ** Run the integrity-check. If no error occurs and the current contents of
   141950 ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
   141951 ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
   141952 **
   141953 ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
   141954 ** error code.
   141955 **
   141956 ** The integrity-check works as follows. For each token and indexed token
   141957 ** prefix in the document set, a 64-bit checksum is calculated (by code
   141958 ** in fts3ChecksumEntry()) based on the following:
   141959 **
   141960 **     + The index number (0 for the main index, 1 for the first prefix
   141961 **       index etc.),
   141962 **     + The token (or token prefix) text itself,
   141963 **     + The language-id of the row it appears in,
   141964 **     + The docid of the row it appears in,
   141965 **     + The column it appears in, and
   141966 **     + The tokens position within that column.
   141967 **
   141968 ** The checksums for all entries in the index are XORed together to create
   141969 ** a single checksum for the entire index.
   141970 **
   141971 ** The integrity-check code calculates the same checksum in two ways:
   141972 **
   141973 **     1. By scanning the contents of the FTS index, and
   141974 **     2. By scanning and tokenizing the content table.
   141975 **
   141976 ** If the two checksums are identical, the integrity-check is deemed to have
   141977 ** passed.
   141978 */
   141979 static int fts3DoIntegrityCheck(
   141980   Fts3Table *p                    /* FTS3 table handle */
   141981 ){
   141982   int rc;
   141983   int bOk = 0;
   141984   rc = fts3IntegrityCheck(p, &bOk);
   141985   if( rc==SQLITE_OK && bOk==0 ) rc = SQLITE_CORRUPT_VTAB;
   141986   return rc;
   141987 }
   141988 
   141989 /*
   141990 ** Handle a 'special' INSERT of the form:
   141991 **
   141992 **   "INSERT INTO tbl(tbl) VALUES(<expr>)"
   141993 **
   141994 ** Argument pVal contains the result of <expr>. Currently the only
   141995 ** meaningful value to insert is the text 'optimize'.
   141996 */
   141997 static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
   141998   int rc;                         /* Return Code */
   141999   const char *zVal = (const char *)sqlite3_value_text(pVal);
   142000   int nVal = sqlite3_value_bytes(pVal);
   142001 
   142002   if( !zVal ){
   142003     return SQLITE_NOMEM;
   142004   }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
   142005     rc = fts3DoOptimize(p, 0);
   142006   }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
   142007     rc = fts3DoRebuild(p);
   142008   }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
   142009     rc = fts3DoIntegrityCheck(p);
   142010   }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
   142011     rc = fts3DoIncrmerge(p, &zVal[6]);
   142012   }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
   142013     rc = fts3DoAutoincrmerge(p, &zVal[10]);
   142014 #ifdef SQLITE_TEST
   142015   }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
   142016     p->nNodeSize = atoi(&zVal[9]);
   142017     rc = SQLITE_OK;
   142018   }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
   142019     p->nMaxPendingData = atoi(&zVal[11]);
   142020     rc = SQLITE_OK;
   142021   }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
   142022     p->bNoIncrDoclist = atoi(&zVal[21]);
   142023     rc = SQLITE_OK;
   142024 #endif
   142025   }else{
   142026     rc = SQLITE_ERROR;
   142027   }
   142028 
   142029   return rc;
   142030 }
   142031 
   142032 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
   142033 /*
   142034 ** Delete all cached deferred doclists. Deferred doclists are cached
   142035 ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
   142036 */
   142037 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
   142038   Fts3DeferredToken *pDef;
   142039   for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
   142040     fts3PendingListDelete(pDef->pList);
   142041     pDef->pList = 0;
   142042   }
   142043 }
   142044 
   142045 /*
   142046 ** Free all entries in the pCsr->pDeffered list. Entries are added to
   142047 ** this list using sqlite3Fts3DeferToken().
   142048 */
   142049 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
   142050   Fts3DeferredToken *pDef;
   142051   Fts3DeferredToken *pNext;
   142052   for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
   142053     pNext = pDef->pNext;
   142054     fts3PendingListDelete(pDef->pList);
   142055     sqlite3_free(pDef);
   142056   }
   142057   pCsr->pDeferred = 0;
   142058 }
   142059 
   142060 /*
   142061 ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
   142062 ** based on the row that pCsr currently points to.
   142063 **
   142064 ** A deferred-doclist is like any other doclist with position information
   142065 ** included, except that it only contains entries for a single row of the
   142066 ** table, not for all rows.
   142067 */
   142068 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
   142069   int rc = SQLITE_OK;             /* Return code */
   142070   if( pCsr->pDeferred ){
   142071     int i;                        /* Used to iterate through table columns */
   142072     sqlite3_int64 iDocid;         /* Docid of the row pCsr points to */
   142073     Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */
   142074 
   142075     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
   142076     sqlite3_tokenizer *pT = p->pTokenizer;
   142077     sqlite3_tokenizer_module const *pModule = pT->pModule;
   142078 
   142079     assert( pCsr->isRequireSeek==0 );
   142080     iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
   142081 
   142082     for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
   142083       if( p->abNotindexed[i]==0 ){
   142084         const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
   142085         sqlite3_tokenizer_cursor *pTC = 0;
   142086 
   142087         rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
   142088         while( rc==SQLITE_OK ){
   142089           char const *zToken;       /* Buffer containing token */
   142090           int nToken = 0;           /* Number of bytes in token */
   142091           int iDum1 = 0, iDum2 = 0; /* Dummy variables */
   142092           int iPos = 0;             /* Position of token in zText */
   142093 
   142094           rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
   142095           for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
   142096             Fts3PhraseToken *pPT = pDef->pToken;
   142097             if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
   142098                 && (pPT->bFirst==0 || iPos==0)
   142099                 && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
   142100                 && (0==memcmp(zToken, pPT->z, pPT->n))
   142101               ){
   142102               fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
   142103             }
   142104           }
   142105         }
   142106         if( pTC ) pModule->xClose(pTC);
   142107         if( rc==SQLITE_DONE ) rc = SQLITE_OK;
   142108       }
   142109     }
   142110 
   142111     for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
   142112       if( pDef->pList ){
   142113         rc = fts3PendingListAppendVarint(&pDef->pList, 0);
   142114       }
   142115     }
   142116   }
   142117 
   142118   return rc;
   142119 }
   142120 
   142121 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
   142122   Fts3DeferredToken *p,
   142123   char **ppData,
   142124   int *pnData
   142125 ){
   142126   char *pRet;
   142127   int nSkip;
   142128   sqlite3_int64 dummy;
   142129 
   142130   *ppData = 0;
   142131   *pnData = 0;
   142132 
   142133   if( p->pList==0 ){
   142134     return SQLITE_OK;
   142135   }
   142136 
   142137   pRet = (char *)sqlite3_malloc(p->pList->nData);
   142138   if( !pRet ) return SQLITE_NOMEM;
   142139 
   142140   nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
   142141   *pnData = p->pList->nData - nSkip;
   142142   *ppData = pRet;
   142143 
   142144   memcpy(pRet, &p->pList->aData[nSkip], *pnData);
   142145   return SQLITE_OK;
   142146 }
   142147 
   142148 /*
   142149 ** Add an entry for token pToken to the pCsr->pDeferred list.
   142150 */
   142151 SQLITE_PRIVATE int sqlite3Fts3DeferToken(
   142152   Fts3Cursor *pCsr,               /* Fts3 table cursor */
   142153   Fts3PhraseToken *pToken,        /* Token to defer */
   142154   int iCol                        /* Column that token must appear in (or -1) */
   142155 ){
   142156   Fts3DeferredToken *pDeferred;
   142157   pDeferred = sqlite3_malloc(sizeof(*pDeferred));
   142158   if( !pDeferred ){
   142159     return SQLITE_NOMEM;
   142160   }
   142161   memset(pDeferred, 0, sizeof(*pDeferred));
   142162   pDeferred->pToken = pToken;
   142163   pDeferred->pNext = pCsr->pDeferred;
   142164   pDeferred->iCol = iCol;
   142165   pCsr->pDeferred = pDeferred;
   142166 
   142167   assert( pToken->pDeferred==0 );
   142168   pToken->pDeferred = pDeferred;
   142169 
   142170   return SQLITE_OK;
   142171 }
   142172 #endif
   142173 
   142174 /*
   142175 ** SQLite value pRowid contains the rowid of a row that may or may not be
   142176 ** present in the FTS3 table. If it is, delete it and adjust the contents
   142177 ** of subsiduary data structures accordingly.
   142178 */
   142179 static int fts3DeleteByRowid(
   142180   Fts3Table *p,
   142181   sqlite3_value *pRowid,
   142182   int *pnChng,                    /* IN/OUT: Decrement if row is deleted */
   142183   u32 *aSzDel
   142184 ){
   142185   int rc = SQLITE_OK;             /* Return code */
   142186   int bFound = 0;                 /* True if *pRowid really is in the table */
   142187 
   142188   fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
   142189   if( bFound && rc==SQLITE_OK ){
   142190     int isEmpty = 0;              /* Deleting *pRowid leaves the table empty */
   142191     rc = fts3IsEmpty(p, pRowid, &isEmpty);
   142192     if( rc==SQLITE_OK ){
   142193       if( isEmpty ){
   142194         /* Deleting this row means the whole table is empty. In this case
   142195         ** delete the contents of all three tables and throw away any
   142196         ** data in the pendingTerms hash table.  */
   142197         rc = fts3DeleteAll(p, 1);
   142198         *pnChng = 0;
   142199         memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
   142200       }else{
   142201         *pnChng = *pnChng - 1;
   142202         if( p->zContentTbl==0 ){
   142203           fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
   142204         }
   142205         if( p->bHasDocsize ){
   142206           fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
   142207         }
   142208       }
   142209     }
   142210   }
   142211 
   142212   return rc;
   142213 }
   142214 
   142215 /*
   142216 ** This function does the work for the xUpdate method of FTS3 virtual
   142217 ** tables. The schema of the virtual table being:
   142218 **
   142219 **     CREATE TABLE <table name>(
   142220 **       <user columns>,
   142221 **       <table name> HIDDEN,
   142222 **       docid HIDDEN,
   142223 **       <langid> HIDDEN
   142224 **     );
   142225 **
   142226 **
   142227 */
   142228 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
   142229   sqlite3_vtab *pVtab,            /* FTS3 vtab object */
   142230   int nArg,                       /* Size of argument array */
   142231   sqlite3_value **apVal,          /* Array of arguments */
   142232   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
   142233 ){
   142234   Fts3Table *p = (Fts3Table *)pVtab;
   142235   int rc = SQLITE_OK;             /* Return Code */
   142236   int isRemove = 0;               /* True for an UPDATE or DELETE */
   142237   u32 *aSzIns = 0;                /* Sizes of inserted documents */
   142238   u32 *aSzDel = 0;                /* Sizes of deleted documents */
   142239   int nChng = 0;                  /* Net change in number of documents */
   142240   int bInsertDone = 0;
   142241 
   142242   /* At this point it must be known if the %_stat table exists or not.
   142243   ** So bHasStat may not be 2.  */
   142244   assert( p->bHasStat==0 || p->bHasStat==1 );
   142245 
   142246   assert( p->pSegments==0 );
   142247   assert(
   142248       nArg==1                     /* DELETE operations */
   142249    || nArg==(2 + p->nColumn + 3)  /* INSERT or UPDATE operations */
   142250   );
   142251 
   142252   /* Check for a "special" INSERT operation. One of the form:
   142253   **
   142254   **   INSERT INTO xyz(xyz) VALUES('command');
   142255   */
   142256   if( nArg>1
   142257    && sqlite3_value_type(apVal[0])==SQLITE_NULL
   142258    && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
   142259   ){
   142260     rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
   142261     goto update_out;
   142262   }
   142263 
   142264   if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
   142265     rc = SQLITE_CONSTRAINT;
   142266     goto update_out;
   142267   }
   142268 
   142269   /* Allocate space to hold the change in document sizes */
   142270   aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
   142271   if( aSzDel==0 ){
   142272     rc = SQLITE_NOMEM;
   142273     goto update_out;
   142274   }
   142275   aSzIns = &aSzDel[p->nColumn+1];
   142276   memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
   142277 
   142278   rc = fts3Writelock(p);
   142279   if( rc!=SQLITE_OK ) goto update_out;
   142280 
   142281   /* If this is an INSERT operation, or an UPDATE that modifies the rowid
   142282   ** value, then this operation requires constraint handling.
   142283   **
   142284   ** If the on-conflict mode is REPLACE, this means that the existing row
   142285   ** should be deleted from the database before inserting the new row. Or,
   142286   ** if the on-conflict mode is other than REPLACE, then this method must
   142287   ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
   142288   ** modify the database file.
   142289   */
   142290   if( nArg>1 && p->zContentTbl==0 ){
   142291     /* Find the value object that holds the new rowid value. */
   142292     sqlite3_value *pNewRowid = apVal[3+p->nColumn];
   142293     if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
   142294       pNewRowid = apVal[1];
   142295     }
   142296 
   142297     if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
   142298         sqlite3_value_type(apVal[0])==SQLITE_NULL
   142299      || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
   142300     )){
   142301       /* The new rowid is not NULL (in this case the rowid will be
   142302       ** automatically assigned and there is no chance of a conflict), and
   142303       ** the statement is either an INSERT or an UPDATE that modifies the
   142304       ** rowid column. So if the conflict mode is REPLACE, then delete any
   142305       ** existing row with rowid=pNewRowid.
   142306       **
   142307       ** Or, if the conflict mode is not REPLACE, insert the new record into
   142308       ** the %_content table. If we hit the duplicate rowid constraint (or any
   142309       ** other error) while doing so, return immediately.
   142310       **
   142311       ** This branch may also run if pNewRowid contains a value that cannot
   142312       ** be losslessly converted to an integer. In this case, the eventual
   142313       ** call to fts3InsertData() (either just below or further on in this
   142314       ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
   142315       ** invoked, it will delete zero rows (since no row will have
   142316       ** docid=$pNewRowid if $pNewRowid is not an integer value).
   142317       */
   142318       if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
   142319         rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
   142320       }else{
   142321         rc = fts3InsertData(p, apVal, pRowid);
   142322         bInsertDone = 1;
   142323       }
   142324     }
   142325   }
   142326   if( rc!=SQLITE_OK ){
   142327     goto update_out;
   142328   }
   142329 
   142330   /* If this is a DELETE or UPDATE operation, remove the old record. */
   142331   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
   142332     assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
   142333     rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
   142334     isRemove = 1;
   142335   }
   142336 
   142337   /* If this is an INSERT or UPDATE operation, insert the new record. */
   142338   if( nArg>1 && rc==SQLITE_OK ){
   142339     int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
   142340     if( bInsertDone==0 ){
   142341       rc = fts3InsertData(p, apVal, pRowid);
   142342       if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
   142343         rc = FTS_CORRUPT_VTAB;
   142344       }
   142345     }
   142346     if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
   142347       rc = fts3PendingTermsDocid(p, iLangid, *pRowid);
   142348     }
   142349     if( rc==SQLITE_OK ){
   142350       assert( p->iPrevDocid==*pRowid );
   142351       rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
   142352     }
   142353     if( p->bHasDocsize ){
   142354       fts3InsertDocsize(&rc, p, aSzIns);
   142355     }
   142356     nChng++;
   142357   }
   142358 
   142359   if( p->bFts4 ){
   142360     fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
   142361   }
   142362 
   142363  update_out:
   142364   sqlite3_free(aSzDel);
   142365   sqlite3Fts3SegmentsClose(p);
   142366   return rc;
   142367 }
   142368 
   142369 /*
   142370 ** Flush any data in the pending-terms hash table to disk. If successful,
   142371 ** merge all segments in the database (including the new segment, if
   142372 ** there was any data to flush) into a single segment.
   142373 */
   142374 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
   142375   int rc;
   142376   rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
   142377   if( rc==SQLITE_OK ){
   142378     rc = fts3DoOptimize(p, 1);
   142379     if( rc==SQLITE_OK || rc==SQLITE_DONE ){
   142380       int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
   142381       if( rc2!=SQLITE_OK ) rc = rc2;
   142382     }else{
   142383       sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
   142384       sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
   142385     }
   142386   }
   142387   sqlite3Fts3SegmentsClose(p);
   142388   return rc;
   142389 }
   142390 
   142391 #endif
   142392 
   142393 /************** End of fts3_write.c ******************************************/
   142394 /************** Begin file fts3_snippet.c ************************************/
   142395 /*
   142396 ** 2009 Oct 23
   142397 **
   142398 ** The author disclaims copyright to this source code.  In place of
   142399 ** a legal notice, here is a blessing:
   142400 **
   142401 **    May you do good and not evil.
   142402 **    May you find forgiveness for yourself and forgive others.
   142403 **    May you share freely, never taking more than you give.
   142404 **
   142405 ******************************************************************************
   142406 */
   142407 
   142408 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   142409 
   142410 /* #include <string.h> */
   142411 /* #include <assert.h> */
   142412 
   142413 /*
   142414 ** Characters that may appear in the second argument to matchinfo().
   142415 */
   142416 #define FTS3_MATCHINFO_NPHRASE   'p'        /* 1 value */
   142417 #define FTS3_MATCHINFO_NCOL      'c'        /* 1 value */
   142418 #define FTS3_MATCHINFO_NDOC      'n'        /* 1 value */
   142419 #define FTS3_MATCHINFO_AVGLENGTH 'a'        /* nCol values */
   142420 #define FTS3_MATCHINFO_LENGTH    'l'        /* nCol values */
   142421 #define FTS3_MATCHINFO_LCS       's'        /* nCol values */
   142422 #define FTS3_MATCHINFO_HITS      'x'        /* 3*nCol*nPhrase values */
   142423 
   142424 /*
   142425 ** The default value for the second argument to matchinfo().
   142426 */
   142427 #define FTS3_MATCHINFO_DEFAULT   "pcx"
   142428 
   142429 
   142430 /*
   142431 ** Used as an fts3ExprIterate() context when loading phrase doclists to
   142432 ** Fts3Expr.aDoclist[]/nDoclist.
   142433 */
   142434 typedef struct LoadDoclistCtx LoadDoclistCtx;
   142435 struct LoadDoclistCtx {
   142436   Fts3Cursor *pCsr;               /* FTS3 Cursor */
   142437   int nPhrase;                    /* Number of phrases seen so far */
   142438   int nToken;                     /* Number of tokens seen so far */
   142439 };
   142440 
   142441 /*
   142442 ** The following types are used as part of the implementation of the
   142443 ** fts3BestSnippet() routine.
   142444 */
   142445 typedef struct SnippetIter SnippetIter;
   142446 typedef struct SnippetPhrase SnippetPhrase;
   142447 typedef struct SnippetFragment SnippetFragment;
   142448 
   142449 struct SnippetIter {
   142450   Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
   142451   int iCol;                       /* Extract snippet from this column */
   142452   int nSnippet;                   /* Requested snippet length (in tokens) */
   142453   int nPhrase;                    /* Number of phrases in query */
   142454   SnippetPhrase *aPhrase;         /* Array of size nPhrase */
   142455   int iCurrent;                   /* First token of current snippet */
   142456 };
   142457 
   142458 struct SnippetPhrase {
   142459   int nToken;                     /* Number of tokens in phrase */
   142460   char *pList;                    /* Pointer to start of phrase position list */
   142461   int iHead;                      /* Next value in position list */
   142462   char *pHead;                    /* Position list data following iHead */
   142463   int iTail;                      /* Next value in trailing position list */
   142464   char *pTail;                    /* Position list data following iTail */
   142465 };
   142466 
   142467 struct SnippetFragment {
   142468   int iCol;                       /* Column snippet is extracted from */
   142469   int iPos;                       /* Index of first token in snippet */
   142470   u64 covered;                    /* Mask of query phrases covered */
   142471   u64 hlmask;                     /* Mask of snippet terms to highlight */
   142472 };
   142473 
   142474 /*
   142475 ** This type is used as an fts3ExprIterate() context object while
   142476 ** accumulating the data returned by the matchinfo() function.
   142477 */
   142478 typedef struct MatchInfo MatchInfo;
   142479 struct MatchInfo {
   142480   Fts3Cursor *pCursor;            /* FTS3 Cursor */
   142481   int nCol;                       /* Number of columns in table */
   142482   int nPhrase;                    /* Number of matchable phrases in query */
   142483   sqlite3_int64 nDoc;             /* Number of docs in database */
   142484   u32 *aMatchinfo;                /* Pre-allocated buffer */
   142485 };
   142486 
   142487 
   142488 
   142489 /*
   142490 ** The snippet() and offsets() functions both return text values. An instance
   142491 ** of the following structure is used to accumulate those values while the
   142492 ** functions are running. See fts3StringAppend() for details.
   142493 */
   142494 typedef struct StrBuffer StrBuffer;
   142495 struct StrBuffer {
   142496   char *z;                        /* Pointer to buffer containing string */
   142497   int n;                          /* Length of z in bytes (excl. nul-term) */
   142498   int nAlloc;                     /* Allocated size of buffer z in bytes */
   142499 };
   142500 
   142501 
   142502 /*
   142503 ** This function is used to help iterate through a position-list. A position
   142504 ** list is a list of unique integers, sorted from smallest to largest. Each
   142505 ** element of the list is represented by an FTS3 varint that takes the value
   142506 ** of the difference between the current element and the previous one plus
   142507 ** two. For example, to store the position-list:
   142508 **
   142509 **     4 9 113
   142510 **
   142511 ** the three varints:
   142512 **
   142513 **     6 7 106
   142514 **
   142515 ** are encoded.
   142516 **
   142517 ** When this function is called, *pp points to the start of an element of
   142518 ** the list. *piPos contains the value of the previous entry in the list.
   142519 ** After it returns, *piPos contains the value of the next element of the
   142520 ** list and *pp is advanced to the following varint.
   142521 */
   142522 static void fts3GetDeltaPosition(char **pp, int *piPos){
   142523   int iVal;
   142524   *pp += fts3GetVarint32(*pp, &iVal);
   142525   *piPos += (iVal-2);
   142526 }
   142527 
   142528 /*
   142529 ** Helper function for fts3ExprIterate() (see below).
   142530 */
   142531 static int fts3ExprIterate2(
   142532   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
   142533   int *piPhrase,                  /* Pointer to phrase counter */
   142534   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
   142535   void *pCtx                      /* Second argument to pass to callback */
   142536 ){
   142537   int rc;                         /* Return code */
   142538   int eType = pExpr->eType;       /* Type of expression node pExpr */
   142539 
   142540   if( eType!=FTSQUERY_PHRASE ){
   142541     assert( pExpr->pLeft && pExpr->pRight );
   142542     rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
   142543     if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
   142544       rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
   142545     }
   142546   }else{
   142547     rc = x(pExpr, *piPhrase, pCtx);
   142548     (*piPhrase)++;
   142549   }
   142550   return rc;
   142551 }
   142552 
   142553 /*
   142554 ** Iterate through all phrase nodes in an FTS3 query, except those that
   142555 ** are part of a sub-tree that is the right-hand-side of a NOT operator.
   142556 ** For each phrase node found, the supplied callback function is invoked.
   142557 **
   142558 ** If the callback function returns anything other than SQLITE_OK,
   142559 ** the iteration is abandoned and the error code returned immediately.
   142560 ** Otherwise, SQLITE_OK is returned after a callback has been made for
   142561 ** all eligible phrase nodes.
   142562 */
   142563 static int fts3ExprIterate(
   142564   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
   142565   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
   142566   void *pCtx                      /* Second argument to pass to callback */
   142567 ){
   142568   int iPhrase = 0;                /* Variable used as the phrase counter */
   142569   return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
   142570 }
   142571 
   142572 /*
   142573 ** This is an fts3ExprIterate() callback used while loading the doclists
   142574 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
   142575 ** fts3ExprLoadDoclists().
   142576 */
   142577 static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
   142578   int rc = SQLITE_OK;
   142579   Fts3Phrase *pPhrase = pExpr->pPhrase;
   142580   LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
   142581 
   142582   UNUSED_PARAMETER(iPhrase);
   142583 
   142584   p->nPhrase++;
   142585   p->nToken += pPhrase->nToken;
   142586 
   142587   return rc;
   142588 }
   142589 
   142590 /*
   142591 ** Load the doclists for each phrase in the query associated with FTS3 cursor
   142592 ** pCsr.
   142593 **
   142594 ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
   142595 ** phrases in the expression (all phrases except those directly or
   142596 ** indirectly descended from the right-hand-side of a NOT operator). If
   142597 ** pnToken is not NULL, then it is set to the number of tokens in all
   142598 ** matchable phrases of the expression.
   142599 */
   142600 static int fts3ExprLoadDoclists(
   142601   Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
   142602   int *pnPhrase,                  /* OUT: Number of phrases in query */
   142603   int *pnToken                    /* OUT: Number of tokens in query */
   142604 ){
   142605   int rc;                         /* Return Code */
   142606   LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
   142607   sCtx.pCsr = pCsr;
   142608   rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
   142609   if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
   142610   if( pnToken ) *pnToken = sCtx.nToken;
   142611   return rc;
   142612 }
   142613 
   142614 static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
   142615   (*(int *)ctx)++;
   142616   UNUSED_PARAMETER(pExpr);
   142617   UNUSED_PARAMETER(iPhrase);
   142618   return SQLITE_OK;
   142619 }
   142620 static int fts3ExprPhraseCount(Fts3Expr *pExpr){
   142621   int nPhrase = 0;
   142622   (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
   142623   return nPhrase;
   142624 }
   142625 
   142626 /*
   142627 ** Advance the position list iterator specified by the first two
   142628 ** arguments so that it points to the first element with a value greater
   142629 ** than or equal to parameter iNext.
   142630 */
   142631 static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
   142632   char *pIter = *ppIter;
   142633   if( pIter ){
   142634     int iIter = *piIter;
   142635 
   142636     while( iIter<iNext ){
   142637       if( 0==(*pIter & 0xFE) ){
   142638         iIter = -1;
   142639         pIter = 0;
   142640         break;
   142641       }
   142642       fts3GetDeltaPosition(&pIter, &iIter);
   142643     }
   142644 
   142645     *piIter = iIter;
   142646     *ppIter = pIter;
   142647   }
   142648 }
   142649 
   142650 /*
   142651 ** Advance the snippet iterator to the next candidate snippet.
   142652 */
   142653 static int fts3SnippetNextCandidate(SnippetIter *pIter){
   142654   int i;                          /* Loop counter */
   142655 
   142656   if( pIter->iCurrent<0 ){
   142657     /* The SnippetIter object has just been initialized. The first snippet
   142658     ** candidate always starts at offset 0 (even if this candidate has a
   142659     ** score of 0.0).
   142660     */
   142661     pIter->iCurrent = 0;
   142662 
   142663     /* Advance the 'head' iterator of each phrase to the first offset that
   142664     ** is greater than or equal to (iNext+nSnippet).
   142665     */
   142666     for(i=0; i<pIter->nPhrase; i++){
   142667       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
   142668       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
   142669     }
   142670   }else{
   142671     int iStart;
   142672     int iEnd = 0x7FFFFFFF;
   142673 
   142674     for(i=0; i<pIter->nPhrase; i++){
   142675       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
   142676       if( pPhrase->pHead && pPhrase->iHead<iEnd ){
   142677         iEnd = pPhrase->iHead;
   142678       }
   142679     }
   142680     if( iEnd==0x7FFFFFFF ){
   142681       return 1;
   142682     }
   142683 
   142684     pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
   142685     for(i=0; i<pIter->nPhrase; i++){
   142686       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
   142687       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
   142688       fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
   142689     }
   142690   }
   142691 
   142692   return 0;
   142693 }
   142694 
   142695 /*
   142696 ** Retrieve information about the current candidate snippet of snippet
   142697 ** iterator pIter.
   142698 */
   142699 static void fts3SnippetDetails(
   142700   SnippetIter *pIter,             /* Snippet iterator */
   142701   u64 mCovered,                   /* Bitmask of phrases already covered */
   142702   int *piToken,                   /* OUT: First token of proposed snippet */
   142703   int *piScore,                   /* OUT: "Score" for this snippet */
   142704   u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
   142705   u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
   142706 ){
   142707   int iStart = pIter->iCurrent;   /* First token of snippet */
   142708   int iScore = 0;                 /* Score of this snippet */
   142709   int i;                          /* Loop counter */
   142710   u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
   142711   u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
   142712 
   142713   for(i=0; i<pIter->nPhrase; i++){
   142714     SnippetPhrase *pPhrase = &pIter->aPhrase[i];
   142715     if( pPhrase->pTail ){
   142716       char *pCsr = pPhrase->pTail;
   142717       int iCsr = pPhrase->iTail;
   142718 
   142719       while( iCsr<(iStart+pIter->nSnippet) ){
   142720         int j;
   142721         u64 mPhrase = (u64)1 << i;
   142722         u64 mPos = (u64)1 << (iCsr - iStart);
   142723         assert( iCsr>=iStart );
   142724         if( (mCover|mCovered)&mPhrase ){
   142725           iScore++;
   142726         }else{
   142727           iScore += 1000;
   142728         }
   142729         mCover |= mPhrase;
   142730 
   142731         for(j=0; j<pPhrase->nToken; j++){
   142732           mHighlight |= (mPos>>j);
   142733         }
   142734 
   142735         if( 0==(*pCsr & 0x0FE) ) break;
   142736         fts3GetDeltaPosition(&pCsr, &iCsr);
   142737       }
   142738     }
   142739   }
   142740 
   142741   /* Set the output variables before returning. */
   142742   *piToken = iStart;
   142743   *piScore = iScore;
   142744   *pmCover = mCover;
   142745   *pmHighlight = mHighlight;
   142746 }
   142747 
   142748 /*
   142749 ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
   142750 ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
   142751 */
   142752 static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
   142753   SnippetIter *p = (SnippetIter *)ctx;
   142754   SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
   142755   char *pCsr;
   142756   int rc;
   142757 
   142758   pPhrase->nToken = pExpr->pPhrase->nToken;
   142759   rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
   142760   assert( rc==SQLITE_OK || pCsr==0 );
   142761   if( pCsr ){
   142762     int iFirst = 0;
   142763     pPhrase->pList = pCsr;
   142764     fts3GetDeltaPosition(&pCsr, &iFirst);
   142765     assert( iFirst>=0 );
   142766     pPhrase->pHead = pCsr;
   142767     pPhrase->pTail = pCsr;
   142768     pPhrase->iHead = iFirst;
   142769     pPhrase->iTail = iFirst;
   142770   }else{
   142771     assert( rc!=SQLITE_OK || (
   142772        pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
   142773     ));
   142774   }
   142775 
   142776   return rc;
   142777 }
   142778 
   142779 /*
   142780 ** Select the fragment of text consisting of nFragment contiguous tokens
   142781 ** from column iCol that represent the "best" snippet. The best snippet
   142782 ** is the snippet with the highest score, where scores are calculated
   142783 ** by adding:
   142784 **
   142785 **   (a) +1 point for each occurrence of a matchable phrase in the snippet.
   142786 **
   142787 **   (b) +1000 points for the first occurrence of each matchable phrase in
   142788 **       the snippet for which the corresponding mCovered bit is not set.
   142789 **
   142790 ** The selected snippet parameters are stored in structure *pFragment before
   142791 ** returning. The score of the selected snippet is stored in *piScore
   142792 ** before returning.
   142793 */
   142794 static int fts3BestSnippet(
   142795   int nSnippet,                   /* Desired snippet length */
   142796   Fts3Cursor *pCsr,               /* Cursor to create snippet for */
   142797   int iCol,                       /* Index of column to create snippet from */
   142798   u64 mCovered,                   /* Mask of phrases already covered */
   142799   u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
   142800   SnippetFragment *pFragment,     /* OUT: Best snippet found */
   142801   int *piScore                    /* OUT: Score of snippet pFragment */
   142802 ){
   142803   int rc;                         /* Return Code */
   142804   int nList;                      /* Number of phrases in expression */
   142805   SnippetIter sIter;              /* Iterates through snippet candidates */
   142806   int nByte;                      /* Number of bytes of space to allocate */
   142807   int iBestScore = -1;            /* Best snippet score found so far */
   142808   int i;                          /* Loop counter */
   142809 
   142810   memset(&sIter, 0, sizeof(sIter));
   142811 
   142812   /* Iterate through the phrases in the expression to count them. The same
   142813   ** callback makes sure the doclists are loaded for each phrase.
   142814   */
   142815   rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
   142816   if( rc!=SQLITE_OK ){
   142817     return rc;
   142818   }
   142819 
   142820   /* Now that it is known how many phrases there are, allocate and zero
   142821   ** the required space using malloc().
   142822   */
   142823   nByte = sizeof(SnippetPhrase) * nList;
   142824   sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
   142825   if( !sIter.aPhrase ){
   142826     return SQLITE_NOMEM;
   142827   }
   142828   memset(sIter.aPhrase, 0, nByte);
   142829 
   142830   /* Initialize the contents of the SnippetIter object. Then iterate through
   142831   ** the set of phrases in the expression to populate the aPhrase[] array.
   142832   */
   142833   sIter.pCsr = pCsr;
   142834   sIter.iCol = iCol;
   142835   sIter.nSnippet = nSnippet;
   142836   sIter.nPhrase = nList;
   142837   sIter.iCurrent = -1;
   142838   (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
   142839 
   142840   /* Set the *pmSeen output variable. */
   142841   for(i=0; i<nList; i++){
   142842     if( sIter.aPhrase[i].pHead ){
   142843       *pmSeen |= (u64)1 << i;
   142844     }
   142845   }
   142846 
   142847   /* Loop through all candidate snippets. Store the best snippet in
   142848   ** *pFragment. Store its associated 'score' in iBestScore.
   142849   */
   142850   pFragment->iCol = iCol;
   142851   while( !fts3SnippetNextCandidate(&sIter) ){
   142852     int iPos;
   142853     int iScore;
   142854     u64 mCover;
   142855     u64 mHighlight;
   142856     fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
   142857     assert( iScore>=0 );
   142858     if( iScore>iBestScore ){
   142859       pFragment->iPos = iPos;
   142860       pFragment->hlmask = mHighlight;
   142861       pFragment->covered = mCover;
   142862       iBestScore = iScore;
   142863     }
   142864   }
   142865 
   142866   sqlite3_free(sIter.aPhrase);
   142867   *piScore = iBestScore;
   142868   return SQLITE_OK;
   142869 }
   142870 
   142871 
   142872 /*
   142873 ** Append a string to the string-buffer passed as the first argument.
   142874 **
   142875 ** If nAppend is negative, then the length of the string zAppend is
   142876 ** determined using strlen().
   142877 */
   142878 static int fts3StringAppend(
   142879   StrBuffer *pStr,                /* Buffer to append to */
   142880   const char *zAppend,            /* Pointer to data to append to buffer */
   142881   int nAppend                     /* Size of zAppend in bytes (or -1) */
   142882 ){
   142883   if( nAppend<0 ){
   142884     nAppend = (int)strlen(zAppend);
   142885   }
   142886 
   142887   /* If there is insufficient space allocated at StrBuffer.z, use realloc()
   142888   ** to grow the buffer until so that it is big enough to accomadate the
   142889   ** appended data.
   142890   */
   142891   if( pStr->n+nAppend+1>=pStr->nAlloc ){
   142892     int nAlloc = pStr->nAlloc+nAppend+100;
   142893     char *zNew = sqlite3_realloc(pStr->z, nAlloc);
   142894     if( !zNew ){
   142895       return SQLITE_NOMEM;
   142896     }
   142897     pStr->z = zNew;
   142898     pStr->nAlloc = nAlloc;
   142899   }
   142900   assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
   142901 
   142902   /* Append the data to the string buffer. */
   142903   memcpy(&pStr->z[pStr->n], zAppend, nAppend);
   142904   pStr->n += nAppend;
   142905   pStr->z[pStr->n] = '\0';
   142906 
   142907   return SQLITE_OK;
   142908 }
   142909 
   142910 /*
   142911 ** The fts3BestSnippet() function often selects snippets that end with a
   142912 ** query term. That is, the final term of the snippet is always a term
   142913 ** that requires highlighting. For example, if 'X' is a highlighted term
   142914 ** and '.' is a non-highlighted term, BestSnippet() may select:
   142915 **
   142916 **     ........X.....X
   142917 **
   142918 ** This function "shifts" the beginning of the snippet forward in the
   142919 ** document so that there are approximately the same number of
   142920 ** non-highlighted terms to the right of the final highlighted term as there
   142921 ** are to the left of the first highlighted term. For example, to this:
   142922 **
   142923 **     ....X.....X....
   142924 **
   142925 ** This is done as part of extracting the snippet text, not when selecting
   142926 ** the snippet. Snippet selection is done based on doclists only, so there
   142927 ** is no way for fts3BestSnippet() to know whether or not the document
   142928 ** actually contains terms that follow the final highlighted term.
   142929 */
   142930 static int fts3SnippetShift(
   142931   Fts3Table *pTab,                /* FTS3 table snippet comes from */
   142932   int iLangid,                    /* Language id to use in tokenizing */
   142933   int nSnippet,                   /* Number of tokens desired for snippet */
   142934   const char *zDoc,               /* Document text to extract snippet from */
   142935   int nDoc,                       /* Size of buffer zDoc in bytes */
   142936   int *piPos,                     /* IN/OUT: First token of snippet */
   142937   u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
   142938 ){
   142939   u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
   142940 
   142941   if( hlmask ){
   142942     int nLeft;                    /* Tokens to the left of first highlight */
   142943     int nRight;                   /* Tokens to the right of last highlight */
   142944     int nDesired;                 /* Ideal number of tokens to shift forward */
   142945 
   142946     for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
   142947     for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
   142948     nDesired = (nLeft-nRight)/2;
   142949 
   142950     /* Ideally, the start of the snippet should be pushed forward in the
   142951     ** document nDesired tokens. This block checks if there are actually
   142952     ** nDesired tokens to the right of the snippet. If so, *piPos and
   142953     ** *pHlMask are updated to shift the snippet nDesired tokens to the
   142954     ** right. Otherwise, the snippet is shifted by the number of tokens
   142955     ** available.
   142956     */
   142957     if( nDesired>0 ){
   142958       int nShift;                 /* Number of tokens to shift snippet by */
   142959       int iCurrent = 0;           /* Token counter */
   142960       int rc;                     /* Return Code */
   142961       sqlite3_tokenizer_module *pMod;
   142962       sqlite3_tokenizer_cursor *pC;
   142963       pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
   142964 
   142965       /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
   142966       ** or more tokens in zDoc/nDoc.
   142967       */
   142968       rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
   142969       if( rc!=SQLITE_OK ){
   142970         return rc;
   142971       }
   142972       while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
   142973         const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
   142974         rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
   142975       }
   142976       pMod->xClose(pC);
   142977       if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
   142978 
   142979       nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
   142980       assert( nShift<=nDesired );
   142981       if( nShift>0 ){
   142982         *piPos += nShift;
   142983         *pHlmask = hlmask >> nShift;
   142984       }
   142985     }
   142986   }
   142987   return SQLITE_OK;
   142988 }
   142989 
   142990 /*
   142991 ** Extract the snippet text for fragment pFragment from cursor pCsr and
   142992 ** append it to string buffer pOut.
   142993 */
   142994 static int fts3SnippetText(
   142995   Fts3Cursor *pCsr,               /* FTS3 Cursor */
   142996   SnippetFragment *pFragment,     /* Snippet to extract */
   142997   int iFragment,                  /* Fragment number */
   142998   int isLast,                     /* True for final fragment in snippet */
   142999   int nSnippet,                   /* Number of tokens in extracted snippet */
   143000   const char *zOpen,              /* String inserted before highlighted term */
   143001   const char *zClose,             /* String inserted after highlighted term */
   143002   const char *zEllipsis,          /* String inserted between snippets */
   143003   StrBuffer *pOut                 /* Write output here */
   143004 ){
   143005   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   143006   int rc;                         /* Return code */
   143007   const char *zDoc;               /* Document text to extract snippet from */
   143008   int nDoc;                       /* Size of zDoc in bytes */
   143009   int iCurrent = 0;               /* Current token number of document */
   143010   int iEnd = 0;                   /* Byte offset of end of current token */
   143011   int isShiftDone = 0;            /* True after snippet is shifted */
   143012   int iPos = pFragment->iPos;     /* First token of snippet */
   143013   u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
   143014   int iCol = pFragment->iCol+1;   /* Query column to extract text from */
   143015   sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
   143016   sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
   143017 
   143018   zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
   143019   if( zDoc==0 ){
   143020     if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
   143021       return SQLITE_NOMEM;
   143022     }
   143023     return SQLITE_OK;
   143024   }
   143025   nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
   143026 
   143027   /* Open a token cursor on the document. */
   143028   pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
   143029   rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
   143030   if( rc!=SQLITE_OK ){
   143031     return rc;
   143032   }
   143033 
   143034   while( rc==SQLITE_OK ){
   143035     const char *ZDUMMY;           /* Dummy argument used with tokenizer */
   143036     int DUMMY1 = -1;              /* Dummy argument used with tokenizer */
   143037     int iBegin = 0;               /* Offset in zDoc of start of token */
   143038     int iFin = 0;                 /* Offset in zDoc of end of token */
   143039     int isHighlight = 0;          /* True for highlighted terms */
   143040 
   143041     /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
   143042     ** in the FTS code the variable that the third argument to xNext points to
   143043     ** is initialized to zero before the first (*but not necessarily
   143044     ** subsequent*) call to xNext(). This is done for a particular application
   143045     ** that needs to know whether or not the tokenizer is being used for
   143046     ** snippet generation or for some other purpose.
   143047     **
   143048     ** Extreme care is required when writing code to depend on this
   143049     ** initialization. It is not a documented part of the tokenizer interface.
   143050     ** If a tokenizer is used directly by any code outside of FTS, this
   143051     ** convention might not be respected.  */
   143052     rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
   143053     if( rc!=SQLITE_OK ){
   143054       if( rc==SQLITE_DONE ){
   143055         /* Special case - the last token of the snippet is also the last token
   143056         ** of the column. Append any punctuation that occurred between the end
   143057         ** of the previous token and the end of the document to the output.
   143058         ** Then break out of the loop. */
   143059         rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
   143060       }
   143061       break;
   143062     }
   143063     if( iCurrent<iPos ){ continue; }
   143064 
   143065     if( !isShiftDone ){
   143066       int n = nDoc - iBegin;
   143067       rc = fts3SnippetShift(
   143068           pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
   143069       );
   143070       isShiftDone = 1;
   143071 
   143072       /* Now that the shift has been done, check if the initial "..." are
   143073       ** required. They are required if (a) this is not the first fragment,
   143074       ** or (b) this fragment does not begin at position 0 of its column.
   143075       */
   143076       if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
   143077         rc = fts3StringAppend(pOut, zEllipsis, -1);
   143078       }
   143079       if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
   143080     }
   143081 
   143082     if( iCurrent>=(iPos+nSnippet) ){
   143083       if( isLast ){
   143084         rc = fts3StringAppend(pOut, zEllipsis, -1);
   143085       }
   143086       break;
   143087     }
   143088 
   143089     /* Set isHighlight to true if this term should be highlighted. */
   143090     isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
   143091 
   143092     if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
   143093     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
   143094     if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
   143095     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
   143096 
   143097     iEnd = iFin;
   143098   }
   143099 
   143100   pMod->xClose(pC);
   143101   return rc;
   143102 }
   143103 
   143104 
   143105 /*
   143106 ** This function is used to count the entries in a column-list (a
   143107 ** delta-encoded list of term offsets within a single column of a single
   143108 ** row). When this function is called, *ppCollist should point to the
   143109 ** beginning of the first varint in the column-list (the varint that
   143110 ** contains the position of the first matching term in the column data).
   143111 ** Before returning, *ppCollist is set to point to the first byte after
   143112 ** the last varint in the column-list (either the 0x00 signifying the end
   143113 ** of the position-list, or the 0x01 that precedes the column number of
   143114 ** the next column in the position-list).
   143115 **
   143116 ** The number of elements in the column-list is returned.
   143117 */
   143118 static int fts3ColumnlistCount(char **ppCollist){
   143119   char *pEnd = *ppCollist;
   143120   char c = 0;
   143121   int nEntry = 0;
   143122 
   143123   /* A column-list is terminated by either a 0x01 or 0x00. */
   143124   while( 0xFE & (*pEnd | c) ){
   143125     c = *pEnd++ & 0x80;
   143126     if( !c ) nEntry++;
   143127   }
   143128 
   143129   *ppCollist = pEnd;
   143130   return nEntry;
   143131 }
   143132 
   143133 /*
   143134 ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
   143135 ** for a single query.
   143136 **
   143137 ** fts3ExprIterate() callback to load the 'global' elements of a
   143138 ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
   143139 ** of the matchinfo array that are constant for all rows returned by the
   143140 ** current query.
   143141 **
   143142 ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
   143143 ** function populates Matchinfo.aMatchinfo[] as follows:
   143144 **
   143145 **   for(iCol=0; iCol<nCol; iCol++){
   143146 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
   143147 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
   143148 **   }
   143149 **
   143150 ** where X is the number of matches for phrase iPhrase is column iCol of all
   143151 ** rows of the table. Y is the number of rows for which column iCol contains
   143152 ** at least one instance of phrase iPhrase.
   143153 **
   143154 ** If the phrase pExpr consists entirely of deferred tokens, then all X and
   143155 ** Y values are set to nDoc, where nDoc is the number of documents in the
   143156 ** file system. This is done because the full-text index doclist is required
   143157 ** to calculate these values properly, and the full-text index doclist is
   143158 ** not available for deferred tokens.
   143159 */
   143160 static int fts3ExprGlobalHitsCb(
   143161   Fts3Expr *pExpr,                /* Phrase expression node */
   143162   int iPhrase,                    /* Phrase number (numbered from zero) */
   143163   void *pCtx                      /* Pointer to MatchInfo structure */
   143164 ){
   143165   MatchInfo *p = (MatchInfo *)pCtx;
   143166   return sqlite3Fts3EvalPhraseStats(
   143167       p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
   143168   );
   143169 }
   143170 
   143171 /*
   143172 ** fts3ExprIterate() callback used to collect the "local" part of the
   143173 ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
   143174 ** array that are different for each row returned by the query.
   143175 */
   143176 static int fts3ExprLocalHitsCb(
   143177   Fts3Expr *pExpr,                /* Phrase expression node */
   143178   int iPhrase,                    /* Phrase number */
   143179   void *pCtx                      /* Pointer to MatchInfo structure */
   143180 ){
   143181   int rc = SQLITE_OK;
   143182   MatchInfo *p = (MatchInfo *)pCtx;
   143183   int iStart = iPhrase * p->nCol * 3;
   143184   int i;
   143185 
   143186   for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
   143187     char *pCsr;
   143188     rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
   143189     if( pCsr ){
   143190       p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
   143191     }else{
   143192       p->aMatchinfo[iStart+i*3] = 0;
   143193     }
   143194   }
   143195 
   143196   return rc;
   143197 }
   143198 
   143199 static int fts3MatchinfoCheck(
   143200   Fts3Table *pTab,
   143201   char cArg,
   143202   char **pzErr
   143203 ){
   143204   if( (cArg==FTS3_MATCHINFO_NPHRASE)
   143205    || (cArg==FTS3_MATCHINFO_NCOL)
   143206    || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
   143207    || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
   143208    || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
   143209    || (cArg==FTS3_MATCHINFO_LCS)
   143210    || (cArg==FTS3_MATCHINFO_HITS)
   143211   ){
   143212     return SQLITE_OK;
   143213   }
   143214   *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg);
   143215   return SQLITE_ERROR;
   143216 }
   143217 
   143218 static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
   143219   int nVal;                       /* Number of integers output by cArg */
   143220 
   143221   switch( cArg ){
   143222     case FTS3_MATCHINFO_NDOC:
   143223     case FTS3_MATCHINFO_NPHRASE:
   143224     case FTS3_MATCHINFO_NCOL:
   143225       nVal = 1;
   143226       break;
   143227 
   143228     case FTS3_MATCHINFO_AVGLENGTH:
   143229     case FTS3_MATCHINFO_LENGTH:
   143230     case FTS3_MATCHINFO_LCS:
   143231       nVal = pInfo->nCol;
   143232       break;
   143233 
   143234     default:
   143235       assert( cArg==FTS3_MATCHINFO_HITS );
   143236       nVal = pInfo->nCol * pInfo->nPhrase * 3;
   143237       break;
   143238   }
   143239 
   143240   return nVal;
   143241 }
   143242 
   143243 static int fts3MatchinfoSelectDoctotal(
   143244   Fts3Table *pTab,
   143245   sqlite3_stmt **ppStmt,
   143246   sqlite3_int64 *pnDoc,
   143247   const char **paLen
   143248 ){
   143249   sqlite3_stmt *pStmt;
   143250   const char *a;
   143251   sqlite3_int64 nDoc;
   143252 
   143253   if( !*ppStmt ){
   143254     int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
   143255     if( rc!=SQLITE_OK ) return rc;
   143256   }
   143257   pStmt = *ppStmt;
   143258   assert( sqlite3_data_count(pStmt)==1 );
   143259 
   143260   a = sqlite3_column_blob(pStmt, 0);
   143261   a += sqlite3Fts3GetVarint(a, &nDoc);
   143262   if( nDoc==0 ) return FTS_CORRUPT_VTAB;
   143263   *pnDoc = (u32)nDoc;
   143264 
   143265   if( paLen ) *paLen = a;
   143266   return SQLITE_OK;
   143267 }
   143268 
   143269 /*
   143270 ** An instance of the following structure is used to store state while
   143271 ** iterating through a multi-column position-list corresponding to the
   143272 ** hits for a single phrase on a single row in order to calculate the
   143273 ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
   143274 */
   143275 typedef struct LcsIterator LcsIterator;
   143276 struct LcsIterator {
   143277   Fts3Expr *pExpr;                /* Pointer to phrase expression */
   143278   int iPosOffset;                 /* Tokens count up to end of this phrase */
   143279   char *pRead;                    /* Cursor used to iterate through aDoclist */
   143280   int iPos;                       /* Current position */
   143281 };
   143282 
   143283 /*
   143284 ** If LcsIterator.iCol is set to the following value, the iterator has
   143285 ** finished iterating through all offsets for all columns.
   143286 */
   143287 #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
   143288 
   143289 static int fts3MatchinfoLcsCb(
   143290   Fts3Expr *pExpr,                /* Phrase expression node */
   143291   int iPhrase,                    /* Phrase number (numbered from zero) */
   143292   void *pCtx                      /* Pointer to MatchInfo structure */
   143293 ){
   143294   LcsIterator *aIter = (LcsIterator *)pCtx;
   143295   aIter[iPhrase].pExpr = pExpr;
   143296   return SQLITE_OK;
   143297 }
   143298 
   143299 /*
   143300 ** Advance the iterator passed as an argument to the next position. Return
   143301 ** 1 if the iterator is at EOF or if it now points to the start of the
   143302 ** position list for the next column.
   143303 */
   143304 static int fts3LcsIteratorAdvance(LcsIterator *pIter){
   143305   char *pRead = pIter->pRead;
   143306   sqlite3_int64 iRead;
   143307   int rc = 0;
   143308 
   143309   pRead += sqlite3Fts3GetVarint(pRead, &iRead);
   143310   if( iRead==0 || iRead==1 ){
   143311     pRead = 0;
   143312     rc = 1;
   143313   }else{
   143314     pIter->iPos += (int)(iRead-2);
   143315   }
   143316 
   143317   pIter->pRead = pRead;
   143318   return rc;
   143319 }
   143320 
   143321 /*
   143322 ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
   143323 **
   143324 ** If the call is successful, the longest-common-substring lengths for each
   143325 ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
   143326 ** array before returning. SQLITE_OK is returned in this case.
   143327 **
   143328 ** Otherwise, if an error occurs, an SQLite error code is returned and the
   143329 ** data written to the first nCol elements of pInfo->aMatchinfo[] is
   143330 ** undefined.
   143331 */
   143332 static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
   143333   LcsIterator *aIter;
   143334   int i;
   143335   int iCol;
   143336   int nToken = 0;
   143337 
   143338   /* Allocate and populate the array of LcsIterator objects. The array
   143339   ** contains one element for each matchable phrase in the query.
   143340   **/
   143341   aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
   143342   if( !aIter ) return SQLITE_NOMEM;
   143343   memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
   143344   (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
   143345 
   143346   for(i=0; i<pInfo->nPhrase; i++){
   143347     LcsIterator *pIter = &aIter[i];
   143348     nToken -= pIter->pExpr->pPhrase->nToken;
   143349     pIter->iPosOffset = nToken;
   143350   }
   143351 
   143352   for(iCol=0; iCol<pInfo->nCol; iCol++){
   143353     int nLcs = 0;                 /* LCS value for this column */
   143354     int nLive = 0;                /* Number of iterators in aIter not at EOF */
   143355 
   143356     for(i=0; i<pInfo->nPhrase; i++){
   143357       int rc;
   143358       LcsIterator *pIt = &aIter[i];
   143359       rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
   143360       if( rc!=SQLITE_OK ) return rc;
   143361       if( pIt->pRead ){
   143362         pIt->iPos = pIt->iPosOffset;
   143363         fts3LcsIteratorAdvance(&aIter[i]);
   143364         nLive++;
   143365       }
   143366     }
   143367 
   143368     while( nLive>0 ){
   143369       LcsIterator *pAdv = 0;      /* The iterator to advance by one position */
   143370       int nThisLcs = 0;           /* LCS for the current iterator positions */
   143371 
   143372       for(i=0; i<pInfo->nPhrase; i++){
   143373         LcsIterator *pIter = &aIter[i];
   143374         if( pIter->pRead==0 ){
   143375           /* This iterator is already at EOF for this column. */
   143376           nThisLcs = 0;
   143377         }else{
   143378           if( pAdv==0 || pIter->iPos<pAdv->iPos ){
   143379             pAdv = pIter;
   143380           }
   143381           if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
   143382             nThisLcs++;
   143383           }else{
   143384             nThisLcs = 1;
   143385           }
   143386           if( nThisLcs>nLcs ) nLcs = nThisLcs;
   143387         }
   143388       }
   143389       if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
   143390     }
   143391 
   143392     pInfo->aMatchinfo[iCol] = nLcs;
   143393   }
   143394 
   143395   sqlite3_free(aIter);
   143396   return SQLITE_OK;
   143397 }
   143398 
   143399 /*
   143400 ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
   143401 ** be returned by the matchinfo() function. Argument zArg contains the
   143402 ** format string passed as the second argument to matchinfo (or the
   143403 ** default value "pcx" if no second argument was specified). The format
   143404 ** string has already been validated and the pInfo->aMatchinfo[] array
   143405 ** is guaranteed to be large enough for the output.
   143406 **
   143407 ** If bGlobal is true, then populate all fields of the matchinfo() output.
   143408 ** If it is false, then assume that those fields that do not change between
   143409 ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
   143410 ** have already been populated.
   143411 **
   143412 ** Return SQLITE_OK if successful, or an SQLite error code if an error
   143413 ** occurs. If a value other than SQLITE_OK is returned, the state the
   143414 ** pInfo->aMatchinfo[] buffer is left in is undefined.
   143415 */
   143416 static int fts3MatchinfoValues(
   143417   Fts3Cursor *pCsr,               /* FTS3 cursor object */
   143418   int bGlobal,                    /* True to grab the global stats */
   143419   MatchInfo *pInfo,               /* Matchinfo context object */
   143420   const char *zArg                /* Matchinfo format string */
   143421 ){
   143422   int rc = SQLITE_OK;
   143423   int i;
   143424   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   143425   sqlite3_stmt *pSelect = 0;
   143426 
   143427   for(i=0; rc==SQLITE_OK && zArg[i]; i++){
   143428 
   143429     switch( zArg[i] ){
   143430       case FTS3_MATCHINFO_NPHRASE:
   143431         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
   143432         break;
   143433 
   143434       case FTS3_MATCHINFO_NCOL:
   143435         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
   143436         break;
   143437 
   143438       case FTS3_MATCHINFO_NDOC:
   143439         if( bGlobal ){
   143440           sqlite3_int64 nDoc = 0;
   143441           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
   143442           pInfo->aMatchinfo[0] = (u32)nDoc;
   143443         }
   143444         break;
   143445 
   143446       case FTS3_MATCHINFO_AVGLENGTH:
   143447         if( bGlobal ){
   143448           sqlite3_int64 nDoc;     /* Number of rows in table */
   143449           const char *a;          /* Aggregate column length array */
   143450 
   143451           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
   143452           if( rc==SQLITE_OK ){
   143453             int iCol;
   143454             for(iCol=0; iCol<pInfo->nCol; iCol++){
   143455               u32 iVal;
   143456               sqlite3_int64 nToken;
   143457               a += sqlite3Fts3GetVarint(a, &nToken);
   143458               iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
   143459               pInfo->aMatchinfo[iCol] = iVal;
   143460             }
   143461           }
   143462         }
   143463         break;
   143464 
   143465       case FTS3_MATCHINFO_LENGTH: {
   143466         sqlite3_stmt *pSelectDocsize = 0;
   143467         rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
   143468         if( rc==SQLITE_OK ){
   143469           int iCol;
   143470           const char *a = sqlite3_column_blob(pSelectDocsize, 0);
   143471           for(iCol=0; iCol<pInfo->nCol; iCol++){
   143472             sqlite3_int64 nToken;
   143473             a += sqlite3Fts3GetVarint(a, &nToken);
   143474             pInfo->aMatchinfo[iCol] = (u32)nToken;
   143475           }
   143476         }
   143477         sqlite3_reset(pSelectDocsize);
   143478         break;
   143479       }
   143480 
   143481       case FTS3_MATCHINFO_LCS:
   143482         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
   143483         if( rc==SQLITE_OK ){
   143484           rc = fts3MatchinfoLcs(pCsr, pInfo);
   143485         }
   143486         break;
   143487 
   143488       default: {
   143489         Fts3Expr *pExpr;
   143490         assert( zArg[i]==FTS3_MATCHINFO_HITS );
   143491         pExpr = pCsr->pExpr;
   143492         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
   143493         if( rc!=SQLITE_OK ) break;
   143494         if( bGlobal ){
   143495           if( pCsr->pDeferred ){
   143496             rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
   143497             if( rc!=SQLITE_OK ) break;
   143498           }
   143499           rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
   143500           if( rc!=SQLITE_OK ) break;
   143501         }
   143502         (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
   143503         break;
   143504       }
   143505     }
   143506 
   143507     pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
   143508   }
   143509 
   143510   sqlite3_reset(pSelect);
   143511   return rc;
   143512 }
   143513 
   143514 
   143515 /*
   143516 ** Populate pCsr->aMatchinfo[] with data for the current row. The
   143517 ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
   143518 */
   143519 static int fts3GetMatchinfo(
   143520   Fts3Cursor *pCsr,               /* FTS3 Cursor object */
   143521   const char *zArg                /* Second argument to matchinfo() function */
   143522 ){
   143523   MatchInfo sInfo;
   143524   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   143525   int rc = SQLITE_OK;
   143526   int bGlobal = 0;                /* Collect 'global' stats as well as local */
   143527 
   143528   memset(&sInfo, 0, sizeof(MatchInfo));
   143529   sInfo.pCursor = pCsr;
   143530   sInfo.nCol = pTab->nColumn;
   143531 
   143532   /* If there is cached matchinfo() data, but the format string for the
   143533   ** cache does not match the format string for this request, discard
   143534   ** the cached data. */
   143535   if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
   143536     assert( pCsr->aMatchinfo );
   143537     sqlite3_free(pCsr->aMatchinfo);
   143538     pCsr->zMatchinfo = 0;
   143539     pCsr->aMatchinfo = 0;
   143540   }
   143541 
   143542   /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
   143543   ** matchinfo function has been called for this query. In this case
   143544   ** allocate the array used to accumulate the matchinfo data and
   143545   ** initialize those elements that are constant for every row.
   143546   */
   143547   if( pCsr->aMatchinfo==0 ){
   143548     int nMatchinfo = 0;           /* Number of u32 elements in match-info */
   143549     int nArg;                     /* Bytes in zArg */
   143550     int i;                        /* Used to iterate through zArg */
   143551 
   143552     /* Determine the number of phrases in the query */
   143553     pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
   143554     sInfo.nPhrase = pCsr->nPhrase;
   143555 
   143556     /* Determine the number of integers in the buffer returned by this call. */
   143557     for(i=0; zArg[i]; i++){
   143558       nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
   143559     }
   143560 
   143561     /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
   143562     nArg = (int)strlen(zArg);
   143563     pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
   143564     if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
   143565 
   143566     pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
   143567     pCsr->nMatchinfo = nMatchinfo;
   143568     memcpy(pCsr->zMatchinfo, zArg, nArg+1);
   143569     memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
   143570     pCsr->isMatchinfoNeeded = 1;
   143571     bGlobal = 1;
   143572   }
   143573 
   143574   sInfo.aMatchinfo = pCsr->aMatchinfo;
   143575   sInfo.nPhrase = pCsr->nPhrase;
   143576   if( pCsr->isMatchinfoNeeded ){
   143577     rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
   143578     pCsr->isMatchinfoNeeded = 0;
   143579   }
   143580 
   143581   return rc;
   143582 }
   143583 
   143584 /*
   143585 ** Implementation of snippet() function.
   143586 */
   143587 SQLITE_PRIVATE void sqlite3Fts3Snippet(
   143588   sqlite3_context *pCtx,          /* SQLite function call context */
   143589   Fts3Cursor *pCsr,               /* Cursor object */
   143590   const char *zStart,             /* Snippet start text - "<b>" */
   143591   const char *zEnd,               /* Snippet end text - "</b>" */
   143592   const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
   143593   int iCol,                       /* Extract snippet from this column */
   143594   int nToken                      /* Approximate number of tokens in snippet */
   143595 ){
   143596   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   143597   int rc = SQLITE_OK;
   143598   int i;
   143599   StrBuffer res = {0, 0, 0};
   143600 
   143601   /* The returned text includes up to four fragments of text extracted from
   143602   ** the data in the current row. The first iteration of the for(...) loop
   143603   ** below attempts to locate a single fragment of text nToken tokens in
   143604   ** size that contains at least one instance of all phrases in the query
   143605   ** expression that appear in the current row. If such a fragment of text
   143606   ** cannot be found, the second iteration of the loop attempts to locate
   143607   ** a pair of fragments, and so on.
   143608   */
   143609   int nSnippet = 0;               /* Number of fragments in this snippet */
   143610   SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
   143611   int nFToken = -1;               /* Number of tokens in each fragment */
   143612 
   143613   if( !pCsr->pExpr ){
   143614     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
   143615     return;
   143616   }
   143617 
   143618   for(nSnippet=1; 1; nSnippet++){
   143619 
   143620     int iSnip;                    /* Loop counter 0..nSnippet-1 */
   143621     u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
   143622     u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
   143623 
   143624     if( nToken>=0 ){
   143625       nFToken = (nToken+nSnippet-1) / nSnippet;
   143626     }else{
   143627       nFToken = -1 * nToken;
   143628     }
   143629 
   143630     for(iSnip=0; iSnip<nSnippet; iSnip++){
   143631       int iBestScore = -1;        /* Best score of columns checked so far */
   143632       int iRead;                  /* Used to iterate through columns */
   143633       SnippetFragment *pFragment = &aSnippet[iSnip];
   143634 
   143635       memset(pFragment, 0, sizeof(*pFragment));
   143636 
   143637       /* Loop through all columns of the table being considered for snippets.
   143638       ** If the iCol argument to this function was negative, this means all
   143639       ** columns of the FTS3 table. Otherwise, only column iCol is considered.
   143640       */
   143641       for(iRead=0; iRead<pTab->nColumn; iRead++){
   143642         SnippetFragment sF = {0, 0, 0, 0};
   143643         int iS;
   143644         if( iCol>=0 && iRead!=iCol ) continue;
   143645 
   143646         /* Find the best snippet of nFToken tokens in column iRead. */
   143647         rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
   143648         if( rc!=SQLITE_OK ){
   143649           goto snippet_out;
   143650         }
   143651         if( iS>iBestScore ){
   143652           *pFragment = sF;
   143653           iBestScore = iS;
   143654         }
   143655       }
   143656 
   143657       mCovered |= pFragment->covered;
   143658     }
   143659 
   143660     /* If all query phrases seen by fts3BestSnippet() are present in at least
   143661     ** one of the nSnippet snippet fragments, break out of the loop.
   143662     */
   143663     assert( (mCovered&mSeen)==mCovered );
   143664     if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
   143665   }
   143666 
   143667   assert( nFToken>0 );
   143668 
   143669   for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
   143670     rc = fts3SnippetText(pCsr, &aSnippet[i],
   143671         i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
   143672     );
   143673   }
   143674 
   143675  snippet_out:
   143676   sqlite3Fts3SegmentsClose(pTab);
   143677   if( rc!=SQLITE_OK ){
   143678     sqlite3_result_error_code(pCtx, rc);
   143679     sqlite3_free(res.z);
   143680   }else{
   143681     sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
   143682   }
   143683 }
   143684 
   143685 
   143686 typedef struct TermOffset TermOffset;
   143687 typedef struct TermOffsetCtx TermOffsetCtx;
   143688 
   143689 struct TermOffset {
   143690   char *pList;                    /* Position-list */
   143691   int iPos;                       /* Position just read from pList */
   143692   int iOff;                       /* Offset of this term from read positions */
   143693 };
   143694 
   143695 struct TermOffsetCtx {
   143696   Fts3Cursor *pCsr;
   143697   int iCol;                       /* Column of table to populate aTerm for */
   143698   int iTerm;
   143699   sqlite3_int64 iDocid;
   143700   TermOffset *aTerm;
   143701 };
   143702 
   143703 /*
   143704 ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
   143705 */
   143706 static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
   143707   TermOffsetCtx *p = (TermOffsetCtx *)ctx;
   143708   int nTerm;                      /* Number of tokens in phrase */
   143709   int iTerm;                      /* For looping through nTerm phrase terms */
   143710   char *pList;                    /* Pointer to position list for phrase */
   143711   int iPos = 0;                   /* First position in position-list */
   143712   int rc;
   143713 
   143714   UNUSED_PARAMETER(iPhrase);
   143715   rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
   143716   nTerm = pExpr->pPhrase->nToken;
   143717   if( pList ){
   143718     fts3GetDeltaPosition(&pList, &iPos);
   143719     assert( iPos>=0 );
   143720   }
   143721 
   143722   for(iTerm=0; iTerm<nTerm; iTerm++){
   143723     TermOffset *pT = &p->aTerm[p->iTerm++];
   143724     pT->iOff = nTerm-iTerm-1;
   143725     pT->pList = pList;
   143726     pT->iPos = iPos;
   143727   }
   143728 
   143729   return rc;
   143730 }
   143731 
   143732 /*
   143733 ** Implementation of offsets() function.
   143734 */
   143735 SQLITE_PRIVATE void sqlite3Fts3Offsets(
   143736   sqlite3_context *pCtx,          /* SQLite function call context */
   143737   Fts3Cursor *pCsr                /* Cursor object */
   143738 ){
   143739   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   143740   sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
   143741   int rc;                         /* Return Code */
   143742   int nToken;                     /* Number of tokens in query */
   143743   int iCol;                       /* Column currently being processed */
   143744   StrBuffer res = {0, 0, 0};      /* Result string */
   143745   TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
   143746 
   143747   if( !pCsr->pExpr ){
   143748     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
   143749     return;
   143750   }
   143751 
   143752   memset(&sCtx, 0, sizeof(sCtx));
   143753   assert( pCsr->isRequireSeek==0 );
   143754 
   143755   /* Count the number of terms in the query */
   143756   rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
   143757   if( rc!=SQLITE_OK ) goto offsets_out;
   143758 
   143759   /* Allocate the array of TermOffset iterators. */
   143760   sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
   143761   if( 0==sCtx.aTerm ){
   143762     rc = SQLITE_NOMEM;
   143763     goto offsets_out;
   143764   }
   143765   sCtx.iDocid = pCsr->iPrevId;
   143766   sCtx.pCsr = pCsr;
   143767 
   143768   /* Loop through the table columns, appending offset information to
   143769   ** string-buffer res for each column.
   143770   */
   143771   for(iCol=0; iCol<pTab->nColumn; iCol++){
   143772     sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
   143773     const char *ZDUMMY;           /* Dummy argument used with xNext() */
   143774     int NDUMMY = 0;               /* Dummy argument used with xNext() */
   143775     int iStart = 0;
   143776     int iEnd = 0;
   143777     int iCurrent = 0;
   143778     const char *zDoc;
   143779     int nDoc;
   143780 
   143781     /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
   143782     ** no way that this operation can fail, so the return code from
   143783     ** fts3ExprIterate() can be discarded.
   143784     */
   143785     sCtx.iCol = iCol;
   143786     sCtx.iTerm = 0;
   143787     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
   143788 
   143789     /* Retreive the text stored in column iCol. If an SQL NULL is stored
   143790     ** in column iCol, jump immediately to the next iteration of the loop.
   143791     ** If an OOM occurs while retrieving the data (this can happen if SQLite
   143792     ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
   143793     ** to the caller.
   143794     */
   143795     zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
   143796     nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
   143797     if( zDoc==0 ){
   143798       if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
   143799         continue;
   143800       }
   143801       rc = SQLITE_NOMEM;
   143802       goto offsets_out;
   143803     }
   143804 
   143805     /* Initialize a tokenizer iterator to iterate through column iCol. */
   143806     rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
   143807         zDoc, nDoc, &pC
   143808     );
   143809     if( rc!=SQLITE_OK ) goto offsets_out;
   143810 
   143811     rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
   143812     while( rc==SQLITE_OK ){
   143813       int i;                      /* Used to loop through terms */
   143814       int iMinPos = 0x7FFFFFFF;   /* Position of next token */
   143815       TermOffset *pTerm = 0;      /* TermOffset associated with next token */
   143816 
   143817       for(i=0; i<nToken; i++){
   143818         TermOffset *pT = &sCtx.aTerm[i];
   143819         if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
   143820           iMinPos = pT->iPos-pT->iOff;
   143821           pTerm = pT;
   143822         }
   143823       }
   143824 
   143825       if( !pTerm ){
   143826         /* All offsets for this column have been gathered. */
   143827         rc = SQLITE_DONE;
   143828       }else{
   143829         assert( iCurrent<=iMinPos );
   143830         if( 0==(0xFE&*pTerm->pList) ){
   143831           pTerm->pList = 0;
   143832         }else{
   143833           fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
   143834         }
   143835         while( rc==SQLITE_OK && iCurrent<iMinPos ){
   143836           rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
   143837         }
   143838         if( rc==SQLITE_OK ){
   143839           char aBuffer[64];
   143840           sqlite3_snprintf(sizeof(aBuffer), aBuffer,
   143841               "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
   143842           );
   143843           rc = fts3StringAppend(&res, aBuffer, -1);
   143844         }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
   143845           rc = FTS_CORRUPT_VTAB;
   143846         }
   143847       }
   143848     }
   143849     if( rc==SQLITE_DONE ){
   143850       rc = SQLITE_OK;
   143851     }
   143852 
   143853     pMod->xClose(pC);
   143854     if( rc!=SQLITE_OK ) goto offsets_out;
   143855   }
   143856 
   143857  offsets_out:
   143858   sqlite3_free(sCtx.aTerm);
   143859   assert( rc!=SQLITE_DONE );
   143860   sqlite3Fts3SegmentsClose(pTab);
   143861   if( rc!=SQLITE_OK ){
   143862     sqlite3_result_error_code(pCtx,  rc);
   143863     sqlite3_free(res.z);
   143864   }else{
   143865     sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
   143866   }
   143867   return;
   143868 }
   143869 
   143870 /*
   143871 ** Implementation of matchinfo() function.
   143872 */
   143873 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
   143874   sqlite3_context *pContext,      /* Function call context */
   143875   Fts3Cursor *pCsr,               /* FTS3 table cursor */
   143876   const char *zArg                /* Second arg to matchinfo() function */
   143877 ){
   143878   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   143879   int rc;
   143880   int i;
   143881   const char *zFormat;
   143882 
   143883   if( zArg ){
   143884     for(i=0; zArg[i]; i++){
   143885       char *zErr = 0;
   143886       if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
   143887         sqlite3_result_error(pContext, zErr, -1);
   143888         sqlite3_free(zErr);
   143889         return;
   143890       }
   143891     }
   143892     zFormat = zArg;
   143893   }else{
   143894     zFormat = FTS3_MATCHINFO_DEFAULT;
   143895   }
   143896 
   143897   if( !pCsr->pExpr ){
   143898     sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
   143899     return;
   143900   }
   143901 
   143902   /* Retrieve matchinfo() data. */
   143903   rc = fts3GetMatchinfo(pCsr, zFormat);
   143904   sqlite3Fts3SegmentsClose(pTab);
   143905 
   143906   if( rc!=SQLITE_OK ){
   143907     sqlite3_result_error_code(pContext, rc);
   143908   }else{
   143909     int n = pCsr->nMatchinfo * sizeof(u32);
   143910     sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
   143911   }
   143912 }
   143913 
   143914 #endif
   143915 
   143916 /************** End of fts3_snippet.c ****************************************/
   143917 /************** Begin file fts3_unicode.c ************************************/
   143918 /*
   143919 ** 2012 May 24
   143920 **
   143921 ** The author disclaims copyright to this source code.  In place of
   143922 ** a legal notice, here is a blessing:
   143923 **
   143924 **    May you do good and not evil.
   143925 **    May you find forgiveness for yourself and forgive others.
   143926 **    May you share freely, never taking more than you give.
   143927 **
   143928 ******************************************************************************
   143929 **
   143930 ** Implementation of the "unicode" full-text-search tokenizer.
   143931 */
   143932 
   143933 #ifndef SQLITE_DISABLE_FTS3_UNICODE
   143934 
   143935 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   143936 
   143937 /* #include <assert.h> */
   143938 /* #include <stdlib.h> */
   143939 /* #include <stdio.h> */
   143940 /* #include <string.h> */
   143941 
   143942 
   143943 /*
   143944 ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
   143945 ** from the sqlite3 source file utf.c. If this file is compiled as part
   143946 ** of the amalgamation, they are not required.
   143947 */
   143948 #ifndef SQLITE_AMALGAMATION
   143949 
   143950 static const unsigned char sqlite3Utf8Trans1[] = {
   143951   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
   143952   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
   143953   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
   143954   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
   143955   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
   143956   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
   143957   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
   143958   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
   143959 };
   143960 
   143961 #define READ_UTF8(zIn, zTerm, c)                           \
   143962   c = *(zIn++);                                            \
   143963   if( c>=0xc0 ){                                           \
   143964     c = sqlite3Utf8Trans1[c-0xc0];                         \
   143965     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
   143966       c = (c<<6) + (0x3f & *(zIn++));                      \
   143967     }                                                      \
   143968     if( c<0x80                                             \
   143969         || (c&0xFFFFF800)==0xD800                          \
   143970         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
   143971   }
   143972 
   143973 #define WRITE_UTF8(zOut, c) {                          \
   143974   if( c<0x00080 ){                                     \
   143975     *zOut++ = (u8)(c&0xFF);                            \
   143976   }                                                    \
   143977   else if( c<0x00800 ){                                \
   143978     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
   143979     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
   143980   }                                                    \
   143981   else if( c<0x10000 ){                                \
   143982     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
   143983     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
   143984     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
   143985   }else{                                               \
   143986     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
   143987     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
   143988     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
   143989     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
   143990   }                                                    \
   143991 }
   143992 
   143993 #endif /* ifndef SQLITE_AMALGAMATION */
   143994 
   143995 typedef struct unicode_tokenizer unicode_tokenizer;
   143996 typedef struct unicode_cursor unicode_cursor;
   143997 
   143998 struct unicode_tokenizer {
   143999   sqlite3_tokenizer base;
   144000   int bRemoveDiacritic;
   144001   int nException;
   144002   int *aiException;
   144003 };
   144004 
   144005 struct unicode_cursor {
   144006   sqlite3_tokenizer_cursor base;
   144007   const unsigned char *aInput;    /* Input text being tokenized */
   144008   int nInput;                     /* Size of aInput[] in bytes */
   144009   int iOff;                       /* Current offset within aInput[] */
   144010   int iToken;                     /* Index of next token to be returned */
   144011   char *zToken;                   /* storage for current token */
   144012   int nAlloc;                     /* space allocated at zToken */
   144013 };
   144014 
   144015 
   144016 /*
   144017 ** Destroy a tokenizer allocated by unicodeCreate().
   144018 */
   144019 static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
   144020   if( pTokenizer ){
   144021     unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
   144022     sqlite3_free(p->aiException);
   144023     sqlite3_free(p);
   144024   }
   144025   return SQLITE_OK;
   144026 }
   144027 
   144028 /*
   144029 ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
   144030 ** statement has specified that the tokenizer for this table shall consider
   144031 ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
   144032 ** token characters (if bAlnum==1).
   144033 **
   144034 ** For each codepoint in the zIn/nIn string, this function checks if the
   144035 ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
   144036 ** If so, no action is taken. Otherwise, the codepoint is added to the
   144037 ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
   144038 ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
   144039 ** codepoints in the aiException[] array.
   144040 **
   144041 ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
   144042 ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
   144043 ** It is not possible to change the behavior of the tokenizer with respect
   144044 ** to these codepoints.
   144045 */
   144046 static int unicodeAddExceptions(
   144047   unicode_tokenizer *p,           /* Tokenizer to add exceptions to */
   144048   int bAlnum,                     /* Replace Isalnum() return value with this */
   144049   const char *zIn,                /* Array of characters to make exceptions */
   144050   int nIn                         /* Length of z in bytes */
   144051 ){
   144052   const unsigned char *z = (const unsigned char *)zIn;
   144053   const unsigned char *zTerm = &z[nIn];
   144054   int iCode;
   144055   int nEntry = 0;
   144056 
   144057   assert( bAlnum==0 || bAlnum==1 );
   144058 
   144059   while( z<zTerm ){
   144060     READ_UTF8(z, zTerm, iCode);
   144061     assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
   144062     if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
   144063      && sqlite3FtsUnicodeIsdiacritic(iCode)==0
   144064     ){
   144065       nEntry++;
   144066     }
   144067   }
   144068 
   144069   if( nEntry ){
   144070     int *aNew;                    /* New aiException[] array */
   144071     int nNew;                     /* Number of valid entries in array aNew[] */
   144072 
   144073     aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
   144074     if( aNew==0 ) return SQLITE_NOMEM;
   144075     nNew = p->nException;
   144076 
   144077     z = (const unsigned char *)zIn;
   144078     while( z<zTerm ){
   144079       READ_UTF8(z, zTerm, iCode);
   144080       if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
   144081        && sqlite3FtsUnicodeIsdiacritic(iCode)==0
   144082       ){
   144083         int i, j;
   144084         for(i=0; i<nNew && aNew[i]<iCode; i++);
   144085         for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
   144086         aNew[i] = iCode;
   144087         nNew++;
   144088       }
   144089     }
   144090     p->aiException = aNew;
   144091     p->nException = nNew;
   144092   }
   144093 
   144094   return SQLITE_OK;
   144095 }
   144096 
   144097 /*
   144098 ** Return true if the p->aiException[] array contains the value iCode.
   144099 */
   144100 static int unicodeIsException(unicode_tokenizer *p, int iCode){
   144101   if( p->nException>0 ){
   144102     int *a = p->aiException;
   144103     int iLo = 0;
   144104     int iHi = p->nException-1;
   144105 
   144106     while( iHi>=iLo ){
   144107       int iTest = (iHi + iLo) / 2;
   144108       if( iCode==a[iTest] ){
   144109         return 1;
   144110       }else if( iCode>a[iTest] ){
   144111         iLo = iTest+1;
   144112       }else{
   144113         iHi = iTest-1;
   144114       }
   144115     }
   144116   }
   144117 
   144118   return 0;
   144119 }
   144120 
   144121 /*
   144122 ** Return true if, for the purposes of tokenization, codepoint iCode is
   144123 ** considered a token character (not a separator).
   144124 */
   144125 static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
   144126   assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
   144127   return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
   144128 }
   144129 
   144130 /*
   144131 ** Create a new tokenizer instance.
   144132 */
   144133 static int unicodeCreate(
   144134   int nArg,                       /* Size of array argv[] */
   144135   const char * const *azArg,      /* Tokenizer creation arguments */
   144136   sqlite3_tokenizer **pp          /* OUT: New tokenizer handle */
   144137 ){
   144138   unicode_tokenizer *pNew;        /* New tokenizer object */
   144139   int i;
   144140   int rc = SQLITE_OK;
   144141 
   144142   pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
   144143   if( pNew==NULL ) return SQLITE_NOMEM;
   144144   memset(pNew, 0, sizeof(unicode_tokenizer));
   144145   pNew->bRemoveDiacritic = 1;
   144146 
   144147   for(i=0; rc==SQLITE_OK && i<nArg; i++){
   144148     const char *z = azArg[i];
   144149     int n = (int)strlen(z);
   144150 
   144151     if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
   144152       pNew->bRemoveDiacritic = 1;
   144153     }
   144154     else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
   144155       pNew->bRemoveDiacritic = 0;
   144156     }
   144157     else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
   144158       rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
   144159     }
   144160     else if( n>=11 && memcmp("separators=", z, 11)==0 ){
   144161       rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
   144162     }
   144163     else{
   144164       /* Unrecognized argument */
   144165       rc  = SQLITE_ERROR;
   144166     }
   144167   }
   144168 
   144169   if( rc!=SQLITE_OK ){
   144170     unicodeDestroy((sqlite3_tokenizer *)pNew);
   144171     pNew = 0;
   144172   }
   144173   *pp = (sqlite3_tokenizer *)pNew;
   144174   return rc;
   144175 }
   144176 
   144177 /*
   144178 ** Prepare to begin tokenizing a particular string.  The input
   144179 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
   144180 ** used to incrementally tokenize this string is returned in
   144181 ** *ppCursor.
   144182 */
   144183 static int unicodeOpen(
   144184   sqlite3_tokenizer *p,           /* The tokenizer */
   144185   const char *aInput,             /* Input string */
   144186   int nInput,                     /* Size of string aInput in bytes */
   144187   sqlite3_tokenizer_cursor **pp   /* OUT: New cursor object */
   144188 ){
   144189   unicode_cursor *pCsr;
   144190 
   144191   pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
   144192   if( pCsr==0 ){
   144193     return SQLITE_NOMEM;
   144194   }
   144195   memset(pCsr, 0, sizeof(unicode_cursor));
   144196 
   144197   pCsr->aInput = (const unsigned char *)aInput;
   144198   if( aInput==0 ){
   144199     pCsr->nInput = 0;
   144200   }else if( nInput<0 ){
   144201     pCsr->nInput = (int)strlen(aInput);
   144202   }else{
   144203     pCsr->nInput = nInput;
   144204   }
   144205 
   144206   *pp = &pCsr->base;
   144207   UNUSED_PARAMETER(p);
   144208   return SQLITE_OK;
   144209 }
   144210 
   144211 /*
   144212 ** Close a tokenization cursor previously opened by a call to
   144213 ** simpleOpen() above.
   144214 */
   144215 static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
   144216   unicode_cursor *pCsr = (unicode_cursor *) pCursor;
   144217   sqlite3_free(pCsr->zToken);
   144218   sqlite3_free(pCsr);
   144219   return SQLITE_OK;
   144220 }
   144221 
   144222 /*
   144223 ** Extract the next token from a tokenization cursor.  The cursor must
   144224 ** have been opened by a prior call to simpleOpen().
   144225 */
   144226 static int unicodeNext(
   144227   sqlite3_tokenizer_cursor *pC,   /* Cursor returned by simpleOpen */
   144228   const char **paToken,           /* OUT: Token text */
   144229   int *pnToken,                   /* OUT: Number of bytes at *paToken */
   144230   int *piStart,                   /* OUT: Starting offset of token */
   144231   int *piEnd,                     /* OUT: Ending offset of token */
   144232   int *piPos                      /* OUT: Position integer of token */
   144233 ){
   144234   unicode_cursor *pCsr = (unicode_cursor *)pC;
   144235   unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
   144236   int iCode = 0;
   144237   char *zOut;
   144238   const unsigned char *z = &pCsr->aInput[pCsr->iOff];
   144239   const unsigned char *zStart = z;
   144240   const unsigned char *zEnd;
   144241   const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
   144242 
   144243   /* Scan past any delimiter characters before the start of the next token.
   144244   ** Return SQLITE_DONE early if this takes us all the way to the end of
   144245   ** the input.  */
   144246   while( z<zTerm ){
   144247     READ_UTF8(z, zTerm, iCode);
   144248     if( unicodeIsAlnum(p, iCode) ) break;
   144249     zStart = z;
   144250   }
   144251   if( zStart>=zTerm ) return SQLITE_DONE;
   144252 
   144253   zOut = pCsr->zToken;
   144254   do {
   144255     int iOut;
   144256 
   144257     /* Grow the output buffer if required. */
   144258     if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
   144259       char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
   144260       if( !zNew ) return SQLITE_NOMEM;
   144261       zOut = &zNew[zOut - pCsr->zToken];
   144262       pCsr->zToken = zNew;
   144263       pCsr->nAlloc += 64;
   144264     }
   144265 
   144266     /* Write the folded case of the last character read to the output */
   144267     zEnd = z;
   144268     iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic);
   144269     if( iOut ){
   144270       WRITE_UTF8(zOut, iOut);
   144271     }
   144272 
   144273     /* If the cursor is not at EOF, read the next character */
   144274     if( z>=zTerm ) break;
   144275     READ_UTF8(z, zTerm, iCode);
   144276   }while( unicodeIsAlnum(p, iCode)
   144277        || sqlite3FtsUnicodeIsdiacritic(iCode)
   144278   );
   144279 
   144280   /* Set the output variables and return. */
   144281   pCsr->iOff = (int)(z - pCsr->aInput);
   144282   *paToken = pCsr->zToken;
   144283   *pnToken = (int)(zOut - pCsr->zToken);
   144284   *piStart = (int)(zStart - pCsr->aInput);
   144285   *piEnd = (int)(zEnd - pCsr->aInput);
   144286   *piPos = pCsr->iToken++;
   144287   return SQLITE_OK;
   144288 }
   144289 
   144290 /*
   144291 ** Set *ppModule to a pointer to the sqlite3_tokenizer_module
   144292 ** structure for the unicode tokenizer.
   144293 */
   144294 SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
   144295   static const sqlite3_tokenizer_module module = {
   144296     0,
   144297     unicodeCreate,
   144298     unicodeDestroy,
   144299     unicodeOpen,
   144300     unicodeClose,
   144301     unicodeNext,
   144302     0,
   144303   };
   144304   *ppModule = &module;
   144305 }
   144306 
   144307 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   144308 #endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */
   144309 
   144310 /************** End of fts3_unicode.c ****************************************/
   144311 /************** Begin file fts3_unicode2.c ***********************************/
   144312 /*
   144313 ** 2012 May 25
   144314 **
   144315 ** The author disclaims copyright to this source code.  In place of
   144316 ** a legal notice, here is a blessing:
   144317 **
   144318 **    May you do good and not evil.
   144319 **    May you find forgiveness for yourself and forgive others.
   144320 **    May you share freely, never taking more than you give.
   144321 **
   144322 ******************************************************************************
   144323 */
   144324 
   144325 /*
   144326 ** DO NOT EDIT THIS MACHINE GENERATED FILE.
   144327 */
   144328 
   144329 #ifndef SQLITE_DISABLE_FTS3_UNICODE
   144330 #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
   144331 
   144332 /* #include <assert.h> */
   144333 
   144334 /*
   144335 ** Return true if the argument corresponds to a unicode codepoint
   144336 ** classified as either a letter or a number. Otherwise false.
   144337 **
   144338 ** The results are undefined if the value passed to this function
   144339 ** is less than zero.
   144340 */
   144341 SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
   144342   /* Each unsigned integer in the following array corresponds to a contiguous
   144343   ** range of unicode codepoints that are not either letters or numbers (i.e.
   144344   ** codepoints for which this function should return 0).
   144345   **
   144346   ** The most significant 22 bits in each 32-bit value contain the first
   144347   ** codepoint in the range. The least significant 10 bits are used to store
   144348   ** the size of the range (always at least 1). In other words, the value
   144349   ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
   144350   ** C. It is not possible to represent a range larger than 1023 codepoints
   144351   ** using this format.
   144352   */
   144353   static const unsigned int aEntry[] = {
   144354     0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
   144355     0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
   144356     0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
   144357     0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
   144358     0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
   144359     0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
   144360     0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
   144361     0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
   144362     0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
   144363     0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
   144364     0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
   144365     0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
   144366     0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
   144367     0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
   144368     0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
   144369     0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
   144370     0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
   144371     0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
   144372     0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
   144373     0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
   144374     0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
   144375     0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
   144376     0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
   144377     0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
   144378     0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
   144379     0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
   144380     0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
   144381     0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
   144382     0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
   144383     0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
   144384     0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
   144385     0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
   144386     0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
   144387     0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
   144388     0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
   144389     0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
   144390     0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
   144391     0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
   144392     0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
   144393     0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
   144394     0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
   144395     0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
   144396     0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
   144397     0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
   144398     0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
   144399     0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
   144400     0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
   144401     0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
   144402     0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
   144403     0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
   144404     0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
   144405     0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
   144406     0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
   144407     0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
   144408     0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
   144409     0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
   144410     0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
   144411     0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
   144412     0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
   144413     0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
   144414     0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
   144415     0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
   144416     0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
   144417     0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
   144418     0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
   144419     0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
   144420     0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
   144421     0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
   144422     0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
   144423     0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
   144424     0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
   144425     0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
   144426     0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
   144427     0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
   144428     0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
   144429     0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
   144430     0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
   144431     0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
   144432     0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
   144433     0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
   144434     0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
   144435     0x380400F0,
   144436   };
   144437   static const unsigned int aAscii[4] = {
   144438     0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
   144439   };
   144440 
   144441   if( c<128 ){
   144442     return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
   144443   }else if( c<(1<<22) ){
   144444     unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
   144445     int iRes = 0;
   144446     int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
   144447     int iLo = 0;
   144448     while( iHi>=iLo ){
   144449       int iTest = (iHi + iLo) / 2;
   144450       if( key >= aEntry[iTest] ){
   144451         iRes = iTest;
   144452         iLo = iTest+1;
   144453       }else{
   144454         iHi = iTest-1;
   144455       }
   144456     }
   144457     assert( aEntry[0]<key );
   144458     assert( key>=aEntry[iRes] );
   144459     return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
   144460   }
   144461   return 1;
   144462 }
   144463 
   144464 
   144465 /*
   144466 ** If the argument is a codepoint corresponding to a lowercase letter
   144467 ** in the ASCII range with a diacritic added, return the codepoint
   144468 ** of the ASCII letter only. For example, if passed 235 - "LATIN
   144469 ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
   144470 ** E"). The resuls of passing a codepoint that corresponds to an
   144471 ** uppercase letter are undefined.
   144472 */
   144473 static int remove_diacritic(int c){
   144474   unsigned short aDia[] = {
   144475         0,  1797,  1848,  1859,  1891,  1928,  1940,  1995,
   144476      2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286,
   144477      2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732,
   144478      2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336,
   144479      3456,  3696,  3712,  3728,  3744,  3896,  3912,  3928,
   144480      3968,  4008,  4040,  4106,  4138,  4170,  4202,  4234,
   144481      4266,  4296,  4312,  4344,  4408,  4424,  4472,  4504,
   144482      6148,  6198,  6264,  6280,  6360,  6429,  6505,  6529,
   144483     61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
   144484     61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
   144485     62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
   144486     62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
   144487     62924, 63050, 63082, 63274, 63390,
   144488   };
   144489   char aChar[] = {
   144490     '\0', 'a',  'c',  'e',  'i',  'n',  'o',  'u',  'y',  'y',  'a',  'c',
   144491     'd',  'e',  'e',  'g',  'h',  'i',  'j',  'k',  'l',  'n',  'o',  'r',
   144492     's',  't',  'u',  'u',  'w',  'y',  'z',  'o',  'u',  'a',  'i',  'o',
   144493     'u',  'g',  'k',  'o',  'j',  'g',  'n',  'a',  'e',  'i',  'o',  'r',
   144494     'u',  's',  't',  'h',  'a',  'e',  'o',  'y',  '\0', '\0', '\0', '\0',
   144495     '\0', '\0', '\0', '\0', 'a',  'b',  'd',  'd',  'e',  'f',  'g',  'h',
   144496     'h',  'i',  'k',  'l',  'l',  'm',  'n',  'p',  'r',  'r',  's',  't',
   144497     'u',  'v',  'w',  'w',  'x',  'y',  'z',  'h',  't',  'w',  'y',  'a',
   144498     'e',  'i',  'o',  'u',  'y',
   144499   };
   144500 
   144501   unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
   144502   int iRes = 0;
   144503   int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
   144504   int iLo = 0;
   144505   while( iHi>=iLo ){
   144506     int iTest = (iHi + iLo) / 2;
   144507     if( key >= aDia[iTest] ){
   144508       iRes = iTest;
   144509       iLo = iTest+1;
   144510     }else{
   144511       iHi = iTest-1;
   144512     }
   144513   }
   144514   assert( key>=aDia[iRes] );
   144515   return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
   144516 }
   144517 
   144518 
   144519 /*
   144520 ** Return true if the argument interpreted as a unicode codepoint
   144521 ** is a diacritical modifier character.
   144522 */
   144523 SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
   144524   unsigned int mask0 = 0x08029FDF;
   144525   unsigned int mask1 = 0x000361F8;
   144526   if( c<768 || c>817 ) return 0;
   144527   return (c < 768+32) ?
   144528       (mask0 & (1 << (c-768))) :
   144529       (mask1 & (1 << (c-768-32)));
   144530 }
   144531 
   144532 
   144533 /*
   144534 ** Interpret the argument as a unicode codepoint. If the codepoint
   144535 ** is an upper case character that has a lower case equivalent,
   144536 ** return the codepoint corresponding to the lower case version.
   144537 ** Otherwise, return a copy of the argument.
   144538 **
   144539 ** The results are undefined if the value passed to this function
   144540 ** is less than zero.
   144541 */
   144542 SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
   144543   /* Each entry in the following array defines a rule for folding a range
   144544   ** of codepoints to lower case. The rule applies to a range of nRange
   144545   ** codepoints starting at codepoint iCode.
   144546   **
   144547   ** If the least significant bit in flags is clear, then the rule applies
   144548   ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
   144549   ** need to be folded). Or, if it is set, then the rule only applies to
   144550   ** every second codepoint in the range, starting with codepoint C.
   144551   **
   144552   ** The 7 most significant bits in flags are an index into the aiOff[]
   144553   ** array. If a specific codepoint C does require folding, then its lower
   144554   ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
   144555   **
   144556   ** The contents of this array are generated by parsing the CaseFolding.txt
   144557   ** file distributed as part of the "Unicode Character Database". See
   144558   ** http://www.unicode.org for details.
   144559   */
   144560   static const struct TableEntry {
   144561     unsigned short iCode;
   144562     unsigned char flags;
   144563     unsigned char nRange;
   144564   } aEntry[] = {
   144565     {65, 14, 26},          {181, 64, 1},          {192, 14, 23},
   144566     {216, 14, 7},          {256, 1, 48},          {306, 1, 6},
   144567     {313, 1, 16},          {330, 1, 46},          {376, 116, 1},
   144568     {377, 1, 6},           {383, 104, 1},         {385, 50, 1},
   144569     {386, 1, 4},           {390, 44, 1},          {391, 0, 1},
   144570     {393, 42, 2},          {395, 0, 1},           {398, 32, 1},
   144571     {399, 38, 1},          {400, 40, 1},          {401, 0, 1},
   144572     {403, 42, 1},          {404, 46, 1},          {406, 52, 1},
   144573     {407, 48, 1},          {408, 0, 1},           {412, 52, 1},
   144574     {413, 54, 1},          {415, 56, 1},          {416, 1, 6},
   144575     {422, 60, 1},          {423, 0, 1},           {425, 60, 1},
   144576     {428, 0, 1},           {430, 60, 1},          {431, 0, 1},
   144577     {433, 58, 2},          {435, 1, 4},           {439, 62, 1},
   144578     {440, 0, 1},           {444, 0, 1},           {452, 2, 1},
   144579     {453, 0, 1},           {455, 2, 1},           {456, 0, 1},
   144580     {458, 2, 1},           {459, 1, 18},          {478, 1, 18},
   144581     {497, 2, 1},           {498, 1, 4},           {502, 122, 1},
   144582     {503, 134, 1},         {504, 1, 40},          {544, 110, 1},
   144583     {546, 1, 18},          {570, 70, 1},          {571, 0, 1},
   144584     {573, 108, 1},         {574, 68, 1},          {577, 0, 1},
   144585     {579, 106, 1},         {580, 28, 1},          {581, 30, 1},
   144586     {582, 1, 10},          {837, 36, 1},          {880, 1, 4},
   144587     {886, 0, 1},           {902, 18, 1},          {904, 16, 3},
   144588     {908, 26, 1},          {910, 24, 2},          {913, 14, 17},
   144589     {931, 14, 9},          {962, 0, 1},           {975, 4, 1},
   144590     {976, 140, 1},         {977, 142, 1},         {981, 146, 1},
   144591     {982, 144, 1},         {984, 1, 24},          {1008, 136, 1},
   144592     {1009, 138, 1},        {1012, 130, 1},        {1013, 128, 1},
   144593     {1015, 0, 1},          {1017, 152, 1},        {1018, 0, 1},
   144594     {1021, 110, 3},        {1024, 34, 16},        {1040, 14, 32},
   144595     {1120, 1, 34},         {1162, 1, 54},         {1216, 6, 1},
   144596     {1217, 1, 14},         {1232, 1, 88},         {1329, 22, 38},
   144597     {4256, 66, 38},        {4295, 66, 1},         {4301, 66, 1},
   144598     {7680, 1, 150},        {7835, 132, 1},        {7838, 96, 1},
   144599     {7840, 1, 96},         {7944, 150, 8},        {7960, 150, 6},
   144600     {7976, 150, 8},        {7992, 150, 8},        {8008, 150, 6},
   144601     {8025, 151, 8},        {8040, 150, 8},        {8072, 150, 8},
   144602     {8088, 150, 8},        {8104, 150, 8},        {8120, 150, 2},
   144603     {8122, 126, 2},        {8124, 148, 1},        {8126, 100, 1},
   144604     {8136, 124, 4},        {8140, 148, 1},        {8152, 150, 2},
   144605     {8154, 120, 2},        {8168, 150, 2},        {8170, 118, 2},
   144606     {8172, 152, 1},        {8184, 112, 2},        {8186, 114, 2},
   144607     {8188, 148, 1},        {8486, 98, 1},         {8490, 92, 1},
   144608     {8491, 94, 1},         {8498, 12, 1},         {8544, 8, 16},
   144609     {8579, 0, 1},          {9398, 10, 26},        {11264, 22, 47},
   144610     {11360, 0, 1},         {11362, 88, 1},        {11363, 102, 1},
   144611     {11364, 90, 1},        {11367, 1, 6},         {11373, 84, 1},
   144612     {11374, 86, 1},        {11375, 80, 1},        {11376, 82, 1},
   144613     {11378, 0, 1},         {11381, 0, 1},         {11390, 78, 2},
   144614     {11392, 1, 100},       {11499, 1, 4},         {11506, 0, 1},
   144615     {42560, 1, 46},        {42624, 1, 24},        {42786, 1, 14},
   144616     {42802, 1, 62},        {42873, 1, 4},         {42877, 76, 1},
   144617     {42878, 1, 10},        {42891, 0, 1},         {42893, 74, 1},
   144618     {42896, 1, 4},         {42912, 1, 10},        {42922, 72, 1},
   144619     {65313, 14, 26},
   144620   };
   144621   static const unsigned short aiOff[] = {
   144622    1,     2,     8,     15,    16,    26,    28,    32,
   144623    37,    38,    40,    48,    63,    64,    69,    71,
   144624    79,    80,    116,   202,   203,   205,   206,   207,
   144625    209,   210,   211,   213,   214,   217,   218,   219,
   144626    775,   7264,  10792, 10795, 23228, 23256, 30204, 54721,
   144627    54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
   144628    57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
   144629    65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
   144630    65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
   144631    65514, 65521, 65527, 65528, 65529,
   144632   };
   144633 
   144634   int ret = c;
   144635 
   144636   assert( c>=0 );
   144637   assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
   144638 
   144639   if( c<128 ){
   144640     if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
   144641   }else if( c<65536 ){
   144642     int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
   144643     int iLo = 0;
   144644     int iRes = -1;
   144645 
   144646     while( iHi>=iLo ){
   144647       int iTest = (iHi + iLo) / 2;
   144648       int cmp = (c - aEntry[iTest].iCode);
   144649       if( cmp>=0 ){
   144650         iRes = iTest;
   144651         iLo = iTest+1;
   144652       }else{
   144653         iHi = iTest-1;
   144654       }
   144655     }
   144656     assert( iRes<0 || c>=aEntry[iRes].iCode );
   144657 
   144658     if( iRes>=0 ){
   144659       const struct TableEntry *p = &aEntry[iRes];
   144660       if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
   144661         ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
   144662         assert( ret>0 );
   144663       }
   144664     }
   144665 
   144666     if( bRemoveDiacritic ) ret = remove_diacritic(ret);
   144667   }
   144668 
   144669   else if( c>=66560 && c<66600 ){
   144670     ret = c + 40;
   144671   }
   144672 
   144673   return ret;
   144674 }
   144675 #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
   144676 #endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */
   144677 
   144678 /************** End of fts3_unicode2.c ***************************************/
   144679 /************** Begin file rtree.c *******************************************/
   144680 /*
   144681 ** 2001 September 15
   144682 **
   144683 ** The author disclaims copyright to this source code.  In place of
   144684 ** a legal notice, here is a blessing:
   144685 **
   144686 **    May you do good and not evil.
   144687 **    May you find forgiveness for yourself and forgive others.
   144688 **    May you share freely, never taking more than you give.
   144689 **
   144690 *************************************************************************
   144691 ** This file contains code for implementations of the r-tree and r*-tree
   144692 ** algorithms packaged as an SQLite virtual table module.
   144693 */
   144694 
   144695 /*
   144696 ** Database Format of R-Tree Tables
   144697 ** --------------------------------
   144698 **
   144699 ** The data structure for a single virtual r-tree table is stored in three
   144700 ** native SQLite tables declared as follows. In each case, the '%' character
   144701 ** in the table name is replaced with the user-supplied name of the r-tree
   144702 ** table.
   144703 **
   144704 **   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
   144705 **   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
   144706 **   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
   144707 **
   144708 ** The data for each node of the r-tree structure is stored in the %_node
   144709 ** table. For each node that is not the root node of the r-tree, there is
   144710 ** an entry in the %_parent table associating the node with its parent.
   144711 ** And for each row of data in the table, there is an entry in the %_rowid
   144712 ** table that maps from the entries rowid to the id of the node that it
   144713 ** is stored on.
   144714 **
   144715 ** The root node of an r-tree always exists, even if the r-tree table is
   144716 ** empty. The nodeno of the root node is always 1. All other nodes in the
   144717 ** table must be the same size as the root node. The content of each node
   144718 ** is formatted as follows:
   144719 **
   144720 **   1. If the node is the root node (node 1), then the first 2 bytes
   144721 **      of the node contain the tree depth as a big-endian integer.
   144722 **      For non-root nodes, the first 2 bytes are left unused.
   144723 **
   144724 **   2. The next 2 bytes contain the number of entries currently
   144725 **      stored in the node.
   144726 **
   144727 **   3. The remainder of the node contains the node entries. Each entry
   144728 **      consists of a single 8-byte integer followed by an even number
   144729 **      of 4-byte coordinates. For leaf nodes the integer is the rowid
   144730 **      of a record. For internal nodes it is the node number of a
   144731 **      child page.
   144732 */
   144733 
   144734 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
   144735 
   144736 #ifndef SQLITE_CORE
   144737   SQLITE_EXTENSION_INIT1
   144738 #else
   144739 #endif
   144740 
   144741 /* #include <string.h> */
   144742 /* #include <assert.h> */
   144743 /* #include <stdio.h> */
   144744 
   144745 #ifndef SQLITE_AMALGAMATION
   144746 #include "sqlite3rtree.h"
   144747 typedef sqlite3_int64 i64;
   144748 typedef unsigned char u8;
   144749 typedef unsigned short u16;
   144750 typedef unsigned int u32;
   144751 #endif
   144752 
   144753 /*  The following macro is used to suppress compiler warnings.
   144754 */
   144755 #ifndef UNUSED_PARAMETER
   144756 # define UNUSED_PARAMETER(x) (void)(x)
   144757 #endif
   144758 
   144759 typedef struct Rtree Rtree;
   144760 typedef struct RtreeCursor RtreeCursor;
   144761 typedef struct RtreeNode RtreeNode;
   144762 typedef struct RtreeCell RtreeCell;
   144763 typedef struct RtreeConstraint RtreeConstraint;
   144764 typedef struct RtreeMatchArg RtreeMatchArg;
   144765 typedef struct RtreeGeomCallback RtreeGeomCallback;
   144766 typedef union RtreeCoord RtreeCoord;
   144767 typedef struct RtreeSearchPoint RtreeSearchPoint;
   144768 
   144769 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
   144770 #define RTREE_MAX_DIMENSIONS 5
   144771 
   144772 /* Size of hash table Rtree.aHash. This hash table is not expected to
   144773 ** ever contain very many entries, so a fixed number of buckets is
   144774 ** used.
   144775 */
   144776 #define HASHSIZE 97
   144777 
   144778 /* The xBestIndex method of this virtual table requires an estimate of
   144779 ** the number of rows in the virtual table to calculate the costs of
   144780 ** various strategies. If possible, this estimate is loaded from the
   144781 ** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
   144782 ** Otherwise, if no sqlite_stat1 entry is available, use
   144783 ** RTREE_DEFAULT_ROWEST.
   144784 */
   144785 #define RTREE_DEFAULT_ROWEST 1048576
   144786 #define RTREE_MIN_ROWEST         100
   144787 
   144788 /*
   144789 ** An rtree virtual-table object.
   144790 */
   144791 struct Rtree {
   144792   sqlite3_vtab base;          /* Base class.  Must be first */
   144793   sqlite3 *db;                /* Host database connection */
   144794   int iNodeSize;              /* Size in bytes of each node in the node table */
   144795   u8 nDim;                    /* Number of dimensions */
   144796   u8 eCoordType;              /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
   144797   u8 nBytesPerCell;           /* Bytes consumed per cell */
   144798   int iDepth;                 /* Current depth of the r-tree structure */
   144799   char *zDb;                  /* Name of database containing r-tree table */
   144800   char *zName;                /* Name of r-tree table */
   144801   int nBusy;                  /* Current number of users of this structure */
   144802   i64 nRowEst;                /* Estimated number of rows in this table */
   144803 
   144804   /* List of nodes removed during a CondenseTree operation. List is
   144805   ** linked together via the pointer normally used for hash chains -
   144806   ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
   144807   ** headed by the node (leaf nodes have RtreeNode.iNode==0).
   144808   */
   144809   RtreeNode *pDeleted;
   144810   int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
   144811 
   144812   /* Statements to read/write/delete a record from xxx_node */
   144813   sqlite3_stmt *pReadNode;
   144814   sqlite3_stmt *pWriteNode;
   144815   sqlite3_stmt *pDeleteNode;
   144816 
   144817   /* Statements to read/write/delete a record from xxx_rowid */
   144818   sqlite3_stmt *pReadRowid;
   144819   sqlite3_stmt *pWriteRowid;
   144820   sqlite3_stmt *pDeleteRowid;
   144821 
   144822   /* Statements to read/write/delete a record from xxx_parent */
   144823   sqlite3_stmt *pReadParent;
   144824   sqlite3_stmt *pWriteParent;
   144825   sqlite3_stmt *pDeleteParent;
   144826 
   144827   RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
   144828 };
   144829 
   144830 /* Possible values for Rtree.eCoordType: */
   144831 #define RTREE_COORD_REAL32 0
   144832 #define RTREE_COORD_INT32  1
   144833 
   144834 /*
   144835 ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
   144836 ** only deal with integer coordinates.  No floating point operations
   144837 ** will be done.
   144838 */
   144839 #ifdef SQLITE_RTREE_INT_ONLY
   144840   typedef sqlite3_int64 RtreeDValue;       /* High accuracy coordinate */
   144841   typedef int RtreeValue;                  /* Low accuracy coordinate */
   144842 # define RTREE_ZERO 0
   144843 #else
   144844   typedef double RtreeDValue;              /* High accuracy coordinate */
   144845   typedef float RtreeValue;                /* Low accuracy coordinate */
   144846 # define RTREE_ZERO 0.0
   144847 #endif
   144848 
   144849 /*
   144850 ** When doing a search of an r-tree, instances of the following structure
   144851 ** record intermediate results from the tree walk.
   144852 **
   144853 ** The id is always a node-id.  For iLevel>=1 the id is the node-id of
   144854 ** the node that the RtreeSearchPoint represents.  When iLevel==0, however,
   144855 ** the id is of the parent node and the cell that RtreeSearchPoint
   144856 ** represents is the iCell-th entry in the parent node.
   144857 */
   144858 struct RtreeSearchPoint {
   144859   RtreeDValue rScore;    /* The score for this node.  Smallest goes first. */
   144860   sqlite3_int64 id;      /* Node ID */
   144861   u8 iLevel;             /* 0=entries.  1=leaf node.  2+ for higher */
   144862   u8 eWithin;            /* PARTLY_WITHIN or FULLY_WITHIN */
   144863   u8 iCell;              /* Cell index within the node */
   144864 };
   144865 
   144866 /*
   144867 ** The minimum number of cells allowed for a node is a third of the
   144868 ** maximum. In Gutman's notation:
   144869 **
   144870 **     m = M/3
   144871 **
   144872 ** If an R*-tree "Reinsert" operation is required, the same number of
   144873 ** cells are removed from the overfull node and reinserted into the tree.
   144874 */
   144875 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
   144876 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
   144877 #define RTREE_MAXCELLS 51
   144878 
   144879 /*
   144880 ** The smallest possible node-size is (512-64)==448 bytes. And the largest
   144881 ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
   144882 ** Therefore all non-root nodes must contain at least 3 entries. Since
   144883 ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
   144884 ** 40 or less.
   144885 */
   144886 #define RTREE_MAX_DEPTH 40
   144887 
   144888 
   144889 /*
   144890 ** Number of entries in the cursor RtreeNode cache.  The first entry is
   144891 ** used to cache the RtreeNode for RtreeCursor.sPoint.  The remaining
   144892 ** entries cache the RtreeNode for the first elements of the priority queue.
   144893 */
   144894 #define RTREE_CACHE_SZ  5
   144895 
   144896 /*
   144897 ** An rtree cursor object.
   144898 */
   144899 struct RtreeCursor {
   144900   sqlite3_vtab_cursor base;         /* Base class.  Must be first */
   144901   u8 atEOF;                         /* True if at end of search */
   144902   u8 bPoint;                        /* True if sPoint is valid */
   144903   int iStrategy;                    /* Copy of idxNum search parameter */
   144904   int nConstraint;                  /* Number of entries in aConstraint */
   144905   RtreeConstraint *aConstraint;     /* Search constraints. */
   144906   int nPointAlloc;                  /* Number of slots allocated for aPoint[] */
   144907   int nPoint;                       /* Number of slots used in aPoint[] */
   144908   int mxLevel;                      /* iLevel value for root of the tree */
   144909   RtreeSearchPoint *aPoint;         /* Priority queue for search points */
   144910   RtreeSearchPoint sPoint;          /* Cached next search point */
   144911   RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
   144912   u32 anQueue[RTREE_MAX_DEPTH+1];   /* Number of queued entries by iLevel */
   144913 };
   144914 
   144915 /* Return the Rtree of a RtreeCursor */
   144916 #define RTREE_OF_CURSOR(X)   ((Rtree*)((X)->base.pVtab))
   144917 
   144918 /*
   144919 ** A coordinate can be either a floating point number or a integer.  All
   144920 ** coordinates within a single R-Tree are always of the same time.
   144921 */
   144922 union RtreeCoord {
   144923   RtreeValue f;      /* Floating point value */
   144924   int i;             /* Integer value */
   144925   u32 u;             /* Unsigned for byte-order conversions */
   144926 };
   144927 
   144928 /*
   144929 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
   144930 ** formatted as a RtreeDValue (double or int64). This macro assumes that local
   144931 ** variable pRtree points to the Rtree structure associated with the
   144932 ** RtreeCoord.
   144933 */
   144934 #ifdef SQLITE_RTREE_INT_ONLY
   144935 # define DCOORD(coord) ((RtreeDValue)coord.i)
   144936 #else
   144937 # define DCOORD(coord) (                           \
   144938     (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
   144939       ((double)coord.f) :                           \
   144940       ((double)coord.i)                             \
   144941   )
   144942 #endif
   144943 
   144944 /*
   144945 ** A search constraint.
   144946 */
   144947 struct RtreeConstraint {
   144948   int iCoord;                     /* Index of constrained coordinate */
   144949   int op;                         /* Constraining operation */
   144950   union {
   144951     RtreeDValue rValue;             /* Constraint value. */
   144952     int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
   144953     int (*xQueryFunc)(sqlite3_rtree_query_info*);
   144954   } u;
   144955   sqlite3_rtree_query_info *pInfo;  /* xGeom and xQueryFunc argument */
   144956 };
   144957 
   144958 /* Possible values for RtreeConstraint.op */
   144959 #define RTREE_EQ    0x41  /* A */
   144960 #define RTREE_LE    0x42  /* B */
   144961 #define RTREE_LT    0x43  /* C */
   144962 #define RTREE_GE    0x44  /* D */
   144963 #define RTREE_GT    0x45  /* E */
   144964 #define RTREE_MATCH 0x46  /* F: Old-style sqlite3_rtree_geometry_callback() */
   144965 #define RTREE_QUERY 0x47  /* G: New-style sqlite3_rtree_query_callback() */
   144966 
   144967 
   144968 /*
   144969 ** An rtree structure node.
   144970 */
   144971 struct RtreeNode {
   144972   RtreeNode *pParent;         /* Parent node */
   144973   i64 iNode;                  /* The node number */
   144974   int nRef;                   /* Number of references to this node */
   144975   int isDirty;                /* True if the node needs to be written to disk */
   144976   u8 *zData;                  /* Content of the node, as should be on disk */
   144977   RtreeNode *pNext;           /* Next node in this hash collision chain */
   144978 };
   144979 
   144980 /* Return the number of cells in a node  */
   144981 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
   144982 
   144983 /*
   144984 ** A single cell from a node, deserialized
   144985 */
   144986 struct RtreeCell {
   144987   i64 iRowid;                                 /* Node or entry ID */
   144988   RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];  /* Bounding box coordinates */
   144989 };
   144990 
   144991 
   144992 /*
   144993 ** This object becomes the sqlite3_user_data() for the SQL functions
   144994 ** that are created by sqlite3_rtree_geometry_callback() and
   144995 ** sqlite3_rtree_query_callback() and which appear on the right of MATCH
   144996 ** operators in order to constrain a search.
   144997 **
   144998 ** xGeom and xQueryFunc are the callback functions.  Exactly one of
   144999 ** xGeom and xQueryFunc fields is non-NULL, depending on whether the
   145000 ** SQL function was created using sqlite3_rtree_geometry_callback() or
   145001 ** sqlite3_rtree_query_callback().
   145002 **
   145003 ** This object is deleted automatically by the destructor mechanism in
   145004 ** sqlite3_create_function_v2().
   145005 */
   145006 struct RtreeGeomCallback {
   145007   int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
   145008   int (*xQueryFunc)(sqlite3_rtree_query_info*);
   145009   void (*xDestructor)(void*);
   145010   void *pContext;
   145011 };
   145012 
   145013 
   145014 /*
   145015 ** Value for the first field of every RtreeMatchArg object. The MATCH
   145016 ** operator tests that the first field of a blob operand matches this
   145017 ** value to avoid operating on invalid blobs (which could cause a segfault).
   145018 */
   145019 #define RTREE_GEOMETRY_MAGIC 0x891245AB
   145020 
   145021 /*
   145022 ** An instance of this structure (in the form of a BLOB) is returned by
   145023 ** the SQL functions that sqlite3_rtree_geometry_callback() and
   145024 ** sqlite3_rtree_query_callback() create, and is read as the right-hand
   145025 ** operand to the MATCH operator of an R-Tree.
   145026 */
   145027 struct RtreeMatchArg {
   145028   u32 magic;                  /* Always RTREE_GEOMETRY_MAGIC */
   145029   RtreeGeomCallback cb;       /* Info about the callback functions */
   145030   int nParam;                 /* Number of parameters to the SQL function */
   145031   RtreeDValue aParam[1];      /* Values for parameters to the SQL function */
   145032 };
   145033 
   145034 #ifndef MAX
   145035 # define MAX(x,y) ((x) < (y) ? (y) : (x))
   145036 #endif
   145037 #ifndef MIN
   145038 # define MIN(x,y) ((x) > (y) ? (y) : (x))
   145039 #endif
   145040 
   145041 /*
   145042 ** Functions to deserialize a 16 bit integer, 32 bit real number and
   145043 ** 64 bit integer. The deserialized value is returned.
   145044 */
   145045 static int readInt16(u8 *p){
   145046   return (p[0]<<8) + p[1];
   145047 }
   145048 static void readCoord(u8 *p, RtreeCoord *pCoord){
   145049   u32 i = (
   145050     (((u32)p[0]) << 24) +
   145051     (((u32)p[1]) << 16) +
   145052     (((u32)p[2]) <<  8) +
   145053     (((u32)p[3]) <<  0)
   145054   );
   145055   *(u32 *)pCoord = i;
   145056 }
   145057 static i64 readInt64(u8 *p){
   145058   return (
   145059     (((i64)p[0]) << 56) +
   145060     (((i64)p[1]) << 48) +
   145061     (((i64)p[2]) << 40) +
   145062     (((i64)p[3]) << 32) +
   145063     (((i64)p[4]) << 24) +
   145064     (((i64)p[5]) << 16) +
   145065     (((i64)p[6]) <<  8) +
   145066     (((i64)p[7]) <<  0)
   145067   );
   145068 }
   145069 
   145070 /*
   145071 ** Functions to serialize a 16 bit integer, 32 bit real number and
   145072 ** 64 bit integer. The value returned is the number of bytes written
   145073 ** to the argument buffer (always 2, 4 and 8 respectively).
   145074 */
   145075 static int writeInt16(u8 *p, int i){
   145076   p[0] = (i>> 8)&0xFF;
   145077   p[1] = (i>> 0)&0xFF;
   145078   return 2;
   145079 }
   145080 static int writeCoord(u8 *p, RtreeCoord *pCoord){
   145081   u32 i;
   145082   assert( sizeof(RtreeCoord)==4 );
   145083   assert( sizeof(u32)==4 );
   145084   i = *(u32 *)pCoord;
   145085   p[0] = (i>>24)&0xFF;
   145086   p[1] = (i>>16)&0xFF;
   145087   p[2] = (i>> 8)&0xFF;
   145088   p[3] = (i>> 0)&0xFF;
   145089   return 4;
   145090 }
   145091 static int writeInt64(u8 *p, i64 i){
   145092   p[0] = (i>>56)&0xFF;
   145093   p[1] = (i>>48)&0xFF;
   145094   p[2] = (i>>40)&0xFF;
   145095   p[3] = (i>>32)&0xFF;
   145096   p[4] = (i>>24)&0xFF;
   145097   p[5] = (i>>16)&0xFF;
   145098   p[6] = (i>> 8)&0xFF;
   145099   p[7] = (i>> 0)&0xFF;
   145100   return 8;
   145101 }
   145102 
   145103 /*
   145104 ** Increment the reference count of node p.
   145105 */
   145106 static void nodeReference(RtreeNode *p){
   145107   if( p ){
   145108     p->nRef++;
   145109   }
   145110 }
   145111 
   145112 /*
   145113 ** Clear the content of node p (set all bytes to 0x00).
   145114 */
   145115 static void nodeZero(Rtree *pRtree, RtreeNode *p){
   145116   memset(&p->zData[2], 0, pRtree->iNodeSize-2);
   145117   p->isDirty = 1;
   145118 }
   145119 
   145120 /*
   145121 ** Given a node number iNode, return the corresponding key to use
   145122 ** in the Rtree.aHash table.
   145123 */
   145124 static int nodeHash(i64 iNode){
   145125   return iNode % HASHSIZE;
   145126 }
   145127 
   145128 /*
   145129 ** Search the node hash table for node iNode. If found, return a pointer
   145130 ** to it. Otherwise, return 0.
   145131 */
   145132 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
   145133   RtreeNode *p;
   145134   for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
   145135   return p;
   145136 }
   145137 
   145138 /*
   145139 ** Add node pNode to the node hash table.
   145140 */
   145141 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
   145142   int iHash;
   145143   assert( pNode->pNext==0 );
   145144   iHash = nodeHash(pNode->iNode);
   145145   pNode->pNext = pRtree->aHash[iHash];
   145146   pRtree->aHash[iHash] = pNode;
   145147 }
   145148 
   145149 /*
   145150 ** Remove node pNode from the node hash table.
   145151 */
   145152 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
   145153   RtreeNode **pp;
   145154   if( pNode->iNode!=0 ){
   145155     pp = &pRtree->aHash[nodeHash(pNode->iNode)];
   145156     for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
   145157     *pp = pNode->pNext;
   145158     pNode->pNext = 0;
   145159   }
   145160 }
   145161 
   145162 /*
   145163 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
   145164 ** indicating that node has not yet been assigned a node number. It is
   145165 ** assigned a node number when nodeWrite() is called to write the
   145166 ** node contents out to the database.
   145167 */
   145168 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
   145169   RtreeNode *pNode;
   145170   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
   145171   if( pNode ){
   145172     memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
   145173     pNode->zData = (u8 *)&pNode[1];
   145174     pNode->nRef = 1;
   145175     pNode->pParent = pParent;
   145176     pNode->isDirty = 1;
   145177     nodeReference(pParent);
   145178   }
   145179   return pNode;
   145180 }
   145181 
   145182 /*
   145183 ** Obtain a reference to an r-tree node.
   145184 */
   145185 static int nodeAcquire(
   145186   Rtree *pRtree,             /* R-tree structure */
   145187   i64 iNode,                 /* Node number to load */
   145188   RtreeNode *pParent,        /* Either the parent node or NULL */
   145189   RtreeNode **ppNode         /* OUT: Acquired node */
   145190 ){
   145191   int rc;
   145192   int rc2 = SQLITE_OK;
   145193   RtreeNode *pNode;
   145194 
   145195   /* Check if the requested node is already in the hash table. If so,
   145196   ** increase its reference count and return it.
   145197   */
   145198   if( (pNode = nodeHashLookup(pRtree, iNode)) ){
   145199     assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
   145200     if( pParent && !pNode->pParent ){
   145201       nodeReference(pParent);
   145202       pNode->pParent = pParent;
   145203     }
   145204     pNode->nRef++;
   145205     *ppNode = pNode;
   145206     return SQLITE_OK;
   145207   }
   145208 
   145209   sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
   145210   rc = sqlite3_step(pRtree->pReadNode);
   145211   if( rc==SQLITE_ROW ){
   145212     const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
   145213     if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
   145214       pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
   145215       if( !pNode ){
   145216         rc2 = SQLITE_NOMEM;
   145217       }else{
   145218         pNode->pParent = pParent;
   145219         pNode->zData = (u8 *)&pNode[1];
   145220         pNode->nRef = 1;
   145221         pNode->iNode = iNode;
   145222         pNode->isDirty = 0;
   145223         pNode->pNext = 0;
   145224         memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
   145225         nodeReference(pParent);
   145226       }
   145227     }
   145228   }
   145229   rc = sqlite3_reset(pRtree->pReadNode);
   145230   if( rc==SQLITE_OK ) rc = rc2;
   145231 
   145232   /* If the root node was just loaded, set pRtree->iDepth to the height
   145233   ** of the r-tree structure. A height of zero means all data is stored on
   145234   ** the root node. A height of one means the children of the root node
   145235   ** are the leaves, and so on. If the depth as specified on the root node
   145236   ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
   145237   */
   145238   if( pNode && iNode==1 ){
   145239     pRtree->iDepth = readInt16(pNode->zData);
   145240     if( pRtree->iDepth>RTREE_MAX_DEPTH ){
   145241       rc = SQLITE_CORRUPT_VTAB;
   145242     }
   145243   }
   145244 
   145245   /* If no error has occurred so far, check if the "number of entries"
   145246   ** field on the node is too large. If so, set the return code to
   145247   ** SQLITE_CORRUPT_VTAB.
   145248   */
   145249   if( pNode && rc==SQLITE_OK ){
   145250     if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
   145251       rc = SQLITE_CORRUPT_VTAB;
   145252     }
   145253   }
   145254 
   145255   if( rc==SQLITE_OK ){
   145256     if( pNode!=0 ){
   145257       nodeHashInsert(pRtree, pNode);
   145258     }else{
   145259       rc = SQLITE_CORRUPT_VTAB;
   145260     }
   145261     *ppNode = pNode;
   145262   }else{
   145263     sqlite3_free(pNode);
   145264     *ppNode = 0;
   145265   }
   145266 
   145267   return rc;
   145268 }
   145269 
   145270 /*
   145271 ** Overwrite cell iCell of node pNode with the contents of pCell.
   145272 */
   145273 static void nodeOverwriteCell(
   145274   Rtree *pRtree,             /* The overall R-Tree */
   145275   RtreeNode *pNode,          /* The node into which the cell is to be written */
   145276   RtreeCell *pCell,          /* The cell to write */
   145277   int iCell                  /* Index into pNode into which pCell is written */
   145278 ){
   145279   int ii;
   145280   u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
   145281   p += writeInt64(p, pCell->iRowid);
   145282   for(ii=0; ii<(pRtree->nDim*2); ii++){
   145283     p += writeCoord(p, &pCell->aCoord[ii]);
   145284   }
   145285   pNode->isDirty = 1;
   145286 }
   145287 
   145288 /*
   145289 ** Remove the cell with index iCell from node pNode.
   145290 */
   145291 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
   145292   u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
   145293   u8 *pSrc = &pDst[pRtree->nBytesPerCell];
   145294   int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
   145295   memmove(pDst, pSrc, nByte);
   145296   writeInt16(&pNode->zData[2], NCELL(pNode)-1);
   145297   pNode->isDirty = 1;
   145298 }
   145299 
   145300 /*
   145301 ** Insert the contents of cell pCell into node pNode. If the insert
   145302 ** is successful, return SQLITE_OK.
   145303 **
   145304 ** If there is not enough free space in pNode, return SQLITE_FULL.
   145305 */
   145306 static int nodeInsertCell(
   145307   Rtree *pRtree,                /* The overall R-Tree */
   145308   RtreeNode *pNode,             /* Write new cell into this node */
   145309   RtreeCell *pCell              /* The cell to be inserted */
   145310 ){
   145311   int nCell;                    /* Current number of cells in pNode */
   145312   int nMaxCell;                 /* Maximum number of cells for pNode */
   145313 
   145314   nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
   145315   nCell = NCELL(pNode);
   145316 
   145317   assert( nCell<=nMaxCell );
   145318   if( nCell<nMaxCell ){
   145319     nodeOverwriteCell(pRtree, pNode, pCell, nCell);
   145320     writeInt16(&pNode->zData[2], nCell+1);
   145321     pNode->isDirty = 1;
   145322   }
   145323 
   145324   return (nCell==nMaxCell);
   145325 }
   145326 
   145327 /*
   145328 ** If the node is dirty, write it out to the database.
   145329 */
   145330 static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
   145331   int rc = SQLITE_OK;
   145332   if( pNode->isDirty ){
   145333     sqlite3_stmt *p = pRtree->pWriteNode;
   145334     if( pNode->iNode ){
   145335       sqlite3_bind_int64(p, 1, pNode->iNode);
   145336     }else{
   145337       sqlite3_bind_null(p, 1);
   145338     }
   145339     sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
   145340     sqlite3_step(p);
   145341     pNode->isDirty = 0;
   145342     rc = sqlite3_reset(p);
   145343     if( pNode->iNode==0 && rc==SQLITE_OK ){
   145344       pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
   145345       nodeHashInsert(pRtree, pNode);
   145346     }
   145347   }
   145348   return rc;
   145349 }
   145350 
   145351 /*
   145352 ** Release a reference to a node. If the node is dirty and the reference
   145353 ** count drops to zero, the node data is written to the database.
   145354 */
   145355 static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
   145356   int rc = SQLITE_OK;
   145357   if( pNode ){
   145358     assert( pNode->nRef>0 );
   145359     pNode->nRef--;
   145360     if( pNode->nRef==0 ){
   145361       if( pNode->iNode==1 ){
   145362         pRtree->iDepth = -1;
   145363       }
   145364       if( pNode->pParent ){
   145365         rc = nodeRelease(pRtree, pNode->pParent);
   145366       }
   145367       if( rc==SQLITE_OK ){
   145368         rc = nodeWrite(pRtree, pNode);
   145369       }
   145370       nodeHashDelete(pRtree, pNode);
   145371       sqlite3_free(pNode);
   145372     }
   145373   }
   145374   return rc;
   145375 }
   145376 
   145377 /*
   145378 ** Return the 64-bit integer value associated with cell iCell of
   145379 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
   145380 ** an internal node, then the 64-bit integer is a child page number.
   145381 */
   145382 static i64 nodeGetRowid(
   145383   Rtree *pRtree,       /* The overall R-Tree */
   145384   RtreeNode *pNode,    /* The node from which to extract the ID */
   145385   int iCell            /* The cell index from which to extract the ID */
   145386 ){
   145387   assert( iCell<NCELL(pNode) );
   145388   return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
   145389 }
   145390 
   145391 /*
   145392 ** Return coordinate iCoord from cell iCell in node pNode.
   145393 */
   145394 static void nodeGetCoord(
   145395   Rtree *pRtree,               /* The overall R-Tree */
   145396   RtreeNode *pNode,            /* The node from which to extract a coordinate */
   145397   int iCell,                   /* The index of the cell within the node */
   145398   int iCoord,                  /* Which coordinate to extract */
   145399   RtreeCoord *pCoord           /* OUT: Space to write result to */
   145400 ){
   145401   readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
   145402 }
   145403 
   145404 /*
   145405 ** Deserialize cell iCell of node pNode. Populate the structure pointed
   145406 ** to by pCell with the results.
   145407 */
   145408 static void nodeGetCell(
   145409   Rtree *pRtree,               /* The overall R-Tree */
   145410   RtreeNode *pNode,            /* The node containing the cell to be read */
   145411   int iCell,                   /* Index of the cell within the node */
   145412   RtreeCell *pCell             /* OUT: Write the cell contents here */
   145413 ){
   145414   u8 *pData;
   145415   u8 *pEnd;
   145416   RtreeCoord *pCoord;
   145417   pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
   145418   pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
   145419   pEnd = pData + pRtree->nDim*8;
   145420   pCoord = pCell->aCoord;
   145421   for(; pData<pEnd; pData+=4, pCoord++){
   145422     readCoord(pData, pCoord);
   145423   }
   145424 }
   145425 
   145426 
   145427 /* Forward declaration for the function that does the work of
   145428 ** the virtual table module xCreate() and xConnect() methods.
   145429 */
   145430 static int rtreeInit(
   145431   sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
   145432 );
   145433 
   145434 /*
   145435 ** Rtree virtual table module xCreate method.
   145436 */
   145437 static int rtreeCreate(
   145438   sqlite3 *db,
   145439   void *pAux,
   145440   int argc, const char *const*argv,
   145441   sqlite3_vtab **ppVtab,
   145442   char **pzErr
   145443 ){
   145444   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
   145445 }
   145446 
   145447 /*
   145448 ** Rtree virtual table module xConnect method.
   145449 */
   145450 static int rtreeConnect(
   145451   sqlite3 *db,
   145452   void *pAux,
   145453   int argc, const char *const*argv,
   145454   sqlite3_vtab **ppVtab,
   145455   char **pzErr
   145456 ){
   145457   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
   145458 }
   145459 
   145460 /*
   145461 ** Increment the r-tree reference count.
   145462 */
   145463 static void rtreeReference(Rtree *pRtree){
   145464   pRtree->nBusy++;
   145465 }
   145466 
   145467 /*
   145468 ** Decrement the r-tree reference count. When the reference count reaches
   145469 ** zero the structure is deleted.
   145470 */
   145471 static void rtreeRelease(Rtree *pRtree){
   145472   pRtree->nBusy--;
   145473   if( pRtree->nBusy==0 ){
   145474     sqlite3_finalize(pRtree->pReadNode);
   145475     sqlite3_finalize(pRtree->pWriteNode);
   145476     sqlite3_finalize(pRtree->pDeleteNode);
   145477     sqlite3_finalize(pRtree->pReadRowid);
   145478     sqlite3_finalize(pRtree->pWriteRowid);
   145479     sqlite3_finalize(pRtree->pDeleteRowid);
   145480     sqlite3_finalize(pRtree->pReadParent);
   145481     sqlite3_finalize(pRtree->pWriteParent);
   145482     sqlite3_finalize(pRtree->pDeleteParent);
   145483     sqlite3_free(pRtree);
   145484   }
   145485 }
   145486 
   145487 /*
   145488 ** Rtree virtual table module xDisconnect method.
   145489 */
   145490 static int rtreeDisconnect(sqlite3_vtab *pVtab){
   145491   rtreeRelease((Rtree *)pVtab);
   145492   return SQLITE_OK;
   145493 }
   145494 
   145495 /*
   145496 ** Rtree virtual table module xDestroy method.
   145497 */
   145498 static int rtreeDestroy(sqlite3_vtab *pVtab){
   145499   Rtree *pRtree = (Rtree *)pVtab;
   145500   int rc;
   145501   char *zCreate = sqlite3_mprintf(
   145502     "DROP TABLE '%q'.'%q_node';"
   145503     "DROP TABLE '%q'.'%q_rowid';"
   145504     "DROP TABLE '%q'.'%q_parent';",
   145505     pRtree->zDb, pRtree->zName,
   145506     pRtree->zDb, pRtree->zName,
   145507     pRtree->zDb, pRtree->zName
   145508   );
   145509   if( !zCreate ){
   145510     rc = SQLITE_NOMEM;
   145511   }else{
   145512     rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
   145513     sqlite3_free(zCreate);
   145514   }
   145515   if( rc==SQLITE_OK ){
   145516     rtreeRelease(pRtree);
   145517   }
   145518 
   145519   return rc;
   145520 }
   145521 
   145522 /*
   145523 ** Rtree virtual table module xOpen method.
   145524 */
   145525 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
   145526   int rc = SQLITE_NOMEM;
   145527   RtreeCursor *pCsr;
   145528 
   145529   pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
   145530   if( pCsr ){
   145531     memset(pCsr, 0, sizeof(RtreeCursor));
   145532     pCsr->base.pVtab = pVTab;
   145533     rc = SQLITE_OK;
   145534   }
   145535   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
   145536 
   145537   return rc;
   145538 }
   145539 
   145540 
   145541 /*
   145542 ** Free the RtreeCursor.aConstraint[] array and its contents.
   145543 */
   145544 static void freeCursorConstraints(RtreeCursor *pCsr){
   145545   if( pCsr->aConstraint ){
   145546     int i;                        /* Used to iterate through constraint array */
   145547     for(i=0; i<pCsr->nConstraint; i++){
   145548       sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
   145549       if( pInfo ){
   145550         if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
   145551         sqlite3_free(pInfo);
   145552       }
   145553     }
   145554     sqlite3_free(pCsr->aConstraint);
   145555     pCsr->aConstraint = 0;
   145556   }
   145557 }
   145558 
   145559 /*
   145560 ** Rtree virtual table module xClose method.
   145561 */
   145562 static int rtreeClose(sqlite3_vtab_cursor *cur){
   145563   Rtree *pRtree = (Rtree *)(cur->pVtab);
   145564   int ii;
   145565   RtreeCursor *pCsr = (RtreeCursor *)cur;
   145566   freeCursorConstraints(pCsr);
   145567   sqlite3_free(pCsr->aPoint);
   145568   for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
   145569   sqlite3_free(pCsr);
   145570   return SQLITE_OK;
   145571 }
   145572 
   145573 /*
   145574 ** Rtree virtual table module xEof method.
   145575 **
   145576 ** Return non-zero if the cursor does not currently point to a valid
   145577 ** record (i.e if the scan has finished), or zero otherwise.
   145578 */
   145579 static int rtreeEof(sqlite3_vtab_cursor *cur){
   145580   RtreeCursor *pCsr = (RtreeCursor *)cur;
   145581   return pCsr->atEOF;
   145582 }
   145583 
   145584 /*
   145585 ** Convert raw bits from the on-disk RTree record into a coordinate value.
   145586 ** The on-disk format is big-endian and needs to be converted for little-
   145587 ** endian platforms.  The on-disk record stores integer coordinates if
   145588 ** eInt is true and it stores 32-bit floating point records if eInt is
   145589 ** false.  a[] is the four bytes of the on-disk record to be decoded.
   145590 ** Store the results in "r".
   145591 **
   145592 ** There are three versions of this macro, one each for little-endian and
   145593 ** big-endian processors and a third generic implementation.  The endian-
   145594 ** specific implementations are much faster and are preferred if the
   145595 ** processor endianness is known at compile-time.  The SQLITE_BYTEORDER
   145596 ** macro is part of sqliteInt.h and hence the endian-specific
   145597 ** implementation will only be used if this module is compiled as part
   145598 ** of the amalgamation.
   145599 */
   145600 #if defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==1234
   145601 #define RTREE_DECODE_COORD(eInt, a, r) {                        \
   145602     RtreeCoord c;    /* Coordinate decoded */                   \
   145603     memcpy(&c.u,a,4);                                           \
   145604     c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)|                   \
   145605           ((c.u&0xff)<<24)|((c.u&0xff00)<<8);                   \
   145606     r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
   145607 }
   145608 #elif defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==4321
   145609 #define RTREE_DECODE_COORD(eInt, a, r) {                        \
   145610     RtreeCoord c;    /* Coordinate decoded */                   \
   145611     memcpy(&c.u,a,4);                                           \
   145612     r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
   145613 }
   145614 #else
   145615 #define RTREE_DECODE_COORD(eInt, a, r) {                        \
   145616     RtreeCoord c;    /* Coordinate decoded */                   \
   145617     c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16)                     \
   145618            +((u32)a[2]<<8) + a[3];                              \
   145619     r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
   145620 }
   145621 #endif
   145622 
   145623 /*
   145624 ** Check the RTree node or entry given by pCellData and p against the MATCH
   145625 ** constraint pConstraint.
   145626 */
   145627 static int rtreeCallbackConstraint(
   145628   RtreeConstraint *pConstraint,  /* The constraint to test */
   145629   int eInt,                      /* True if RTree holding integer coordinates */
   145630   u8 *pCellData,                 /* Raw cell content */
   145631   RtreeSearchPoint *pSearch,     /* Container of this cell */
   145632   sqlite3_rtree_dbl *prScore,    /* OUT: score for the cell */
   145633   int *peWithin                  /* OUT: visibility of the cell */
   145634 ){
   145635   int i;                                                /* Loop counter */
   145636   sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
   145637   int nCoord = pInfo->nCoord;                           /* No. of coordinates */
   145638   int rc;                                             /* Callback return code */
   145639   sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2];   /* Decoded coordinates */
   145640 
   145641   assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
   145642   assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
   145643 
   145644   if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
   145645     pInfo->iRowid = readInt64(pCellData);
   145646   }
   145647   pCellData += 8;
   145648   for(i=0; i<nCoord; i++, pCellData += 4){
   145649     RTREE_DECODE_COORD(eInt, pCellData, aCoord[i]);
   145650   }
   145651   if( pConstraint->op==RTREE_MATCH ){
   145652     rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
   145653                               nCoord, aCoord, &i);
   145654     if( i==0 ) *peWithin = NOT_WITHIN;
   145655     *prScore = RTREE_ZERO;
   145656   }else{
   145657     pInfo->aCoord = aCoord;
   145658     pInfo->iLevel = pSearch->iLevel - 1;
   145659     pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
   145660     pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
   145661     rc = pConstraint->u.xQueryFunc(pInfo);
   145662     if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
   145663     if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
   145664       *prScore = pInfo->rScore;
   145665     }
   145666   }
   145667   return rc;
   145668 }
   145669 
   145670 /*
   145671 ** Check the internal RTree node given by pCellData against constraint p.
   145672 ** If this constraint cannot be satisfied by any child within the node,
   145673 ** set *peWithin to NOT_WITHIN.
   145674 */
   145675 static void rtreeNonleafConstraint(
   145676   RtreeConstraint *p,        /* The constraint to test */
   145677   int eInt,                  /* True if RTree holds integer coordinates */
   145678   u8 *pCellData,             /* Raw cell content as appears on disk */
   145679   int *peWithin              /* Adjust downward, as appropriate */
   145680 ){
   145681   sqlite3_rtree_dbl val;     /* Coordinate value convert to a double */
   145682 
   145683   /* p->iCoord might point to either a lower or upper bound coordinate
   145684   ** in a coordinate pair.  But make pCellData point to the lower bound.
   145685   */
   145686   pCellData += 8 + 4*(p->iCoord&0xfe);
   145687 
   145688   assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
   145689       || p->op==RTREE_GT || p->op==RTREE_EQ );
   145690   switch( p->op ){
   145691     case RTREE_LE:
   145692     case RTREE_LT:
   145693     case RTREE_EQ:
   145694       RTREE_DECODE_COORD(eInt, pCellData, val);
   145695       /* val now holds the lower bound of the coordinate pair */
   145696       if( p->u.rValue>=val ) return;
   145697       if( p->op!=RTREE_EQ ) break;  /* RTREE_LE and RTREE_LT end here */
   145698       /* Fall through for the RTREE_EQ case */
   145699 
   145700     default: /* RTREE_GT or RTREE_GE,  or fallthrough of RTREE_EQ */
   145701       pCellData += 4;
   145702       RTREE_DECODE_COORD(eInt, pCellData, val);
   145703       /* val now holds the upper bound of the coordinate pair */
   145704       if( p->u.rValue<=val ) return;
   145705   }
   145706   *peWithin = NOT_WITHIN;
   145707 }
   145708 
   145709 /*
   145710 ** Check the leaf RTree cell given by pCellData against constraint p.
   145711 ** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
   145712 ** If the constraint is satisfied, leave *peWithin unchanged.
   145713 **
   145714 ** The constraint is of the form:  xN op $val
   145715 **
   145716 ** The op is given by p->op.  The xN is p->iCoord-th coordinate in
   145717 ** pCellData.  $val is given by p->u.rValue.
   145718 */
   145719 static void rtreeLeafConstraint(
   145720   RtreeConstraint *p,        /* The constraint to test */
   145721   int eInt,                  /* True if RTree holds integer coordinates */
   145722   u8 *pCellData,             /* Raw cell content as appears on disk */
   145723   int *peWithin              /* Adjust downward, as appropriate */
   145724 ){
   145725   RtreeDValue xN;      /* Coordinate value converted to a double */
   145726 
   145727   assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
   145728       || p->op==RTREE_GT || p->op==RTREE_EQ );
   145729   pCellData += 8 + p->iCoord*4;
   145730   RTREE_DECODE_COORD(eInt, pCellData, xN);
   145731   switch( p->op ){
   145732     case RTREE_LE: if( xN <= p->u.rValue ) return;  break;
   145733     case RTREE_LT: if( xN <  p->u.rValue ) return;  break;
   145734     case RTREE_GE: if( xN >= p->u.rValue ) return;  break;
   145735     case RTREE_GT: if( xN >  p->u.rValue ) return;  break;
   145736     default:       if( xN == p->u.rValue ) return;  break;
   145737   }
   145738   *peWithin = NOT_WITHIN;
   145739 }
   145740 
   145741 /*
   145742 ** One of the cells in node pNode is guaranteed to have a 64-bit
   145743 ** integer value equal to iRowid. Return the index of this cell.
   145744 */
   145745 static int nodeRowidIndex(
   145746   Rtree *pRtree,
   145747   RtreeNode *pNode,
   145748   i64 iRowid,
   145749   int *piIndex
   145750 ){
   145751   int ii;
   145752   int nCell = NCELL(pNode);
   145753   assert( nCell<200 );
   145754   for(ii=0; ii<nCell; ii++){
   145755     if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
   145756       *piIndex = ii;
   145757       return SQLITE_OK;
   145758     }
   145759   }
   145760   return SQLITE_CORRUPT_VTAB;
   145761 }
   145762 
   145763 /*
   145764 ** Return the index of the cell containing a pointer to node pNode
   145765 ** in its parent. If pNode is the root node, return -1.
   145766 */
   145767 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
   145768   RtreeNode *pParent = pNode->pParent;
   145769   if( pParent ){
   145770     return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
   145771   }
   145772   *piIndex = -1;
   145773   return SQLITE_OK;
   145774 }
   145775 
   145776 /*
   145777 ** Compare two search points.  Return negative, zero, or positive if the first
   145778 ** is less than, equal to, or greater than the second.
   145779 **
   145780 ** The rScore is the primary key.  Smaller rScore values come first.
   145781 ** If the rScore is a tie, then use iLevel as the tie breaker with smaller
   145782 ** iLevel values coming first.  In this way, if rScore is the same for all
   145783 ** SearchPoints, then iLevel becomes the deciding factor and the result
   145784 ** is a depth-first search, which is the desired default behavior.
   145785 */
   145786 static int rtreeSearchPointCompare(
   145787   const RtreeSearchPoint *pA,
   145788   const RtreeSearchPoint *pB
   145789 ){
   145790   if( pA->rScore<pB->rScore ) return -1;
   145791   if( pA->rScore>pB->rScore ) return +1;
   145792   if( pA->iLevel<pB->iLevel ) return -1;
   145793   if( pA->iLevel>pB->iLevel ) return +1;
   145794   return 0;
   145795 }
   145796 
   145797 /*
   145798 ** Interchange to search points in a cursor.
   145799 */
   145800 static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
   145801   RtreeSearchPoint t = p->aPoint[i];
   145802   assert( i<j );
   145803   p->aPoint[i] = p->aPoint[j];
   145804   p->aPoint[j] = t;
   145805   i++; j++;
   145806   if( i<RTREE_CACHE_SZ ){
   145807     if( j>=RTREE_CACHE_SZ ){
   145808       nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
   145809       p->aNode[i] = 0;
   145810     }else{
   145811       RtreeNode *pTemp = p->aNode[i];
   145812       p->aNode[i] = p->aNode[j];
   145813       p->aNode[j] = pTemp;
   145814     }
   145815   }
   145816 }
   145817 
   145818 /*
   145819 ** Return the search point with the lowest current score.
   145820 */
   145821 static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
   145822   return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
   145823 }
   145824 
   145825 /*
   145826 ** Get the RtreeNode for the search point with the lowest score.
   145827 */
   145828 static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
   145829   sqlite3_int64 id;
   145830   int ii = 1 - pCur->bPoint;
   145831   assert( ii==0 || ii==1 );
   145832   assert( pCur->bPoint || pCur->nPoint );
   145833   if( pCur->aNode[ii]==0 ){
   145834     assert( pRC!=0 );
   145835     id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
   145836     *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
   145837   }
   145838   return pCur->aNode[ii];
   145839 }
   145840 
   145841 /*
   145842 ** Push a new element onto the priority queue
   145843 */
   145844 static RtreeSearchPoint *rtreeEnqueue(
   145845   RtreeCursor *pCur,    /* The cursor */
   145846   RtreeDValue rScore,   /* Score for the new search point */
   145847   u8 iLevel             /* Level for the new search point */
   145848 ){
   145849   int i, j;
   145850   RtreeSearchPoint *pNew;
   145851   if( pCur->nPoint>=pCur->nPointAlloc ){
   145852     int nNew = pCur->nPointAlloc*2 + 8;
   145853     pNew = sqlite3_realloc(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
   145854     if( pNew==0 ) return 0;
   145855     pCur->aPoint = pNew;
   145856     pCur->nPointAlloc = nNew;
   145857   }
   145858   i = pCur->nPoint++;
   145859   pNew = pCur->aPoint + i;
   145860   pNew->rScore = rScore;
   145861   pNew->iLevel = iLevel;
   145862   assert( iLevel>=0 && iLevel<=RTREE_MAX_DEPTH );
   145863   while( i>0 ){
   145864     RtreeSearchPoint *pParent;
   145865     j = (i-1)/2;
   145866     pParent = pCur->aPoint + j;
   145867     if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
   145868     rtreeSearchPointSwap(pCur, j, i);
   145869     i = j;
   145870     pNew = pParent;
   145871   }
   145872   return pNew;
   145873 }
   145874 
   145875 /*
   145876 ** Allocate a new RtreeSearchPoint and return a pointer to it.  Return
   145877 ** NULL if malloc fails.
   145878 */
   145879 static RtreeSearchPoint *rtreeSearchPointNew(
   145880   RtreeCursor *pCur,    /* The cursor */
   145881   RtreeDValue rScore,   /* Score for the new search point */
   145882   u8 iLevel             /* Level for the new search point */
   145883 ){
   145884   RtreeSearchPoint *pNew, *pFirst;
   145885   pFirst = rtreeSearchPointFirst(pCur);
   145886   pCur->anQueue[iLevel]++;
   145887   if( pFirst==0
   145888    || pFirst->rScore>rScore
   145889    || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
   145890   ){
   145891     if( pCur->bPoint ){
   145892       int ii;
   145893       pNew = rtreeEnqueue(pCur, rScore, iLevel);
   145894       if( pNew==0 ) return 0;
   145895       ii = (int)(pNew - pCur->aPoint) + 1;
   145896       if( ii<RTREE_CACHE_SZ ){
   145897         assert( pCur->aNode[ii]==0 );
   145898         pCur->aNode[ii] = pCur->aNode[0];
   145899        }else{
   145900         nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
   145901       }
   145902       pCur->aNode[0] = 0;
   145903       *pNew = pCur->sPoint;
   145904     }
   145905     pCur->sPoint.rScore = rScore;
   145906     pCur->sPoint.iLevel = iLevel;
   145907     pCur->bPoint = 1;
   145908     return &pCur->sPoint;
   145909   }else{
   145910     return rtreeEnqueue(pCur, rScore, iLevel);
   145911   }
   145912 }
   145913 
   145914 #if 0
   145915 /* Tracing routines for the RtreeSearchPoint queue */
   145916 static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
   145917   if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
   145918   printf(" %d.%05lld.%02d %g %d",
   145919     p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
   145920   );
   145921   idx++;
   145922   if( idx<RTREE_CACHE_SZ ){
   145923     printf(" %p\n", pCur->aNode[idx]);
   145924   }else{
   145925     printf("\n");
   145926   }
   145927 }
   145928 static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
   145929   int ii;
   145930   printf("=== %9s ", zPrefix);
   145931   if( pCur->bPoint ){
   145932     tracePoint(&pCur->sPoint, -1, pCur);
   145933   }
   145934   for(ii=0; ii<pCur->nPoint; ii++){
   145935     if( ii>0 || pCur->bPoint ) printf("              ");
   145936     tracePoint(&pCur->aPoint[ii], ii, pCur);
   145937   }
   145938 }
   145939 # define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
   145940 #else
   145941 # define RTREE_QUEUE_TRACE(A,B)   /* no-op */
   145942 #endif
   145943 
   145944 /* Remove the search point with the lowest current score.
   145945 */
   145946 static void rtreeSearchPointPop(RtreeCursor *p){
   145947   int i, j, k, n;
   145948   i = 1 - p->bPoint;
   145949   assert( i==0 || i==1 );
   145950   if( p->aNode[i] ){
   145951     nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
   145952     p->aNode[i] = 0;
   145953   }
   145954   if( p->bPoint ){
   145955     p->anQueue[p->sPoint.iLevel]--;
   145956     p->bPoint = 0;
   145957   }else if( p->nPoint ){
   145958     p->anQueue[p->aPoint[0].iLevel]--;
   145959     n = --p->nPoint;
   145960     p->aPoint[0] = p->aPoint[n];
   145961     if( n<RTREE_CACHE_SZ-1 ){
   145962       p->aNode[1] = p->aNode[n+1];
   145963       p->aNode[n+1] = 0;
   145964     }
   145965     i = 0;
   145966     while( (j = i*2+1)<n ){
   145967       k = j+1;
   145968       if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
   145969         if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
   145970           rtreeSearchPointSwap(p, i, k);
   145971           i = k;
   145972         }else{
   145973           break;
   145974         }
   145975       }else{
   145976         if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
   145977           rtreeSearchPointSwap(p, i, j);
   145978           i = j;
   145979         }else{
   145980           break;
   145981         }
   145982       }
   145983     }
   145984   }
   145985 }
   145986 
   145987 
   145988 /*
   145989 ** Continue the search on cursor pCur until the front of the queue
   145990 ** contains an entry suitable for returning as a result-set row,
   145991 ** or until the RtreeSearchPoint queue is empty, indicating that the
   145992 ** query has completed.
   145993 */
   145994 static int rtreeStepToLeaf(RtreeCursor *pCur){
   145995   RtreeSearchPoint *p;
   145996   Rtree *pRtree = RTREE_OF_CURSOR(pCur);
   145997   RtreeNode *pNode;
   145998   int eWithin;
   145999   int rc = SQLITE_OK;
   146000   int nCell;
   146001   int nConstraint = pCur->nConstraint;
   146002   int ii;
   146003   int eInt;
   146004   RtreeSearchPoint x;
   146005 
   146006   eInt = pRtree->eCoordType==RTREE_COORD_INT32;
   146007   while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
   146008     pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
   146009     if( rc ) return rc;
   146010     nCell = NCELL(pNode);
   146011     assert( nCell<200 );
   146012     while( p->iCell<nCell ){
   146013       sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
   146014       u8 *pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
   146015       eWithin = FULLY_WITHIN;
   146016       for(ii=0; ii<nConstraint; ii++){
   146017         RtreeConstraint *pConstraint = pCur->aConstraint + ii;
   146018         if( pConstraint->op>=RTREE_MATCH ){
   146019           rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
   146020                                        &rScore, &eWithin);
   146021           if( rc ) return rc;
   146022         }else if( p->iLevel==1 ){
   146023           rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
   146024         }else{
   146025           rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
   146026         }
   146027         if( eWithin==NOT_WITHIN ) break;
   146028       }
   146029       p->iCell++;
   146030       if( eWithin==NOT_WITHIN ) continue;
   146031       x.iLevel = p->iLevel - 1;
   146032       if( x.iLevel ){
   146033         x.id = readInt64(pCellData);
   146034         x.iCell = 0;
   146035       }else{
   146036         x.id = p->id;
   146037         x.iCell = p->iCell - 1;
   146038       }
   146039       if( p->iCell>=nCell ){
   146040         RTREE_QUEUE_TRACE(pCur, "POP-S:");
   146041         rtreeSearchPointPop(pCur);
   146042       }
   146043       if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
   146044       p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
   146045       if( p==0 ) return SQLITE_NOMEM;
   146046       p->eWithin = eWithin;
   146047       p->id = x.id;
   146048       p->iCell = x.iCell;
   146049       RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
   146050       break;
   146051     }
   146052     if( p->iCell>=nCell ){
   146053       RTREE_QUEUE_TRACE(pCur, "POP-Se:");
   146054       rtreeSearchPointPop(pCur);
   146055     }
   146056   }
   146057   pCur->atEOF = p==0;
   146058   return SQLITE_OK;
   146059 }
   146060 
   146061 /*
   146062 ** Rtree virtual table module xNext method.
   146063 */
   146064 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
   146065   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
   146066   int rc = SQLITE_OK;
   146067 
   146068   /* Move to the next entry that matches the configured constraints. */
   146069   RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
   146070   rtreeSearchPointPop(pCsr);
   146071   rc = rtreeStepToLeaf(pCsr);
   146072   return rc;
   146073 }
   146074 
   146075 /*
   146076 ** Rtree virtual table module xRowid method.
   146077 */
   146078 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
   146079   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
   146080   RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
   146081   int rc = SQLITE_OK;
   146082   RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
   146083   if( rc==SQLITE_OK && p ){
   146084     *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
   146085   }
   146086   return rc;
   146087 }
   146088 
   146089 /*
   146090 ** Rtree virtual table module xColumn method.
   146091 */
   146092 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
   146093   Rtree *pRtree = (Rtree *)cur->pVtab;
   146094   RtreeCursor *pCsr = (RtreeCursor *)cur;
   146095   RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
   146096   RtreeCoord c;
   146097   int rc = SQLITE_OK;
   146098   RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
   146099 
   146100   if( rc ) return rc;
   146101   if( p==0 ) return SQLITE_OK;
   146102   if( i==0 ){
   146103     sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
   146104   }else{
   146105     if( rc ) return rc;
   146106     nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
   146107 #ifndef SQLITE_RTREE_INT_ONLY
   146108     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
   146109       sqlite3_result_double(ctx, c.f);
   146110     }else
   146111 #endif
   146112     {
   146113       assert( pRtree->eCoordType==RTREE_COORD_INT32 );
   146114       sqlite3_result_int(ctx, c.i);
   146115     }
   146116   }
   146117   return SQLITE_OK;
   146118 }
   146119 
   146120 /*
   146121 ** Use nodeAcquire() to obtain the leaf node containing the record with
   146122 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
   146123 ** return SQLITE_OK. If there is no such record in the table, set
   146124 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
   146125 ** to zero and return an SQLite error code.
   146126 */
   146127 static int findLeafNode(
   146128   Rtree *pRtree,              /* RTree to search */
   146129   i64 iRowid,                 /* The rowid searching for */
   146130   RtreeNode **ppLeaf,         /* Write the node here */
   146131   sqlite3_int64 *piNode       /* Write the node-id here */
   146132 ){
   146133   int rc;
   146134   *ppLeaf = 0;
   146135   sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
   146136   if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
   146137     i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
   146138     if( piNode ) *piNode = iNode;
   146139     rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
   146140     sqlite3_reset(pRtree->pReadRowid);
   146141   }else{
   146142     rc = sqlite3_reset(pRtree->pReadRowid);
   146143   }
   146144   return rc;
   146145 }
   146146 
   146147 /*
   146148 ** This function is called to configure the RtreeConstraint object passed
   146149 ** as the second argument for a MATCH constraint. The value passed as the
   146150 ** first argument to this function is the right-hand operand to the MATCH
   146151 ** operator.
   146152 */
   146153 static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
   146154   RtreeMatchArg *pBlob;              /* BLOB returned by geometry function */
   146155   sqlite3_rtree_query_info *pInfo;   /* Callback information */
   146156   int nBlob;                         /* Size of the geometry function blob */
   146157   int nExpected;                     /* Expected size of the BLOB */
   146158 
   146159   /* Check that value is actually a blob. */
   146160   if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
   146161 
   146162   /* Check that the blob is roughly the right size. */
   146163   nBlob = sqlite3_value_bytes(pValue);
   146164   if( nBlob<(int)sizeof(RtreeMatchArg)
   146165    || ((nBlob-sizeof(RtreeMatchArg))%sizeof(RtreeDValue))!=0
   146166   ){
   146167     return SQLITE_ERROR;
   146168   }
   146169 
   146170   pInfo = (sqlite3_rtree_query_info*)sqlite3_malloc( sizeof(*pInfo)+nBlob );
   146171   if( !pInfo ) return SQLITE_NOMEM;
   146172   memset(pInfo, 0, sizeof(*pInfo));
   146173   pBlob = (RtreeMatchArg*)&pInfo[1];
   146174 
   146175   memcpy(pBlob, sqlite3_value_blob(pValue), nBlob);
   146176   nExpected = (int)(sizeof(RtreeMatchArg) +
   146177                     (pBlob->nParam-1)*sizeof(RtreeDValue));
   146178   if( pBlob->magic!=RTREE_GEOMETRY_MAGIC || nBlob!=nExpected ){
   146179     sqlite3_free(pInfo);
   146180     return SQLITE_ERROR;
   146181   }
   146182   pInfo->pContext = pBlob->cb.pContext;
   146183   pInfo->nParam = pBlob->nParam;
   146184   pInfo->aParam = pBlob->aParam;
   146185 
   146186   if( pBlob->cb.xGeom ){
   146187     pCons->u.xGeom = pBlob->cb.xGeom;
   146188   }else{
   146189     pCons->op = RTREE_QUERY;
   146190     pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
   146191   }
   146192   pCons->pInfo = pInfo;
   146193   return SQLITE_OK;
   146194 }
   146195 
   146196 /*
   146197 ** Rtree virtual table module xFilter method.
   146198 */
   146199 static int rtreeFilter(
   146200   sqlite3_vtab_cursor *pVtabCursor,
   146201   int idxNum, const char *idxStr,
   146202   int argc, sqlite3_value **argv
   146203 ){
   146204   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
   146205   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
   146206   RtreeNode *pRoot = 0;
   146207   int ii;
   146208   int rc = SQLITE_OK;
   146209   int iCell = 0;
   146210 
   146211   rtreeReference(pRtree);
   146212 
   146213   /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
   146214   freeCursorConstraints(pCsr);
   146215   sqlite3_free(pCsr->aPoint);
   146216   memset(pCsr, 0, sizeof(RtreeCursor));
   146217   pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
   146218 
   146219   pCsr->iStrategy = idxNum;
   146220   if( idxNum==1 ){
   146221     /* Special case - lookup by rowid. */
   146222     RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
   146223     RtreeSearchPoint *p;     /* Search point for the the leaf */
   146224     i64 iRowid = sqlite3_value_int64(argv[0]);
   146225     i64 iNode = 0;
   146226     rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
   146227     if( rc==SQLITE_OK && pLeaf!=0 ){
   146228       p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
   146229       assert( p!=0 );  /* Always returns pCsr->sPoint */
   146230       pCsr->aNode[0] = pLeaf;
   146231       p->id = iNode;
   146232       p->eWithin = PARTLY_WITHIN;
   146233       rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
   146234       p->iCell = iCell;
   146235       RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
   146236     }else{
   146237       pCsr->atEOF = 1;
   146238     }
   146239   }else{
   146240     /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
   146241     ** with the configured constraints.
   146242     */
   146243     rc = nodeAcquire(pRtree, 1, 0, &pRoot);
   146244     if( rc==SQLITE_OK && argc>0 ){
   146245       pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
   146246       pCsr->nConstraint = argc;
   146247       if( !pCsr->aConstraint ){
   146248         rc = SQLITE_NOMEM;
   146249       }else{
   146250         memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
   146251         memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
   146252         assert( (idxStr==0 && argc==0)
   146253                 || (idxStr && (int)strlen(idxStr)==argc*2) );
   146254         for(ii=0; ii<argc; ii++){
   146255           RtreeConstraint *p = &pCsr->aConstraint[ii];
   146256           p->op = idxStr[ii*2];
   146257           p->iCoord = idxStr[ii*2+1]-'0';
   146258           if( p->op>=RTREE_MATCH ){
   146259             /* A MATCH operator. The right-hand-side must be a blob that
   146260             ** can be cast into an RtreeMatchArg object. One created using
   146261             ** an sqlite3_rtree_geometry_callback() SQL user function.
   146262             */
   146263             rc = deserializeGeometry(argv[ii], p);
   146264             if( rc!=SQLITE_OK ){
   146265               break;
   146266             }
   146267             p->pInfo->nCoord = pRtree->nDim*2;
   146268             p->pInfo->anQueue = pCsr->anQueue;
   146269             p->pInfo->mxLevel = pRtree->iDepth + 1;
   146270           }else{
   146271 #ifdef SQLITE_RTREE_INT_ONLY
   146272             p->u.rValue = sqlite3_value_int64(argv[ii]);
   146273 #else
   146274             p->u.rValue = sqlite3_value_double(argv[ii]);
   146275 #endif
   146276           }
   146277         }
   146278       }
   146279     }
   146280     if( rc==SQLITE_OK ){
   146281       RtreeSearchPoint *pNew;
   146282       pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, pRtree->iDepth+1);
   146283       if( pNew==0 ) return SQLITE_NOMEM;
   146284       pNew->id = 1;
   146285       pNew->iCell = 0;
   146286       pNew->eWithin = PARTLY_WITHIN;
   146287       assert( pCsr->bPoint==1 );
   146288       pCsr->aNode[0] = pRoot;
   146289       pRoot = 0;
   146290       RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
   146291       rc = rtreeStepToLeaf(pCsr);
   146292     }
   146293   }
   146294 
   146295   nodeRelease(pRtree, pRoot);
   146296   rtreeRelease(pRtree);
   146297   return rc;
   146298 }
   146299 
   146300 /*
   146301 ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
   146302 ** extension is currently being used by a version of SQLite too old to
   146303 ** support estimatedRows. In that case this function is a no-op.
   146304 */
   146305 static void setEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
   146306 #if SQLITE_VERSION_NUMBER>=3008002
   146307   if( sqlite3_libversion_number()>=3008002 ){
   146308     pIdxInfo->estimatedRows = nRow;
   146309   }
   146310 #endif
   146311 }
   146312 
   146313 /*
   146314 ** Rtree virtual table module xBestIndex method. There are three
   146315 ** table scan strategies to choose from (in order from most to
   146316 ** least desirable):
   146317 **
   146318 **   idxNum     idxStr        Strategy
   146319 **   ------------------------------------------------
   146320 **     1        Unused        Direct lookup by rowid.
   146321 **     2        See below     R-tree query or full-table scan.
   146322 **   ------------------------------------------------
   146323 **
   146324 ** If strategy 1 is used, then idxStr is not meaningful. If strategy
   146325 ** 2 is used, idxStr is formatted to contain 2 bytes for each
   146326 ** constraint used. The first two bytes of idxStr correspond to
   146327 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
   146328 ** (argvIndex==1) etc.
   146329 **
   146330 ** The first of each pair of bytes in idxStr identifies the constraint
   146331 ** operator as follows:
   146332 **
   146333 **   Operator    Byte Value
   146334 **   ----------------------
   146335 **      =        0x41 ('A')
   146336 **     <=        0x42 ('B')
   146337 **      <        0x43 ('C')
   146338 **     >=        0x44 ('D')
   146339 **      >        0x45 ('E')
   146340 **   MATCH       0x46 ('F')
   146341 **   ----------------------
   146342 **
   146343 ** The second of each pair of bytes identifies the coordinate column
   146344 ** to which the constraint applies. The leftmost coordinate column
   146345 ** is 'a', the second from the left 'b' etc.
   146346 */
   146347 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
   146348   Rtree *pRtree = (Rtree*)tab;
   146349   int rc = SQLITE_OK;
   146350   int ii;
   146351   i64 nRow;                       /* Estimated rows returned by this scan */
   146352 
   146353   int iIdx = 0;
   146354   char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
   146355   memset(zIdxStr, 0, sizeof(zIdxStr));
   146356 
   146357   assert( pIdxInfo->idxStr==0 );
   146358   for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
   146359     struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
   146360 
   146361     if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
   146362       /* We have an equality constraint on the rowid. Use strategy 1. */
   146363       int jj;
   146364       for(jj=0; jj<ii; jj++){
   146365         pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
   146366         pIdxInfo->aConstraintUsage[jj].omit = 0;
   146367       }
   146368       pIdxInfo->idxNum = 1;
   146369       pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
   146370       pIdxInfo->aConstraintUsage[jj].omit = 1;
   146371 
   146372       /* This strategy involves a two rowid lookups on an B-Tree structures
   146373       ** and then a linear search of an R-Tree node. This should be
   146374       ** considered almost as quick as a direct rowid lookup (for which
   146375       ** sqlite uses an internal cost of 0.0). It is expected to return
   146376       ** a single row.
   146377       */
   146378       pIdxInfo->estimatedCost = 30.0;
   146379       setEstimatedRows(pIdxInfo, 1);
   146380       return SQLITE_OK;
   146381     }
   146382 
   146383     if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
   146384       u8 op;
   146385       switch( p->op ){
   146386         case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
   146387         case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
   146388         case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
   146389         case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
   146390         case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
   146391         default:
   146392           assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
   146393           op = RTREE_MATCH;
   146394           break;
   146395       }
   146396       zIdxStr[iIdx++] = op;
   146397       zIdxStr[iIdx++] = p->iColumn - 1 + '0';
   146398       pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
   146399       pIdxInfo->aConstraintUsage[ii].omit = 1;
   146400     }
   146401   }
   146402 
   146403   pIdxInfo->idxNum = 2;
   146404   pIdxInfo->needToFreeIdxStr = 1;
   146405   if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
   146406     return SQLITE_NOMEM;
   146407   }
   146408 
   146409   nRow = pRtree->nRowEst / (iIdx + 1);
   146410   pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
   146411   setEstimatedRows(pIdxInfo, nRow);
   146412 
   146413   return rc;
   146414 }
   146415 
   146416 /*
   146417 ** Return the N-dimensional volumn of the cell stored in *p.
   146418 */
   146419 static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
   146420   RtreeDValue area = (RtreeDValue)1;
   146421   int ii;
   146422   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
   146423     area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
   146424   }
   146425   return area;
   146426 }
   146427 
   146428 /*
   146429 ** Return the margin length of cell p. The margin length is the sum
   146430 ** of the objects size in each dimension.
   146431 */
   146432 static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
   146433   RtreeDValue margin = (RtreeDValue)0;
   146434   int ii;
   146435   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
   146436     margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
   146437   }
   146438   return margin;
   146439 }
   146440 
   146441 /*
   146442 ** Store the union of cells p1 and p2 in p1.
   146443 */
   146444 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
   146445   int ii;
   146446   if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
   146447     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
   146448       p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
   146449       p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
   146450     }
   146451   }else{
   146452     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
   146453       p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
   146454       p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
   146455     }
   146456   }
   146457 }
   146458 
   146459 /*
   146460 ** Return true if the area covered by p2 is a subset of the area covered
   146461 ** by p1. False otherwise.
   146462 */
   146463 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
   146464   int ii;
   146465   int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
   146466   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
   146467     RtreeCoord *a1 = &p1->aCoord[ii];
   146468     RtreeCoord *a2 = &p2->aCoord[ii];
   146469     if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
   146470      || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
   146471     ){
   146472       return 0;
   146473     }
   146474   }
   146475   return 1;
   146476 }
   146477 
   146478 /*
   146479 ** Return the amount cell p would grow by if it were unioned with pCell.
   146480 */
   146481 static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
   146482   RtreeDValue area;
   146483   RtreeCell cell;
   146484   memcpy(&cell, p, sizeof(RtreeCell));
   146485   area = cellArea(pRtree, &cell);
   146486   cellUnion(pRtree, &cell, pCell);
   146487   return (cellArea(pRtree, &cell)-area);
   146488 }
   146489 
   146490 static RtreeDValue cellOverlap(
   146491   Rtree *pRtree,
   146492   RtreeCell *p,
   146493   RtreeCell *aCell,
   146494   int nCell
   146495 ){
   146496   int ii;
   146497   RtreeDValue overlap = RTREE_ZERO;
   146498   for(ii=0; ii<nCell; ii++){
   146499     int jj;
   146500     RtreeDValue o = (RtreeDValue)1;
   146501     for(jj=0; jj<(pRtree->nDim*2); jj+=2){
   146502       RtreeDValue x1, x2;
   146503       x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
   146504       x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
   146505       if( x2<x1 ){
   146506         o = (RtreeDValue)0;
   146507         break;
   146508       }else{
   146509         o = o * (x2-x1);
   146510       }
   146511     }
   146512     overlap += o;
   146513   }
   146514   return overlap;
   146515 }
   146516 
   146517 
   146518 /*
   146519 ** This function implements the ChooseLeaf algorithm from Gutman[84].
   146520 ** ChooseSubTree in r*tree terminology.
   146521 */
   146522 static int ChooseLeaf(
   146523   Rtree *pRtree,               /* Rtree table */
   146524   RtreeCell *pCell,            /* Cell to insert into rtree */
   146525   int iHeight,                 /* Height of sub-tree rooted at pCell */
   146526   RtreeNode **ppLeaf           /* OUT: Selected leaf page */
   146527 ){
   146528   int rc;
   146529   int ii;
   146530   RtreeNode *pNode;
   146531   rc = nodeAcquire(pRtree, 1, 0, &pNode);
   146532 
   146533   for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
   146534     int iCell;
   146535     sqlite3_int64 iBest = 0;
   146536 
   146537     RtreeDValue fMinGrowth = RTREE_ZERO;
   146538     RtreeDValue fMinArea = RTREE_ZERO;
   146539 
   146540     int nCell = NCELL(pNode);
   146541     RtreeCell cell;
   146542     RtreeNode *pChild;
   146543 
   146544     RtreeCell *aCell = 0;
   146545 
   146546     /* Select the child node which will be enlarged the least if pCell
   146547     ** is inserted into it. Resolve ties by choosing the entry with
   146548     ** the smallest area.
   146549     */
   146550     for(iCell=0; iCell<nCell; iCell++){
   146551       int bBest = 0;
   146552       RtreeDValue growth;
   146553       RtreeDValue area;
   146554       nodeGetCell(pRtree, pNode, iCell, &cell);
   146555       growth = cellGrowth(pRtree, &cell, pCell);
   146556       area = cellArea(pRtree, &cell);
   146557       if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
   146558         bBest = 1;
   146559       }
   146560       if( bBest ){
   146561         fMinGrowth = growth;
   146562         fMinArea = area;
   146563         iBest = cell.iRowid;
   146564       }
   146565     }
   146566 
   146567     sqlite3_free(aCell);
   146568     rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
   146569     nodeRelease(pRtree, pNode);
   146570     pNode = pChild;
   146571   }
   146572 
   146573   *ppLeaf = pNode;
   146574   return rc;
   146575 }
   146576 
   146577 /*
   146578 ** A cell with the same content as pCell has just been inserted into
   146579 ** the node pNode. This function updates the bounding box cells in
   146580 ** all ancestor elements.
   146581 */
   146582 static int AdjustTree(
   146583   Rtree *pRtree,                    /* Rtree table */
   146584   RtreeNode *pNode,                 /* Adjust ancestry of this node. */
   146585   RtreeCell *pCell                  /* This cell was just inserted */
   146586 ){
   146587   RtreeNode *p = pNode;
   146588   while( p->pParent ){
   146589     RtreeNode *pParent = p->pParent;
   146590     RtreeCell cell;
   146591     int iCell;
   146592 
   146593     if( nodeParentIndex(pRtree, p, &iCell) ){
   146594       return SQLITE_CORRUPT_VTAB;
   146595     }
   146596 
   146597     nodeGetCell(pRtree, pParent, iCell, &cell);
   146598     if( !cellContains(pRtree, &cell, pCell) ){
   146599       cellUnion(pRtree, &cell, pCell);
   146600       nodeOverwriteCell(pRtree, pParent, &cell, iCell);
   146601     }
   146602 
   146603     p = pParent;
   146604   }
   146605   return SQLITE_OK;
   146606 }
   146607 
   146608 /*
   146609 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
   146610 */
   146611 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
   146612   sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
   146613   sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
   146614   sqlite3_step(pRtree->pWriteRowid);
   146615   return sqlite3_reset(pRtree->pWriteRowid);
   146616 }
   146617 
   146618 /*
   146619 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
   146620 */
   146621 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
   146622   sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
   146623   sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
   146624   sqlite3_step(pRtree->pWriteParent);
   146625   return sqlite3_reset(pRtree->pWriteParent);
   146626 }
   146627 
   146628 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
   146629 
   146630 
   146631 /*
   146632 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
   146633 ** nIdx. The aIdx array contains the set of integers from 0 to
   146634 ** (nIdx-1) in no particular order. This function sorts the values
   146635 ** in aIdx according to the indexed values in aDistance. For
   146636 ** example, assuming the inputs:
   146637 **
   146638 **   aIdx      = { 0,   1,   2,   3 }
   146639 **   aDistance = { 5.0, 2.0, 7.0, 6.0 }
   146640 **
   146641 ** this function sets the aIdx array to contain:
   146642 **
   146643 **   aIdx      = { 0,   1,   2,   3 }
   146644 **
   146645 ** The aSpare array is used as temporary working space by the
   146646 ** sorting algorithm.
   146647 */
   146648 static void SortByDistance(
   146649   int *aIdx,
   146650   int nIdx,
   146651   RtreeDValue *aDistance,
   146652   int *aSpare
   146653 ){
   146654   if( nIdx>1 ){
   146655     int iLeft = 0;
   146656     int iRight = 0;
   146657 
   146658     int nLeft = nIdx/2;
   146659     int nRight = nIdx-nLeft;
   146660     int *aLeft = aIdx;
   146661     int *aRight = &aIdx[nLeft];
   146662 
   146663     SortByDistance(aLeft, nLeft, aDistance, aSpare);
   146664     SortByDistance(aRight, nRight, aDistance, aSpare);
   146665 
   146666     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
   146667     aLeft = aSpare;
   146668 
   146669     while( iLeft<nLeft || iRight<nRight ){
   146670       if( iLeft==nLeft ){
   146671         aIdx[iLeft+iRight] = aRight[iRight];
   146672         iRight++;
   146673       }else if( iRight==nRight ){
   146674         aIdx[iLeft+iRight] = aLeft[iLeft];
   146675         iLeft++;
   146676       }else{
   146677         RtreeDValue fLeft = aDistance[aLeft[iLeft]];
   146678         RtreeDValue fRight = aDistance[aRight[iRight]];
   146679         if( fLeft<fRight ){
   146680           aIdx[iLeft+iRight] = aLeft[iLeft];
   146681           iLeft++;
   146682         }else{
   146683           aIdx[iLeft+iRight] = aRight[iRight];
   146684           iRight++;
   146685         }
   146686       }
   146687     }
   146688 
   146689 #if 0
   146690     /* Check that the sort worked */
   146691     {
   146692       int jj;
   146693       for(jj=1; jj<nIdx; jj++){
   146694         RtreeDValue left = aDistance[aIdx[jj-1]];
   146695         RtreeDValue right = aDistance[aIdx[jj]];
   146696         assert( left<=right );
   146697       }
   146698     }
   146699 #endif
   146700   }
   146701 }
   146702 
   146703 /*
   146704 ** Arguments aIdx, aCell and aSpare all point to arrays of size
   146705 ** nIdx. The aIdx array contains the set of integers from 0 to
   146706 ** (nIdx-1) in no particular order. This function sorts the values
   146707 ** in aIdx according to dimension iDim of the cells in aCell. The
   146708 ** minimum value of dimension iDim is considered first, the
   146709 ** maximum used to break ties.
   146710 **
   146711 ** The aSpare array is used as temporary working space by the
   146712 ** sorting algorithm.
   146713 */
   146714 static void SortByDimension(
   146715   Rtree *pRtree,
   146716   int *aIdx,
   146717   int nIdx,
   146718   int iDim,
   146719   RtreeCell *aCell,
   146720   int *aSpare
   146721 ){
   146722   if( nIdx>1 ){
   146723 
   146724     int iLeft = 0;
   146725     int iRight = 0;
   146726 
   146727     int nLeft = nIdx/2;
   146728     int nRight = nIdx-nLeft;
   146729     int *aLeft = aIdx;
   146730     int *aRight = &aIdx[nLeft];
   146731 
   146732     SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
   146733     SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
   146734 
   146735     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
   146736     aLeft = aSpare;
   146737     while( iLeft<nLeft || iRight<nRight ){
   146738       RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
   146739       RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
   146740       RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
   146741       RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
   146742       if( (iLeft!=nLeft) && ((iRight==nRight)
   146743        || (xleft1<xright1)
   146744        || (xleft1==xright1 && xleft2<xright2)
   146745       )){
   146746         aIdx[iLeft+iRight] = aLeft[iLeft];
   146747         iLeft++;
   146748       }else{
   146749         aIdx[iLeft+iRight] = aRight[iRight];
   146750         iRight++;
   146751       }
   146752     }
   146753 
   146754 #if 0
   146755     /* Check that the sort worked */
   146756     {
   146757       int jj;
   146758       for(jj=1; jj<nIdx; jj++){
   146759         RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
   146760         RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
   146761         RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
   146762         RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
   146763         assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
   146764       }
   146765     }
   146766 #endif
   146767   }
   146768 }
   146769 
   146770 /*
   146771 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
   146772 */
   146773 static int splitNodeStartree(
   146774   Rtree *pRtree,
   146775   RtreeCell *aCell,
   146776   int nCell,
   146777   RtreeNode *pLeft,
   146778   RtreeNode *pRight,
   146779   RtreeCell *pBboxLeft,
   146780   RtreeCell *pBboxRight
   146781 ){
   146782   int **aaSorted;
   146783   int *aSpare;
   146784   int ii;
   146785 
   146786   int iBestDim = 0;
   146787   int iBestSplit = 0;
   146788   RtreeDValue fBestMargin = RTREE_ZERO;
   146789 
   146790   int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
   146791 
   146792   aaSorted = (int **)sqlite3_malloc(nByte);
   146793   if( !aaSorted ){
   146794     return SQLITE_NOMEM;
   146795   }
   146796 
   146797   aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
   146798   memset(aaSorted, 0, nByte);
   146799   for(ii=0; ii<pRtree->nDim; ii++){
   146800     int jj;
   146801     aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
   146802     for(jj=0; jj<nCell; jj++){
   146803       aaSorted[ii][jj] = jj;
   146804     }
   146805     SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
   146806   }
   146807 
   146808   for(ii=0; ii<pRtree->nDim; ii++){
   146809     RtreeDValue margin = RTREE_ZERO;
   146810     RtreeDValue fBestOverlap = RTREE_ZERO;
   146811     RtreeDValue fBestArea = RTREE_ZERO;
   146812     int iBestLeft = 0;
   146813     int nLeft;
   146814 
   146815     for(
   146816       nLeft=RTREE_MINCELLS(pRtree);
   146817       nLeft<=(nCell-RTREE_MINCELLS(pRtree));
   146818       nLeft++
   146819     ){
   146820       RtreeCell left;
   146821       RtreeCell right;
   146822       int kk;
   146823       RtreeDValue overlap;
   146824       RtreeDValue area;
   146825 
   146826       memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
   146827       memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
   146828       for(kk=1; kk<(nCell-1); kk++){
   146829         if( kk<nLeft ){
   146830           cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
   146831         }else{
   146832           cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
   146833         }
   146834       }
   146835       margin += cellMargin(pRtree, &left);
   146836       margin += cellMargin(pRtree, &right);
   146837       overlap = cellOverlap(pRtree, &left, &right, 1);
   146838       area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
   146839       if( (nLeft==RTREE_MINCELLS(pRtree))
   146840        || (overlap<fBestOverlap)
   146841        || (overlap==fBestOverlap && area<fBestArea)
   146842       ){
   146843         iBestLeft = nLeft;
   146844         fBestOverlap = overlap;
   146845         fBestArea = area;
   146846       }
   146847     }
   146848 
   146849     if( ii==0 || margin<fBestMargin ){
   146850       iBestDim = ii;
   146851       fBestMargin = margin;
   146852       iBestSplit = iBestLeft;
   146853     }
   146854   }
   146855 
   146856   memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
   146857   memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
   146858   for(ii=0; ii<nCell; ii++){
   146859     RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
   146860     RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
   146861     RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
   146862     nodeInsertCell(pRtree, pTarget, pCell);
   146863     cellUnion(pRtree, pBbox, pCell);
   146864   }
   146865 
   146866   sqlite3_free(aaSorted);
   146867   return SQLITE_OK;
   146868 }
   146869 
   146870 
   146871 static int updateMapping(
   146872   Rtree *pRtree,
   146873   i64 iRowid,
   146874   RtreeNode *pNode,
   146875   int iHeight
   146876 ){
   146877   int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
   146878   xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
   146879   if( iHeight>0 ){
   146880     RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
   146881     if( pChild ){
   146882       nodeRelease(pRtree, pChild->pParent);
   146883       nodeReference(pNode);
   146884       pChild->pParent = pNode;
   146885     }
   146886   }
   146887   return xSetMapping(pRtree, iRowid, pNode->iNode);
   146888 }
   146889 
   146890 static int SplitNode(
   146891   Rtree *pRtree,
   146892   RtreeNode *pNode,
   146893   RtreeCell *pCell,
   146894   int iHeight
   146895 ){
   146896   int i;
   146897   int newCellIsRight = 0;
   146898 
   146899   int rc = SQLITE_OK;
   146900   int nCell = NCELL(pNode);
   146901   RtreeCell *aCell;
   146902   int *aiUsed;
   146903 
   146904   RtreeNode *pLeft = 0;
   146905   RtreeNode *pRight = 0;
   146906 
   146907   RtreeCell leftbbox;
   146908   RtreeCell rightbbox;
   146909 
   146910   /* Allocate an array and populate it with a copy of pCell and
   146911   ** all cells from node pLeft. Then zero the original node.
   146912   */
   146913   aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
   146914   if( !aCell ){
   146915     rc = SQLITE_NOMEM;
   146916     goto splitnode_out;
   146917   }
   146918   aiUsed = (int *)&aCell[nCell+1];
   146919   memset(aiUsed, 0, sizeof(int)*(nCell+1));
   146920   for(i=0; i<nCell; i++){
   146921     nodeGetCell(pRtree, pNode, i, &aCell[i]);
   146922   }
   146923   nodeZero(pRtree, pNode);
   146924   memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
   146925   nCell++;
   146926 
   146927   if( pNode->iNode==1 ){
   146928     pRight = nodeNew(pRtree, pNode);
   146929     pLeft = nodeNew(pRtree, pNode);
   146930     pRtree->iDepth++;
   146931     pNode->isDirty = 1;
   146932     writeInt16(pNode->zData, pRtree->iDepth);
   146933   }else{
   146934     pLeft = pNode;
   146935     pRight = nodeNew(pRtree, pLeft->pParent);
   146936     nodeReference(pLeft);
   146937   }
   146938 
   146939   if( !pLeft || !pRight ){
   146940     rc = SQLITE_NOMEM;
   146941     goto splitnode_out;
   146942   }
   146943 
   146944   memset(pLeft->zData, 0, pRtree->iNodeSize);
   146945   memset(pRight->zData, 0, pRtree->iNodeSize);
   146946 
   146947   rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
   146948                          &leftbbox, &rightbbox);
   146949   if( rc!=SQLITE_OK ){
   146950     goto splitnode_out;
   146951   }
   146952 
   146953   /* Ensure both child nodes have node numbers assigned to them by calling
   146954   ** nodeWrite(). Node pRight always needs a node number, as it was created
   146955   ** by nodeNew() above. But node pLeft sometimes already has a node number.
   146956   ** In this case avoid the all to nodeWrite().
   146957   */
   146958   if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
   146959    || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
   146960   ){
   146961     goto splitnode_out;
   146962   }
   146963 
   146964   rightbbox.iRowid = pRight->iNode;
   146965   leftbbox.iRowid = pLeft->iNode;
   146966 
   146967   if( pNode->iNode==1 ){
   146968     rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
   146969     if( rc!=SQLITE_OK ){
   146970       goto splitnode_out;
   146971     }
   146972   }else{
   146973     RtreeNode *pParent = pLeft->pParent;
   146974     int iCell;
   146975     rc = nodeParentIndex(pRtree, pLeft, &iCell);
   146976     if( rc==SQLITE_OK ){
   146977       nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
   146978       rc = AdjustTree(pRtree, pParent, &leftbbox);
   146979     }
   146980     if( rc!=SQLITE_OK ){
   146981       goto splitnode_out;
   146982     }
   146983   }
   146984   if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
   146985     goto splitnode_out;
   146986   }
   146987 
   146988   for(i=0; i<NCELL(pRight); i++){
   146989     i64 iRowid = nodeGetRowid(pRtree, pRight, i);
   146990     rc = updateMapping(pRtree, iRowid, pRight, iHeight);
   146991     if( iRowid==pCell->iRowid ){
   146992       newCellIsRight = 1;
   146993     }
   146994     if( rc!=SQLITE_OK ){
   146995       goto splitnode_out;
   146996     }
   146997   }
   146998   if( pNode->iNode==1 ){
   146999     for(i=0; i<NCELL(pLeft); i++){
   147000       i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
   147001       rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
   147002       if( rc!=SQLITE_OK ){
   147003         goto splitnode_out;
   147004       }
   147005     }
   147006   }else if( newCellIsRight==0 ){
   147007     rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
   147008   }
   147009 
   147010   if( rc==SQLITE_OK ){
   147011     rc = nodeRelease(pRtree, pRight);
   147012     pRight = 0;
   147013   }
   147014   if( rc==SQLITE_OK ){
   147015     rc = nodeRelease(pRtree, pLeft);
   147016     pLeft = 0;
   147017   }
   147018 
   147019 splitnode_out:
   147020   nodeRelease(pRtree, pRight);
   147021   nodeRelease(pRtree, pLeft);
   147022   sqlite3_free(aCell);
   147023   return rc;
   147024 }
   147025 
   147026 /*
   147027 ** If node pLeaf is not the root of the r-tree and its pParent pointer is
   147028 ** still NULL, load all ancestor nodes of pLeaf into memory and populate
   147029 ** the pLeaf->pParent chain all the way up to the root node.
   147030 **
   147031 ** This operation is required when a row is deleted (or updated - an update
   147032 ** is implemented as a delete followed by an insert). SQLite provides the
   147033 ** rowid of the row to delete, which can be used to find the leaf on which
   147034 ** the entry resides (argument pLeaf). Once the leaf is located, this
   147035 ** function is called to determine its ancestry.
   147036 */
   147037 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
   147038   int rc = SQLITE_OK;
   147039   RtreeNode *pChild = pLeaf;
   147040   while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
   147041     int rc2 = SQLITE_OK;          /* sqlite3_reset() return code */
   147042     sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
   147043     rc = sqlite3_step(pRtree->pReadParent);
   147044     if( rc==SQLITE_ROW ){
   147045       RtreeNode *pTest;           /* Used to test for reference loops */
   147046       i64 iNode;                  /* Node number of parent node */
   147047 
   147048       /* Before setting pChild->pParent, test that we are not creating a
   147049       ** loop of references (as we would if, say, pChild==pParent). We don't
   147050       ** want to do this as it leads to a memory leak when trying to delete
   147051       ** the referenced counted node structures.
   147052       */
   147053       iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
   147054       for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
   147055       if( !pTest ){
   147056         rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
   147057       }
   147058     }
   147059     rc = sqlite3_reset(pRtree->pReadParent);
   147060     if( rc==SQLITE_OK ) rc = rc2;
   147061     if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
   147062     pChild = pChild->pParent;
   147063   }
   147064   return rc;
   147065 }
   147066 
   147067 static int deleteCell(Rtree *, RtreeNode *, int, int);
   147068 
   147069 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
   147070   int rc;
   147071   int rc2;
   147072   RtreeNode *pParent = 0;
   147073   int iCell;
   147074 
   147075   assert( pNode->nRef==1 );
   147076 
   147077   /* Remove the entry in the parent cell. */
   147078   rc = nodeParentIndex(pRtree, pNode, &iCell);
   147079   if( rc==SQLITE_OK ){
   147080     pParent = pNode->pParent;
   147081     pNode->pParent = 0;
   147082     rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
   147083   }
   147084   rc2 = nodeRelease(pRtree, pParent);
   147085   if( rc==SQLITE_OK ){
   147086     rc = rc2;
   147087   }
   147088   if( rc!=SQLITE_OK ){
   147089     return rc;
   147090   }
   147091 
   147092   /* Remove the xxx_node entry. */
   147093   sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
   147094   sqlite3_step(pRtree->pDeleteNode);
   147095   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
   147096     return rc;
   147097   }
   147098 
   147099   /* Remove the xxx_parent entry. */
   147100   sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
   147101   sqlite3_step(pRtree->pDeleteParent);
   147102   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
   147103     return rc;
   147104   }
   147105 
   147106   /* Remove the node from the in-memory hash table and link it into
   147107   ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
   147108   */
   147109   nodeHashDelete(pRtree, pNode);
   147110   pNode->iNode = iHeight;
   147111   pNode->pNext = pRtree->pDeleted;
   147112   pNode->nRef++;
   147113   pRtree->pDeleted = pNode;
   147114 
   147115   return SQLITE_OK;
   147116 }
   147117 
   147118 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
   147119   RtreeNode *pParent = pNode->pParent;
   147120   int rc = SQLITE_OK;
   147121   if( pParent ){
   147122     int ii;
   147123     int nCell = NCELL(pNode);
   147124     RtreeCell box;                            /* Bounding box for pNode */
   147125     nodeGetCell(pRtree, pNode, 0, &box);
   147126     for(ii=1; ii<nCell; ii++){
   147127       RtreeCell cell;
   147128       nodeGetCell(pRtree, pNode, ii, &cell);
   147129       cellUnion(pRtree, &box, &cell);
   147130     }
   147131     box.iRowid = pNode->iNode;
   147132     rc = nodeParentIndex(pRtree, pNode, &ii);
   147133     if( rc==SQLITE_OK ){
   147134       nodeOverwriteCell(pRtree, pParent, &box, ii);
   147135       rc = fixBoundingBox(pRtree, pParent);
   147136     }
   147137   }
   147138   return rc;
   147139 }
   147140 
   147141 /*
   147142 ** Delete the cell at index iCell of node pNode. After removing the
   147143 ** cell, adjust the r-tree data structure if required.
   147144 */
   147145 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
   147146   RtreeNode *pParent;
   147147   int rc;
   147148 
   147149   if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
   147150     return rc;
   147151   }
   147152 
   147153   /* Remove the cell from the node. This call just moves bytes around
   147154   ** the in-memory node image, so it cannot fail.
   147155   */
   147156   nodeDeleteCell(pRtree, pNode, iCell);
   147157 
   147158   /* If the node is not the tree root and now has less than the minimum
   147159   ** number of cells, remove it from the tree. Otherwise, update the
   147160   ** cell in the parent node so that it tightly contains the updated
   147161   ** node.
   147162   */
   147163   pParent = pNode->pParent;
   147164   assert( pParent || pNode->iNode==1 );
   147165   if( pParent ){
   147166     if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
   147167       rc = removeNode(pRtree, pNode, iHeight);
   147168     }else{
   147169       rc = fixBoundingBox(pRtree, pNode);
   147170     }
   147171   }
   147172 
   147173   return rc;
   147174 }
   147175 
   147176 static int Reinsert(
   147177   Rtree *pRtree,
   147178   RtreeNode *pNode,
   147179   RtreeCell *pCell,
   147180   int iHeight
   147181 ){
   147182   int *aOrder;
   147183   int *aSpare;
   147184   RtreeCell *aCell;
   147185   RtreeDValue *aDistance;
   147186   int nCell;
   147187   RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
   147188   int iDim;
   147189   int ii;
   147190   int rc = SQLITE_OK;
   147191   int n;
   147192 
   147193   memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
   147194 
   147195   nCell = NCELL(pNode)+1;
   147196   n = (nCell+1)&(~1);
   147197 
   147198   /* Allocate the buffers used by this operation. The allocation is
   147199   ** relinquished before this function returns.
   147200   */
   147201   aCell = (RtreeCell *)sqlite3_malloc(n * (
   147202     sizeof(RtreeCell)     +         /* aCell array */
   147203     sizeof(int)           +         /* aOrder array */
   147204     sizeof(int)           +         /* aSpare array */
   147205     sizeof(RtreeDValue)             /* aDistance array */
   147206   ));
   147207   if( !aCell ){
   147208     return SQLITE_NOMEM;
   147209   }
   147210   aOrder    = (int *)&aCell[n];
   147211   aSpare    = (int *)&aOrder[n];
   147212   aDistance = (RtreeDValue *)&aSpare[n];
   147213 
   147214   for(ii=0; ii<nCell; ii++){
   147215     if( ii==(nCell-1) ){
   147216       memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
   147217     }else{
   147218       nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
   147219     }
   147220     aOrder[ii] = ii;
   147221     for(iDim=0; iDim<pRtree->nDim; iDim++){
   147222       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
   147223       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
   147224     }
   147225   }
   147226   for(iDim=0; iDim<pRtree->nDim; iDim++){
   147227     aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
   147228   }
   147229 
   147230   for(ii=0; ii<nCell; ii++){
   147231     aDistance[ii] = RTREE_ZERO;
   147232     for(iDim=0; iDim<pRtree->nDim; iDim++){
   147233       RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
   147234                                DCOORD(aCell[ii].aCoord[iDim*2]));
   147235       aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
   147236     }
   147237   }
   147238 
   147239   SortByDistance(aOrder, nCell, aDistance, aSpare);
   147240   nodeZero(pRtree, pNode);
   147241 
   147242   for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
   147243     RtreeCell *p = &aCell[aOrder[ii]];
   147244     nodeInsertCell(pRtree, pNode, p);
   147245     if( p->iRowid==pCell->iRowid ){
   147246       if( iHeight==0 ){
   147247         rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
   147248       }else{
   147249         rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
   147250       }
   147251     }
   147252   }
   147253   if( rc==SQLITE_OK ){
   147254     rc = fixBoundingBox(pRtree, pNode);
   147255   }
   147256   for(; rc==SQLITE_OK && ii<nCell; ii++){
   147257     /* Find a node to store this cell in. pNode->iNode currently contains
   147258     ** the height of the sub-tree headed by the cell.
   147259     */
   147260     RtreeNode *pInsert;
   147261     RtreeCell *p = &aCell[aOrder[ii]];
   147262     rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
   147263     if( rc==SQLITE_OK ){
   147264       int rc2;
   147265       rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
   147266       rc2 = nodeRelease(pRtree, pInsert);
   147267       if( rc==SQLITE_OK ){
   147268         rc = rc2;
   147269       }
   147270     }
   147271   }
   147272 
   147273   sqlite3_free(aCell);
   147274   return rc;
   147275 }
   147276 
   147277 /*
   147278 ** Insert cell pCell into node pNode. Node pNode is the head of a
   147279 ** subtree iHeight high (leaf nodes have iHeight==0).
   147280 */
   147281 static int rtreeInsertCell(
   147282   Rtree *pRtree,
   147283   RtreeNode *pNode,
   147284   RtreeCell *pCell,
   147285   int iHeight
   147286 ){
   147287   int rc = SQLITE_OK;
   147288   if( iHeight>0 ){
   147289     RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
   147290     if( pChild ){
   147291       nodeRelease(pRtree, pChild->pParent);
   147292       nodeReference(pNode);
   147293       pChild->pParent = pNode;
   147294     }
   147295   }
   147296   if( nodeInsertCell(pRtree, pNode, pCell) ){
   147297     if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
   147298       rc = SplitNode(pRtree, pNode, pCell, iHeight);
   147299     }else{
   147300       pRtree->iReinsertHeight = iHeight;
   147301       rc = Reinsert(pRtree, pNode, pCell, iHeight);
   147302     }
   147303   }else{
   147304     rc = AdjustTree(pRtree, pNode, pCell);
   147305     if( rc==SQLITE_OK ){
   147306       if( iHeight==0 ){
   147307         rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
   147308       }else{
   147309         rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
   147310       }
   147311     }
   147312   }
   147313   return rc;
   147314 }
   147315 
   147316 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
   147317   int ii;
   147318   int rc = SQLITE_OK;
   147319   int nCell = NCELL(pNode);
   147320 
   147321   for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
   147322     RtreeNode *pInsert;
   147323     RtreeCell cell;
   147324     nodeGetCell(pRtree, pNode, ii, &cell);
   147325 
   147326     /* Find a node to store this cell in. pNode->iNode currently contains
   147327     ** the height of the sub-tree headed by the cell.
   147328     */
   147329     rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
   147330     if( rc==SQLITE_OK ){
   147331       int rc2;
   147332       rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
   147333       rc2 = nodeRelease(pRtree, pInsert);
   147334       if( rc==SQLITE_OK ){
   147335         rc = rc2;
   147336       }
   147337     }
   147338   }
   147339   return rc;
   147340 }
   147341 
   147342 /*
   147343 ** Select a currently unused rowid for a new r-tree record.
   147344 */
   147345 static int newRowid(Rtree *pRtree, i64 *piRowid){
   147346   int rc;
   147347   sqlite3_bind_null(pRtree->pWriteRowid, 1);
   147348   sqlite3_bind_null(pRtree->pWriteRowid, 2);
   147349   sqlite3_step(pRtree->pWriteRowid);
   147350   rc = sqlite3_reset(pRtree->pWriteRowid);
   147351   *piRowid = sqlite3_last_insert_rowid(pRtree->db);
   147352   return rc;
   147353 }
   147354 
   147355 /*
   147356 ** Remove the entry with rowid=iDelete from the r-tree structure.
   147357 */
   147358 static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
   147359   int rc;                         /* Return code */
   147360   RtreeNode *pLeaf = 0;           /* Leaf node containing record iDelete */
   147361   int iCell;                      /* Index of iDelete cell in pLeaf */
   147362   RtreeNode *pRoot;               /* Root node of rtree structure */
   147363 
   147364 
   147365   /* Obtain a reference to the root node to initialize Rtree.iDepth */
   147366   rc = nodeAcquire(pRtree, 1, 0, &pRoot);
   147367 
   147368   /* Obtain a reference to the leaf node that contains the entry
   147369   ** about to be deleted.
   147370   */
   147371   if( rc==SQLITE_OK ){
   147372     rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
   147373   }
   147374 
   147375   /* Delete the cell in question from the leaf node. */
   147376   if( rc==SQLITE_OK ){
   147377     int rc2;
   147378     rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
   147379     if( rc==SQLITE_OK ){
   147380       rc = deleteCell(pRtree, pLeaf, iCell, 0);
   147381     }
   147382     rc2 = nodeRelease(pRtree, pLeaf);
   147383     if( rc==SQLITE_OK ){
   147384       rc = rc2;
   147385     }
   147386   }
   147387 
   147388   /* Delete the corresponding entry in the <rtree>_rowid table. */
   147389   if( rc==SQLITE_OK ){
   147390     sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
   147391     sqlite3_step(pRtree->pDeleteRowid);
   147392     rc = sqlite3_reset(pRtree->pDeleteRowid);
   147393   }
   147394 
   147395   /* Check if the root node now has exactly one child. If so, remove
   147396   ** it, schedule the contents of the child for reinsertion and
   147397   ** reduce the tree height by one.
   147398   **
   147399   ** This is equivalent to copying the contents of the child into
   147400   ** the root node (the operation that Gutman's paper says to perform
   147401   ** in this scenario).
   147402   */
   147403   if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
   147404     int rc2;
   147405     RtreeNode *pChild;
   147406     i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
   147407     rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
   147408     if( rc==SQLITE_OK ){
   147409       rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
   147410     }
   147411     rc2 = nodeRelease(pRtree, pChild);
   147412     if( rc==SQLITE_OK ) rc = rc2;
   147413     if( rc==SQLITE_OK ){
   147414       pRtree->iDepth--;
   147415       writeInt16(pRoot->zData, pRtree->iDepth);
   147416       pRoot->isDirty = 1;
   147417     }
   147418   }
   147419 
   147420   /* Re-insert the contents of any underfull nodes removed from the tree. */
   147421   for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
   147422     if( rc==SQLITE_OK ){
   147423       rc = reinsertNodeContent(pRtree, pLeaf);
   147424     }
   147425     pRtree->pDeleted = pLeaf->pNext;
   147426     sqlite3_free(pLeaf);
   147427   }
   147428 
   147429   /* Release the reference to the root node. */
   147430   if( rc==SQLITE_OK ){
   147431     rc = nodeRelease(pRtree, pRoot);
   147432   }else{
   147433     nodeRelease(pRtree, pRoot);
   147434   }
   147435 
   147436   return rc;
   147437 }
   147438 
   147439 /*
   147440 ** Rounding constants for float->double conversion.
   147441 */
   147442 #define RNDTOWARDS  (1.0 - 1.0/8388608.0)  /* Round towards zero */
   147443 #define RNDAWAY     (1.0 + 1.0/8388608.0)  /* Round away from zero */
   147444 
   147445 #if !defined(SQLITE_RTREE_INT_ONLY)
   147446 /*
   147447 ** Convert an sqlite3_value into an RtreeValue (presumably a float)
   147448 ** while taking care to round toward negative or positive, respectively.
   147449 */
   147450 static RtreeValue rtreeValueDown(sqlite3_value *v){
   147451   double d = sqlite3_value_double(v);
   147452   float f = (float)d;
   147453   if( f>d ){
   147454     f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
   147455   }
   147456   return f;
   147457 }
   147458 static RtreeValue rtreeValueUp(sqlite3_value *v){
   147459   double d = sqlite3_value_double(v);
   147460   float f = (float)d;
   147461   if( f<d ){
   147462     f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
   147463   }
   147464   return f;
   147465 }
   147466 #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
   147467 
   147468 
   147469 /*
   147470 ** The xUpdate method for rtree module virtual tables.
   147471 */
   147472 static int rtreeUpdate(
   147473   sqlite3_vtab *pVtab,
   147474   int nData,
   147475   sqlite3_value **azData,
   147476   sqlite_int64 *pRowid
   147477 ){
   147478   Rtree *pRtree = (Rtree *)pVtab;
   147479   int rc = SQLITE_OK;
   147480   RtreeCell cell;                 /* New cell to insert if nData>1 */
   147481   int bHaveRowid = 0;             /* Set to 1 after new rowid is determined */
   147482 
   147483   rtreeReference(pRtree);
   147484   assert(nData>=1);
   147485 
   147486   /* Constraint handling. A write operation on an r-tree table may return
   147487   ** SQLITE_CONSTRAINT for two reasons:
   147488   **
   147489   **   1. A duplicate rowid value, or
   147490   **   2. The supplied data violates the "x2>=x1" constraint.
   147491   **
   147492   ** In the first case, if the conflict-handling mode is REPLACE, then
   147493   ** the conflicting row can be removed before proceeding. In the second
   147494   ** case, SQLITE_CONSTRAINT must be returned regardless of the
   147495   ** conflict-handling mode specified by the user.
   147496   */
   147497   if( nData>1 ){
   147498     int ii;
   147499 
   147500     /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
   147501     assert( nData==(pRtree->nDim*2 + 3) );
   147502 #ifndef SQLITE_RTREE_INT_ONLY
   147503     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
   147504       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
   147505         cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
   147506         cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
   147507         if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
   147508           rc = SQLITE_CONSTRAINT;
   147509           goto constraint;
   147510         }
   147511       }
   147512     }else
   147513 #endif
   147514     {
   147515       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
   147516         cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
   147517         cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
   147518         if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
   147519           rc = SQLITE_CONSTRAINT;
   147520           goto constraint;
   147521         }
   147522       }
   147523     }
   147524 
   147525     /* If a rowid value was supplied, check if it is already present in
   147526     ** the table. If so, the constraint has failed. */
   147527     if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
   147528       cell.iRowid = sqlite3_value_int64(azData[2]);
   147529       if( sqlite3_value_type(azData[0])==SQLITE_NULL
   147530        || sqlite3_value_int64(azData[0])!=cell.iRowid
   147531       ){
   147532         int steprc;
   147533         sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
   147534         steprc = sqlite3_step(pRtree->pReadRowid);
   147535         rc = sqlite3_reset(pRtree->pReadRowid);
   147536         if( SQLITE_ROW==steprc ){
   147537           if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
   147538             rc = rtreeDeleteRowid(pRtree, cell.iRowid);
   147539           }else{
   147540             rc = SQLITE_CONSTRAINT;
   147541             goto constraint;
   147542           }
   147543         }
   147544       }
   147545       bHaveRowid = 1;
   147546     }
   147547   }
   147548 
   147549   /* If azData[0] is not an SQL NULL value, it is the rowid of a
   147550   ** record to delete from the r-tree table. The following block does
   147551   ** just that.
   147552   */
   147553   if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
   147554     rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
   147555   }
   147556 
   147557   /* If the azData[] array contains more than one element, elements
   147558   ** (azData[2]..azData[argc-1]) contain a new record to insert into
   147559   ** the r-tree structure.
   147560   */
   147561   if( rc==SQLITE_OK && nData>1 ){
   147562     /* Insert the new record into the r-tree */
   147563     RtreeNode *pLeaf = 0;
   147564 
   147565     /* Figure out the rowid of the new row. */
   147566     if( bHaveRowid==0 ){
   147567       rc = newRowid(pRtree, &cell.iRowid);
   147568     }
   147569     *pRowid = cell.iRowid;
   147570 
   147571     if( rc==SQLITE_OK ){
   147572       rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
   147573     }
   147574     if( rc==SQLITE_OK ){
   147575       int rc2;
   147576       pRtree->iReinsertHeight = -1;
   147577       rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
   147578       rc2 = nodeRelease(pRtree, pLeaf);
   147579       if( rc==SQLITE_OK ){
   147580         rc = rc2;
   147581       }
   147582     }
   147583   }
   147584 
   147585 constraint:
   147586   rtreeRelease(pRtree);
   147587   return rc;
   147588 }
   147589 
   147590 /*
   147591 ** The xRename method for rtree module virtual tables.
   147592 */
   147593 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
   147594   Rtree *pRtree = (Rtree *)pVtab;
   147595   int rc = SQLITE_NOMEM;
   147596   char *zSql = sqlite3_mprintf(
   147597     "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
   147598     "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
   147599     "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
   147600     , pRtree->zDb, pRtree->zName, zNewName
   147601     , pRtree->zDb, pRtree->zName, zNewName
   147602     , pRtree->zDb, pRtree->zName, zNewName
   147603   );
   147604   if( zSql ){
   147605     rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
   147606     sqlite3_free(zSql);
   147607   }
   147608   return rc;
   147609 }
   147610 
   147611 /*
   147612 ** This function populates the pRtree->nRowEst variable with an estimate
   147613 ** of the number of rows in the virtual table. If possible, this is based
   147614 ** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
   147615 */
   147616 static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
   147617   const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
   147618   char *zSql;
   147619   sqlite3_stmt *p;
   147620   int rc;
   147621   i64 nRow = 0;
   147622 
   147623   zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
   147624   if( zSql==0 ){
   147625     rc = SQLITE_NOMEM;
   147626   }else{
   147627     rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
   147628     if( rc==SQLITE_OK ){
   147629       if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
   147630       rc = sqlite3_finalize(p);
   147631     }else if( rc!=SQLITE_NOMEM ){
   147632       rc = SQLITE_OK;
   147633     }
   147634 
   147635     if( rc==SQLITE_OK ){
   147636       if( nRow==0 ){
   147637         pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
   147638       }else{
   147639         pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
   147640       }
   147641     }
   147642     sqlite3_free(zSql);
   147643   }
   147644 
   147645   return rc;
   147646 }
   147647 
   147648 static sqlite3_module rtreeModule = {
   147649   0,                          /* iVersion */
   147650   rtreeCreate,                /* xCreate - create a table */
   147651   rtreeConnect,               /* xConnect - connect to an existing table */
   147652   rtreeBestIndex,             /* xBestIndex - Determine search strategy */
   147653   rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
   147654   rtreeDestroy,               /* xDestroy - Drop a table */
   147655   rtreeOpen,                  /* xOpen - open a cursor */
   147656   rtreeClose,                 /* xClose - close a cursor */
   147657   rtreeFilter,                /* xFilter - configure scan constraints */
   147658   rtreeNext,                  /* xNext - advance a cursor */
   147659   rtreeEof,                   /* xEof */
   147660   rtreeColumn,                /* xColumn - read data */
   147661   rtreeRowid,                 /* xRowid - read data */
   147662   rtreeUpdate,                /* xUpdate - write data */
   147663   0,                          /* xBegin - begin transaction */
   147664   0,                          /* xSync - sync transaction */
   147665   0,                          /* xCommit - commit transaction */
   147666   0,                          /* xRollback - rollback transaction */
   147667   0,                          /* xFindFunction - function overloading */
   147668   rtreeRename,                /* xRename - rename the table */
   147669   0,                          /* xSavepoint */
   147670   0,                          /* xRelease */
   147671   0                           /* xRollbackTo */
   147672 };
   147673 
   147674 static int rtreeSqlInit(
   147675   Rtree *pRtree,
   147676   sqlite3 *db,
   147677   const char *zDb,
   147678   const char *zPrefix,
   147679   int isCreate
   147680 ){
   147681   int rc = SQLITE_OK;
   147682 
   147683   #define N_STATEMENT 9
   147684   static const char *azSql[N_STATEMENT] = {
   147685     /* Read and write the xxx_node table */
   147686     "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
   147687     "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
   147688     "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
   147689 
   147690     /* Read and write the xxx_rowid table */
   147691     "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
   147692     "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
   147693     "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
   147694 
   147695     /* Read and write the xxx_parent table */
   147696     "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
   147697     "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
   147698     "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
   147699   };
   147700   sqlite3_stmt **appStmt[N_STATEMENT];
   147701   int i;
   147702 
   147703   pRtree->db = db;
   147704 
   147705   if( isCreate ){
   147706     char *zCreate = sqlite3_mprintf(
   147707 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
   147708 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
   147709 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,"
   147710                                   " parentnode INTEGER);"
   147711 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
   147712       zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
   147713     );
   147714     if( !zCreate ){
   147715       return SQLITE_NOMEM;
   147716     }
   147717     rc = sqlite3_exec(db, zCreate, 0, 0, 0);
   147718     sqlite3_free(zCreate);
   147719     if( rc!=SQLITE_OK ){
   147720       return rc;
   147721     }
   147722   }
   147723 
   147724   appStmt[0] = &pRtree->pReadNode;
   147725   appStmt[1] = &pRtree->pWriteNode;
   147726   appStmt[2] = &pRtree->pDeleteNode;
   147727   appStmt[3] = &pRtree->pReadRowid;
   147728   appStmt[4] = &pRtree->pWriteRowid;
   147729   appStmt[5] = &pRtree->pDeleteRowid;
   147730   appStmt[6] = &pRtree->pReadParent;
   147731   appStmt[7] = &pRtree->pWriteParent;
   147732   appStmt[8] = &pRtree->pDeleteParent;
   147733 
   147734   rc = rtreeQueryStat1(db, pRtree);
   147735   for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
   147736     char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
   147737     if( zSql ){
   147738       rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
   147739     }else{
   147740       rc = SQLITE_NOMEM;
   147741     }
   147742     sqlite3_free(zSql);
   147743   }
   147744 
   147745   return rc;
   147746 }
   147747 
   147748 /*
   147749 ** The second argument to this function contains the text of an SQL statement
   147750 ** that returns a single integer value. The statement is compiled and executed
   147751 ** using database connection db. If successful, the integer value returned
   147752 ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
   147753 ** code is returned and the value of *piVal after returning is not defined.
   147754 */
   147755 static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
   147756   int rc = SQLITE_NOMEM;
   147757   if( zSql ){
   147758     sqlite3_stmt *pStmt = 0;
   147759     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
   147760     if( rc==SQLITE_OK ){
   147761       if( SQLITE_ROW==sqlite3_step(pStmt) ){
   147762         *piVal = sqlite3_column_int(pStmt, 0);
   147763       }
   147764       rc = sqlite3_finalize(pStmt);
   147765     }
   147766   }
   147767   return rc;
   147768 }
   147769 
   147770 /*
   147771 ** This function is called from within the xConnect() or xCreate() method to
   147772 ** determine the node-size used by the rtree table being created or connected
   147773 ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
   147774 ** Otherwise, an SQLite error code is returned.
   147775 **
   147776 ** If this function is being called as part of an xConnect(), then the rtree
   147777 ** table already exists. In this case the node-size is determined by inspecting
   147778 ** the root node of the tree.
   147779 **
   147780 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
   147781 ** This ensures that each node is stored on a single database page. If the
   147782 ** database page-size is so large that more than RTREE_MAXCELLS entries
   147783 ** would fit in a single node, use a smaller node-size.
   147784 */
   147785 static int getNodeSize(
   147786   sqlite3 *db,                    /* Database handle */
   147787   Rtree *pRtree,                  /* Rtree handle */
   147788   int isCreate,                   /* True for xCreate, false for xConnect */
   147789   char **pzErr                    /* OUT: Error message, if any */
   147790 ){
   147791   int rc;
   147792   char *zSql;
   147793   if( isCreate ){
   147794     int iPageSize = 0;
   147795     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
   147796     rc = getIntFromStmt(db, zSql, &iPageSize);
   147797     if( rc==SQLITE_OK ){
   147798       pRtree->iNodeSize = iPageSize-64;
   147799       if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
   147800         pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
   147801       }
   147802     }else{
   147803       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
   147804     }
   147805   }else{
   147806     zSql = sqlite3_mprintf(
   147807         "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
   147808         pRtree->zDb, pRtree->zName
   147809     );
   147810     rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
   147811     if( rc!=SQLITE_OK ){
   147812       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
   147813     }
   147814   }
   147815 
   147816   sqlite3_free(zSql);
   147817   return rc;
   147818 }
   147819 
   147820 /*
   147821 ** This function is the implementation of both the xConnect and xCreate
   147822 ** methods of the r-tree virtual table.
   147823 **
   147824 **   argv[0]   -> module name
   147825 **   argv[1]   -> database name
   147826 **   argv[2]   -> table name
   147827 **   argv[...] -> column names...
   147828 */
   147829 static int rtreeInit(
   147830   sqlite3 *db,                        /* Database connection */
   147831   void *pAux,                         /* One of the RTREE_COORD_* constants */
   147832   int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
   147833   sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
   147834   char **pzErr,                       /* OUT: Error message, if any */
   147835   int isCreate                        /* True for xCreate, false for xConnect */
   147836 ){
   147837   int rc = SQLITE_OK;
   147838   Rtree *pRtree;
   147839   int nDb;              /* Length of string argv[1] */
   147840   int nName;            /* Length of string argv[2] */
   147841   int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
   147842 
   147843   const char *aErrMsg[] = {
   147844     0,                                                    /* 0 */
   147845     "Wrong number of columns for an rtree table",         /* 1 */
   147846     "Too few columns for an rtree table",                 /* 2 */
   147847     "Too many columns for an rtree table"                 /* 3 */
   147848   };
   147849 
   147850   int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
   147851   if( aErrMsg[iErr] ){
   147852     *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
   147853     return SQLITE_ERROR;
   147854   }
   147855 
   147856   sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
   147857 
   147858   /* Allocate the sqlite3_vtab structure */
   147859   nDb = (int)strlen(argv[1]);
   147860   nName = (int)strlen(argv[2]);
   147861   pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
   147862   if( !pRtree ){
   147863     return SQLITE_NOMEM;
   147864   }
   147865   memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
   147866   pRtree->nBusy = 1;
   147867   pRtree->base.pModule = &rtreeModule;
   147868   pRtree->zDb = (char *)&pRtree[1];
   147869   pRtree->zName = &pRtree->zDb[nDb+1];
   147870   pRtree->nDim = (argc-4)/2;
   147871   pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
   147872   pRtree->eCoordType = eCoordType;
   147873   memcpy(pRtree->zDb, argv[1], nDb);
   147874   memcpy(pRtree->zName, argv[2], nName);
   147875 
   147876   /* Figure out the node size to use. */
   147877   rc = getNodeSize(db, pRtree, isCreate, pzErr);
   147878 
   147879   /* Create/Connect to the underlying relational database schema. If
   147880   ** that is successful, call sqlite3_declare_vtab() to configure
   147881   ** the r-tree table schema.
   147882   */
   147883   if( rc==SQLITE_OK ){
   147884     if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
   147885       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
   147886     }else{
   147887       char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
   147888       char *zTmp;
   147889       int ii;
   147890       for(ii=4; zSql && ii<argc; ii++){
   147891         zTmp = zSql;
   147892         zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
   147893         sqlite3_free(zTmp);
   147894       }
   147895       if( zSql ){
   147896         zTmp = zSql;
   147897         zSql = sqlite3_mprintf("%s);", zTmp);
   147898         sqlite3_free(zTmp);
   147899       }
   147900       if( !zSql ){
   147901         rc = SQLITE_NOMEM;
   147902       }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
   147903         *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
   147904       }
   147905       sqlite3_free(zSql);
   147906     }
   147907   }
   147908 
   147909   if( rc==SQLITE_OK ){
   147910     *ppVtab = (sqlite3_vtab *)pRtree;
   147911   }else{
   147912     assert( *ppVtab==0 );
   147913     assert( pRtree->nBusy==1 );
   147914     rtreeRelease(pRtree);
   147915   }
   147916   return rc;
   147917 }
   147918 
   147919 
   147920 /*
   147921 ** Implementation of a scalar function that decodes r-tree nodes to
   147922 ** human readable strings. This can be used for debugging and analysis.
   147923 **
   147924 ** The scalar function takes two arguments: (1) the number of dimensions
   147925 ** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
   147926 ** an r-tree node.  For a two-dimensional r-tree structure called "rt", to
   147927 ** deserialize all nodes, a statement like:
   147928 **
   147929 **   SELECT rtreenode(2, data) FROM rt_node;
   147930 **
   147931 ** The human readable string takes the form of a Tcl list with one
   147932 ** entry for each cell in the r-tree node. Each entry is itself a
   147933 ** list, containing the 8-byte rowid/pageno followed by the
   147934 ** <num-dimension>*2 coordinates.
   147935 */
   147936 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
   147937   char *zText = 0;
   147938   RtreeNode node;
   147939   Rtree tree;
   147940   int ii;
   147941 
   147942   UNUSED_PARAMETER(nArg);
   147943   memset(&node, 0, sizeof(RtreeNode));
   147944   memset(&tree, 0, sizeof(Rtree));
   147945   tree.nDim = sqlite3_value_int(apArg[0]);
   147946   tree.nBytesPerCell = 8 + 8 * tree.nDim;
   147947   node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
   147948 
   147949   for(ii=0; ii<NCELL(&node); ii++){
   147950     char zCell[512];
   147951     int nCell = 0;
   147952     RtreeCell cell;
   147953     int jj;
   147954 
   147955     nodeGetCell(&tree, &node, ii, &cell);
   147956     sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
   147957     nCell = (int)strlen(zCell);
   147958     for(jj=0; jj<tree.nDim*2; jj++){
   147959 #ifndef SQLITE_RTREE_INT_ONLY
   147960       sqlite3_snprintf(512-nCell,&zCell[nCell], " %g",
   147961                        (double)cell.aCoord[jj].f);
   147962 #else
   147963       sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
   147964                        cell.aCoord[jj].i);
   147965 #endif
   147966       nCell = (int)strlen(zCell);
   147967     }
   147968 
   147969     if( zText ){
   147970       char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
   147971       sqlite3_free(zText);
   147972       zText = zTextNew;
   147973     }else{
   147974       zText = sqlite3_mprintf("{%s}", zCell);
   147975     }
   147976   }
   147977 
   147978   sqlite3_result_text(ctx, zText, -1, sqlite3_free);
   147979 }
   147980 
   147981 /* This routine implements an SQL function that returns the "depth" parameter
   147982 ** from the front of a blob that is an r-tree node.  For example:
   147983 **
   147984 **     SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
   147985 **
   147986 ** The depth value is 0 for all nodes other than the root node, and the root
   147987 ** node always has nodeno=1, so the example above is the primary use for this
   147988 ** routine.  This routine is intended for testing and analysis only.
   147989 */
   147990 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
   147991   UNUSED_PARAMETER(nArg);
   147992   if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
   147993    || sqlite3_value_bytes(apArg[0])<2
   147994   ){
   147995     sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
   147996   }else{
   147997     u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
   147998     sqlite3_result_int(ctx, readInt16(zBlob));
   147999   }
   148000 }
   148001 
   148002 /*
   148003 ** Register the r-tree module with database handle db. This creates the
   148004 ** virtual table module "rtree" and the debugging/analysis scalar
   148005 ** function "rtreenode".
   148006 */
   148007 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
   148008   const int utf8 = SQLITE_UTF8;
   148009   int rc;
   148010 
   148011   rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
   148012   if( rc==SQLITE_OK ){
   148013     rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
   148014   }
   148015   if( rc==SQLITE_OK ){
   148016 #ifdef SQLITE_RTREE_INT_ONLY
   148017     void *c = (void *)RTREE_COORD_INT32;
   148018 #else
   148019     void *c = (void *)RTREE_COORD_REAL32;
   148020 #endif
   148021     rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
   148022   }
   148023   if( rc==SQLITE_OK ){
   148024     void *c = (void *)RTREE_COORD_INT32;
   148025     rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
   148026   }
   148027 
   148028   return rc;
   148029 }
   148030 
   148031 /*
   148032 ** This routine deletes the RtreeGeomCallback object that was attached
   148033 ** one of the SQL functions create by sqlite3_rtree_geometry_callback()
   148034 ** or sqlite3_rtree_query_callback().  In other words, this routine is the
   148035 ** destructor for an RtreeGeomCallback objecct.  This routine is called when
   148036 ** the corresponding SQL function is deleted.
   148037 */
   148038 static void rtreeFreeCallback(void *p){
   148039   RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
   148040   if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
   148041   sqlite3_free(p);
   148042 }
   148043 
   148044 /*
   148045 ** Each call to sqlite3_rtree_geometry_callback() or
   148046 ** sqlite3_rtree_query_callback() creates an ordinary SQLite
   148047 ** scalar function that is implemented by this routine.
   148048 **
   148049 ** All this function does is construct an RtreeMatchArg object that
   148050 ** contains the geometry-checking callback routines and a list of
   148051 ** parameters to this function, then return that RtreeMatchArg object
   148052 ** as a BLOB.
   148053 **
   148054 ** The R-Tree MATCH operator will read the returned BLOB, deserialize
   148055 ** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
   148056 ** out which elements of the R-Tree should be returned by the query.
   148057 */
   148058 static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
   148059   RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
   148060   RtreeMatchArg *pBlob;
   148061   int nBlob;
   148062 
   148063   nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue);
   148064   pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
   148065   if( !pBlob ){
   148066     sqlite3_result_error_nomem(ctx);
   148067   }else{
   148068     int i;
   148069     pBlob->magic = RTREE_GEOMETRY_MAGIC;
   148070     pBlob->cb = pGeomCtx[0];
   148071     pBlob->nParam = nArg;
   148072     for(i=0; i<nArg; i++){
   148073 #ifdef SQLITE_RTREE_INT_ONLY
   148074       pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
   148075 #else
   148076       pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
   148077 #endif
   148078     }
   148079     sqlite3_result_blob(ctx, pBlob, nBlob, sqlite3_free);
   148080   }
   148081 }
   148082 
   148083 /*
   148084 ** Register a new geometry function for use with the r-tree MATCH operator.
   148085 */
   148086 SQLITE_API int sqlite3_rtree_geometry_callback(
   148087   sqlite3 *db,                  /* Register SQL function on this connection */
   148088   const char *zGeom,            /* Name of the new SQL function */
   148089   int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
   148090   void *pContext                /* Extra data associated with the callback */
   148091 ){
   148092   RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
   148093 
   148094   /* Allocate and populate the context object. */
   148095   pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
   148096   if( !pGeomCtx ) return SQLITE_NOMEM;
   148097   pGeomCtx->xGeom = xGeom;
   148098   pGeomCtx->xQueryFunc = 0;
   148099   pGeomCtx->xDestructor = 0;
   148100   pGeomCtx->pContext = pContext;
   148101   return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
   148102       (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
   148103   );
   148104 }
   148105 
   148106 /*
   148107 ** Register a new 2nd-generation geometry function for use with the
   148108 ** r-tree MATCH operator.
   148109 */
   148110 SQLITE_API int sqlite3_rtree_query_callback(
   148111   sqlite3 *db,                 /* Register SQL function on this connection */
   148112   const char *zQueryFunc,      /* Name of new SQL function */
   148113   int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
   148114   void *pContext,              /* Extra data passed into the callback */
   148115   void (*xDestructor)(void*)   /* Destructor for the extra data */
   148116 ){
   148117   RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
   148118 
   148119   /* Allocate and populate the context object. */
   148120   pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
   148121   if( !pGeomCtx ) return SQLITE_NOMEM;
   148122   pGeomCtx->xGeom = 0;
   148123   pGeomCtx->xQueryFunc = xQueryFunc;
   148124   pGeomCtx->xDestructor = xDestructor;
   148125   pGeomCtx->pContext = pContext;
   148126   return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY,
   148127       (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
   148128   );
   148129 }
   148130 
   148131 #if !SQLITE_CORE
   148132 #ifdef _WIN32
   148133 __declspec(dllexport)
   148134 #endif
   148135 SQLITE_API int sqlite3_rtree_init(
   148136   sqlite3 *db,
   148137   char **pzErrMsg,
   148138   const sqlite3_api_routines *pApi
   148139 ){
   148140   SQLITE_EXTENSION_INIT2(pApi)
   148141   return sqlite3RtreeInit(db);
   148142 }
   148143 #endif
   148144 
   148145 #endif
   148146 
   148147 /************** End of rtree.c ***********************************************/
   148148 /************** Begin file icu.c *********************************************/
   148149 /*
   148150 ** 2007 May 6
   148151 **
   148152 ** The author disclaims copyright to this source code.  In place of
   148153 ** a legal notice, here is a blessing:
   148154 **
   148155 **    May you do good and not evil.
   148156 **    May you find forgiveness for yourself and forgive others.
   148157 **    May you share freely, never taking more than you give.
   148158 **
   148159 *************************************************************************
   148160 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
   148161 **
   148162 ** This file implements an integration between the ICU library
   148163 ** ("International Components for Unicode", an open-source library
   148164 ** for handling unicode data) and SQLite. The integration uses
   148165 ** ICU to provide the following to SQLite:
   148166 **
   148167 **   * An implementation of the SQL regexp() function (and hence REGEXP
   148168 **     operator) using the ICU uregex_XX() APIs.
   148169 **
   148170 **   * Implementations of the SQL scalar upper() and lower() functions
   148171 **     for case mapping.
   148172 **
   148173 **   * Integration of ICU and SQLite collation sequences.
   148174 **
   148175 **   * An implementation of the LIKE operator that uses ICU to
   148176 **     provide case-independent matching.
   148177 */
   148178 
   148179 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
   148180 
   148181 /* Include ICU headers */
   148182 #include <unicode/utypes.h>
   148183 #include <unicode/uregex.h>
   148184 #include <unicode/ustring.h>
   148185 #include <unicode/ucol.h>
   148186 
   148187 /* #include <assert.h> */
   148188 
   148189 #ifndef SQLITE_CORE
   148190   SQLITE_EXTENSION_INIT1
   148191 #else
   148192 #endif
   148193 
   148194 /*
   148195 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
   148196 ** operator.
   148197 */
   148198 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
   148199 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
   148200 #endif
   148201 
   148202 /*
   148203 ** Version of sqlite3_free() that is always a function, never a macro.
   148204 */
   148205 static void xFree(void *p){
   148206   sqlite3_free(p);
   148207 }
   148208 
   148209 /*
   148210 ** Compare two UTF-8 strings for equality where the first string is
   148211 ** a "LIKE" expression. Return true (1) if they are the same and
   148212 ** false (0) if they are different.
   148213 */
   148214 static int icuLikeCompare(
   148215   const uint8_t *zPattern,   /* LIKE pattern */
   148216   const uint8_t *zString,    /* The UTF-8 string to compare against */
   148217   const UChar32 uEsc         /* The escape character */
   148218 ){
   148219   static const int MATCH_ONE = (UChar32)'_';
   148220   static const int MATCH_ALL = (UChar32)'%';
   148221 
   148222   int iPattern = 0;       /* Current byte index in zPattern */
   148223   int iString = 0;        /* Current byte index in zString */
   148224 
   148225   int prevEscape = 0;     /* True if the previous character was uEsc */
   148226 
   148227   while( zPattern[iPattern]!=0 ){
   148228 
   148229     /* Read (and consume) the next character from the input pattern. */
   148230     UChar32 uPattern;
   148231     U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
   148232     assert(uPattern!=0);
   148233 
   148234     /* There are now 4 possibilities:
   148235     **
   148236     **     1. uPattern is an unescaped match-all character "%",
   148237     **     2. uPattern is an unescaped match-one character "_",
   148238     **     3. uPattern is an unescaped escape character, or
   148239     **     4. uPattern is to be handled as an ordinary character
   148240     */
   148241     if( !prevEscape && uPattern==MATCH_ALL ){
   148242       /* Case 1. */
   148243       uint8_t c;
   148244 
   148245       /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
   148246       ** MATCH_ALL. For each MATCH_ONE, skip one character in the
   148247       ** test string.
   148248       */
   148249       while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
   148250         if( c==MATCH_ONE ){
   148251           if( zString[iString]==0 ) return 0;
   148252           U8_FWD_1_UNSAFE(zString, iString);
   148253         }
   148254         iPattern++;
   148255       }
   148256 
   148257       if( zPattern[iPattern]==0 ) return 1;
   148258 
   148259       while( zString[iString] ){
   148260         if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
   148261           return 1;
   148262         }
   148263         U8_FWD_1_UNSAFE(zString, iString);
   148264       }
   148265       return 0;
   148266 
   148267     }else if( !prevEscape && uPattern==MATCH_ONE ){
   148268       /* Case 2. */
   148269       if( zString[iString]==0 ) return 0;
   148270       U8_FWD_1_UNSAFE(zString, iString);
   148271 
   148272     }else if( !prevEscape && uPattern==uEsc){
   148273       /* Case 3. */
   148274       prevEscape = 1;
   148275 
   148276     }else{
   148277       /* Case 4. */
   148278       UChar32 uString;
   148279       U8_NEXT_UNSAFE(zString, iString, uString);
   148280       uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
   148281       uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
   148282       if( uString!=uPattern ){
   148283         return 0;
   148284       }
   148285       prevEscape = 0;
   148286     }
   148287   }
   148288 
   148289   return zString[iString]==0;
   148290 }
   148291 
   148292 /*
   148293 ** Implementation of the like() SQL function.  This function implements
   148294 ** the build-in LIKE operator.  The first argument to the function is the
   148295 ** pattern and the second argument is the string.  So, the SQL statements:
   148296 **
   148297 **       A LIKE B
   148298 **
   148299 ** is implemented as like(B, A). If there is an escape character E,
   148300 **
   148301 **       A LIKE B ESCAPE E
   148302 **
   148303 ** is mapped to like(B, A, E).
   148304 */
   148305 static void icuLikeFunc(
   148306   sqlite3_context *context,
   148307   int argc,
   148308   sqlite3_value **argv
   148309 ){
   148310   const unsigned char *zA = sqlite3_value_text(argv[0]);
   148311   const unsigned char *zB = sqlite3_value_text(argv[1]);
   148312   UChar32 uEsc = 0;
   148313 
   148314   /* Limit the length of the LIKE or GLOB pattern to avoid problems
   148315   ** of deep recursion and N*N behavior in patternCompare().
   148316   */
   148317   if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
   148318     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
   148319     return;
   148320   }
   148321 
   148322 
   148323   if( argc==3 ){
   148324     /* The escape character string must consist of a single UTF-8 character.
   148325     ** Otherwise, return an error.
   148326     */
   148327     int nE= sqlite3_value_bytes(argv[2]);
   148328     const unsigned char *zE = sqlite3_value_text(argv[2]);
   148329     int i = 0;
   148330     if( zE==0 ) return;
   148331     U8_NEXT(zE, i, nE, uEsc);
   148332     if( i!=nE){
   148333       sqlite3_result_error(context,
   148334           "ESCAPE expression must be a single character", -1);
   148335       return;
   148336     }
   148337   }
   148338 
   148339   if( zA && zB ){
   148340     sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
   148341   }
   148342 }
   148343 
   148344 /*
   148345 ** This function is called when an ICU function called from within
   148346 ** the implementation of an SQL scalar function returns an error.
   148347 **
   148348 ** The scalar function context passed as the first argument is
   148349 ** loaded with an error message based on the following two args.
   148350 */
   148351 static void icuFunctionError(
   148352   sqlite3_context *pCtx,       /* SQLite scalar function context */
   148353   const char *zName,           /* Name of ICU function that failed */
   148354   UErrorCode e                 /* Error code returned by ICU function */
   148355 ){
   148356   char zBuf[128];
   148357   sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
   148358   zBuf[127] = '\0';
   148359   sqlite3_result_error(pCtx, zBuf, -1);
   148360 }
   148361 
   148362 /*
   148363 ** Function to delete compiled regexp objects. Registered as
   148364 ** a destructor function with sqlite3_set_auxdata().
   148365 */
   148366 static void icuRegexpDelete(void *p){
   148367   URegularExpression *pExpr = (URegularExpression *)p;
   148368   uregex_close(pExpr);
   148369 }
   148370 
   148371 /*
   148372 ** Implementation of SQLite REGEXP operator. This scalar function takes
   148373 ** two arguments. The first is a regular expression pattern to compile
   148374 ** the second is a string to match against that pattern. If either
   148375 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
   148376 ** is 1 if the string matches the pattern, or 0 otherwise.
   148377 **
   148378 ** SQLite maps the regexp() function to the regexp() operator such
   148379 ** that the following two are equivalent:
   148380 **
   148381 **     zString REGEXP zPattern
   148382 **     regexp(zPattern, zString)
   148383 **
   148384 ** Uses the following ICU regexp APIs:
   148385 **
   148386 **     uregex_open()
   148387 **     uregex_matches()
   148388 **     uregex_close()
   148389 */
   148390 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
   148391   UErrorCode status = U_ZERO_ERROR;
   148392   URegularExpression *pExpr;
   148393   UBool res;
   148394   const UChar *zString = sqlite3_value_text16(apArg[1]);
   148395 
   148396   (void)nArg;  /* Unused parameter */
   148397 
   148398   /* If the left hand side of the regexp operator is NULL,
   148399   ** then the result is also NULL.
   148400   */
   148401   if( !zString ){
   148402     return;
   148403   }
   148404 
   148405   pExpr = sqlite3_get_auxdata(p, 0);
   148406   if( !pExpr ){
   148407     const UChar *zPattern = sqlite3_value_text16(apArg[0]);
   148408     if( !zPattern ){
   148409       return;
   148410     }
   148411     pExpr = uregex_open(zPattern, -1, 0, 0, &status);
   148412 
   148413     if( U_SUCCESS(status) ){
   148414       sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
   148415     }else{
   148416       assert(!pExpr);
   148417       icuFunctionError(p, "uregex_open", status);
   148418       return;
   148419     }
   148420   }
   148421 
   148422   /* Configure the text that the regular expression operates on. */
   148423   uregex_setText(pExpr, zString, -1, &status);
   148424   if( !U_SUCCESS(status) ){
   148425     icuFunctionError(p, "uregex_setText", status);
   148426     return;
   148427   }
   148428 
   148429   /* Attempt the match */
   148430   res = uregex_matches(pExpr, 0, &status);
   148431   if( !U_SUCCESS(status) ){
   148432     icuFunctionError(p, "uregex_matches", status);
   148433     return;
   148434   }
   148435 
   148436   /* Set the text that the regular expression operates on to a NULL
   148437   ** pointer. This is not really necessary, but it is tidier than
   148438   ** leaving the regular expression object configured with an invalid
   148439   ** pointer after this function returns.
   148440   */
   148441   uregex_setText(pExpr, 0, 0, &status);
   148442 
   148443   /* Return 1 or 0. */
   148444   sqlite3_result_int(p, res ? 1 : 0);
   148445 }
   148446 
   148447 /*
   148448 ** Implementations of scalar functions for case mapping - upper() and
   148449 ** lower(). Function upper() converts its input to upper-case (ABC).
   148450 ** Function lower() converts to lower-case (abc).
   148451 **
   148452 ** ICU provides two types of case mapping, "general" case mapping and
   148453 ** "language specific". Refer to ICU documentation for the differences
   148454 ** between the two.
   148455 **
   148456 ** To utilise "general" case mapping, the upper() or lower() scalar
   148457 ** functions are invoked with one argument:
   148458 **
   148459 **     upper('ABC') -> 'abc'
   148460 **     lower('abc') -> 'ABC'
   148461 **
   148462 ** To access ICU "language specific" case mapping, upper() or lower()
   148463 ** should be invoked with two arguments. The second argument is the name
   148464 ** of the locale to use. Passing an empty string ("") or SQL NULL value
   148465 ** as the second argument is the same as invoking the 1 argument version
   148466 ** of upper() or lower().
   148467 **
   148468 **     lower('I', 'en_us') -> 'i'
   148469 **     lower('I', 'tr_tr') -> '' (small dotless i)
   148470 **
   148471 ** http://www.icu-project.org/userguide/posix.html#case_mappings
   148472 */
   148473 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
   148474   const UChar *zInput;
   148475   UChar *zOutput;
   148476   int nInput;
   148477   int nOutput;
   148478 
   148479   UErrorCode status = U_ZERO_ERROR;
   148480   const char *zLocale = 0;
   148481 
   148482   assert(nArg==1 || nArg==2);
   148483   if( nArg==2 ){
   148484     zLocale = (const char *)sqlite3_value_text(apArg[1]);
   148485   }
   148486 
   148487   zInput = sqlite3_value_text16(apArg[0]);
   148488   if( !zInput ){
   148489     return;
   148490   }
   148491   nInput = sqlite3_value_bytes16(apArg[0]);
   148492 
   148493   nOutput = nInput * 2 + 2;
   148494   zOutput = sqlite3_malloc(nOutput);
   148495   if( !zOutput ){
   148496     return;
   148497   }
   148498 
   148499   if( sqlite3_user_data(p) ){
   148500     u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
   148501   }else{
   148502     u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
   148503   }
   148504 
   148505   if( !U_SUCCESS(status) ){
   148506     icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
   148507     return;
   148508   }
   148509 
   148510   sqlite3_result_text16(p, zOutput, -1, xFree);
   148511 }
   148512 
   148513 /*
   148514 ** Collation sequence destructor function. The pCtx argument points to
   148515 ** a UCollator structure previously allocated using ucol_open().
   148516 */
   148517 static void icuCollationDel(void *pCtx){
   148518   UCollator *p = (UCollator *)pCtx;
   148519   ucol_close(p);
   148520 }
   148521 
   148522 /*
   148523 ** Collation sequence comparison function. The pCtx argument points to
   148524 ** a UCollator structure previously allocated using ucol_open().
   148525 */
   148526 static int icuCollationColl(
   148527   void *pCtx,
   148528   int nLeft,
   148529   const void *zLeft,
   148530   int nRight,
   148531   const void *zRight
   148532 ){
   148533   UCollationResult res;
   148534   UCollator *p = (UCollator *)pCtx;
   148535   res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
   148536   switch( res ){
   148537     case UCOL_LESS:    return -1;
   148538     case UCOL_GREATER: return +1;
   148539     case UCOL_EQUAL:   return 0;
   148540   }
   148541   assert(!"Unexpected return value from ucol_strcoll()");
   148542   return 0;
   148543 }
   148544 
   148545 /*
   148546 ** Implementation of the scalar function icu_load_collation().
   148547 **
   148548 ** This scalar function is used to add ICU collation based collation
   148549 ** types to an SQLite database connection. It is intended to be called
   148550 ** as follows:
   148551 **
   148552 **     SELECT icu_load_collation(<locale>, <collation-name>);
   148553 **
   148554 ** Where <locale> is a string containing an ICU locale identifier (i.e.
   148555 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
   148556 ** collation sequence to create.
   148557 */
   148558 static void icuLoadCollation(
   148559   sqlite3_context *p,
   148560   int nArg,
   148561   sqlite3_value **apArg
   148562 ){
   148563   sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
   148564   UErrorCode status = U_ZERO_ERROR;
   148565   const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
   148566   const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
   148567   UCollator *pUCollator;    /* ICU library collation object */
   148568   int rc;                   /* Return code from sqlite3_create_collation_x() */
   148569 
   148570   assert(nArg==2);
   148571   zLocale = (const char *)sqlite3_value_text(apArg[0]);
   148572   zName = (const char *)sqlite3_value_text(apArg[1]);
   148573 
   148574   if( !zLocale || !zName ){
   148575     return;
   148576   }
   148577 
   148578   pUCollator = ucol_open(zLocale, &status);
   148579   if( !U_SUCCESS(status) ){
   148580     icuFunctionError(p, "ucol_open", status);
   148581     return;
   148582   }
   148583   assert(p);
   148584 
   148585   rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
   148586       icuCollationColl, icuCollationDel
   148587   );
   148588   if( rc!=SQLITE_OK ){
   148589     ucol_close(pUCollator);
   148590     sqlite3_result_error(p, "Error registering collation function", -1);
   148591   }
   148592 }
   148593 
   148594 /*
   148595 ** Register the ICU extension functions with database db.
   148596 */
   148597 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
   148598   struct IcuScalar {
   148599     const char *zName;                        /* Function name */
   148600     int nArg;                                 /* Number of arguments */
   148601     int enc;                                  /* Optimal text encoding */
   148602     void *pContext;                           /* sqlite3_user_data() context */
   148603     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
   148604   } scalars[] = {
   148605     {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
   148606 
   148607     {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
   148608     {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
   148609     {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
   148610     {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
   148611 
   148612     {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
   148613     {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
   148614     {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
   148615     {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
   148616 
   148617     {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
   148618     {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
   148619 
   148620     {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
   148621   };
   148622 
   148623   int rc = SQLITE_OK;
   148624   int i;
   148625 
   148626   for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
   148627     struct IcuScalar *p = &scalars[i];
   148628     rc = sqlite3_create_function(
   148629         db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
   148630     );
   148631   }
   148632 
   148633   return rc;
   148634 }
   148635 
   148636 #if !SQLITE_CORE
   148637 #ifdef _WIN32
   148638 __declspec(dllexport)
   148639 #endif
   148640 SQLITE_API int sqlite3_icu_init(
   148641   sqlite3 *db,
   148642   char **pzErrMsg,
   148643   const sqlite3_api_routines *pApi
   148644 ){
   148645   SQLITE_EXTENSION_INIT2(pApi)
   148646   return sqlite3IcuInit(db);
   148647 }
   148648 #endif
   148649 
   148650 #endif
   148651 
   148652 /************** End of icu.c *************************************************/
   148653 /************** Begin file fts3_icu.c ****************************************/
   148654 /*
   148655 ** 2007 June 22
   148656 **
   148657 ** The author disclaims copyright to this source code.  In place of
   148658 ** a legal notice, here is a blessing:
   148659 **
   148660 **    May you do good and not evil.
   148661 **    May you find forgiveness for yourself and forgive others.
   148662 **    May you share freely, never taking more than you give.
   148663 **
   148664 *************************************************************************
   148665 ** This file implements a tokenizer for fts3 based on the ICU library.
   148666 */
   148667 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   148668 #ifdef SQLITE_ENABLE_ICU
   148669 
   148670 /* #include <assert.h> */
   148671 /* #include <string.h> */
   148672 
   148673 #include <unicode/ubrk.h>
   148674 /* #include <unicode/ucol.h> */
   148675 /* #include <unicode/ustring.h> */
   148676 #include <unicode/utf16.h>
   148677 
   148678 typedef struct IcuTokenizer IcuTokenizer;
   148679 typedef struct IcuCursor IcuCursor;
   148680 
   148681 struct IcuTokenizer {
   148682   sqlite3_tokenizer base;
   148683   char *zLocale;
   148684 };
   148685 
   148686 struct IcuCursor {
   148687   sqlite3_tokenizer_cursor base;
   148688 
   148689   UBreakIterator *pIter;      /* ICU break-iterator object */
   148690   int nChar;                  /* Number of UChar elements in pInput */
   148691   UChar *aChar;               /* Copy of input using utf-16 encoding */
   148692   int *aOffset;               /* Offsets of each character in utf-8 input */
   148693 
   148694   int nBuffer;
   148695   char *zBuffer;
   148696 
   148697   int iToken;
   148698 };
   148699 
   148700 /*
   148701 ** Create a new tokenizer instance.
   148702 */
   148703 static int icuCreate(
   148704   int argc,                            /* Number of entries in argv[] */
   148705   const char * const *argv,            /* Tokenizer creation arguments */
   148706   sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
   148707 ){
   148708   IcuTokenizer *p;
   148709   int n = 0;
   148710 
   148711   if( argc>0 ){
   148712     n = strlen(argv[0])+1;
   148713   }
   148714   p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
   148715   if( !p ){
   148716     return SQLITE_NOMEM;
   148717   }
   148718   memset(p, 0, sizeof(IcuTokenizer));
   148719 
   148720   if( n ){
   148721     p->zLocale = (char *)&p[1];
   148722     memcpy(p->zLocale, argv[0], n);
   148723   }
   148724 
   148725   *ppTokenizer = (sqlite3_tokenizer *)p;
   148726 
   148727   return SQLITE_OK;
   148728 }
   148729 
   148730 /*
   148731 ** Destroy a tokenizer
   148732 */
   148733 static int icuDestroy(sqlite3_tokenizer *pTokenizer){
   148734   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
   148735   sqlite3_free(p);
   148736   return SQLITE_OK;
   148737 }
   148738 
   148739 /*
   148740 ** Prepare to begin tokenizing a particular string.  The input
   148741 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
   148742 ** used to incrementally tokenize this string is returned in
   148743 ** *ppCursor.
   148744 */
   148745 static int icuOpen(
   148746   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
   148747   const char *zInput,                    /* Input string */
   148748   int nInput,                            /* Length of zInput in bytes */
   148749   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
   148750 ){
   148751   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
   148752   IcuCursor *pCsr;
   148753 
   148754   const int32_t opt = U_FOLD_CASE_DEFAULT;
   148755   UErrorCode status = U_ZERO_ERROR;
   148756   int nChar;
   148757 
   148758   UChar32 c;
   148759   int iInput = 0;
   148760   int iOut = 0;
   148761 
   148762   *ppCursor = 0;
   148763 
   148764   if( zInput==0 ){
   148765     nInput = 0;
   148766     zInput = "";
   148767   }else if( nInput<0 ){
   148768     nInput = strlen(zInput);
   148769   }
   148770   nChar = nInput+1;
   148771   pCsr = (IcuCursor *)sqlite3_malloc(
   148772       sizeof(IcuCursor) +                /* IcuCursor */
   148773       ((nChar+3)&~3) * sizeof(UChar) +   /* IcuCursor.aChar[] */
   148774       (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
   148775   );
   148776   if( !pCsr ){
   148777     return SQLITE_NOMEM;
   148778   }
   148779   memset(pCsr, 0, sizeof(IcuCursor));
   148780   pCsr->aChar = (UChar *)&pCsr[1];
   148781   pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
   148782 
   148783   pCsr->aOffset[iOut] = iInput;
   148784   U8_NEXT(zInput, iInput, nInput, c);
   148785   while( c>0 ){
   148786     int isError = 0;
   148787     c = u_foldCase(c, opt);
   148788     U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
   148789     if( isError ){
   148790       sqlite3_free(pCsr);
   148791       return SQLITE_ERROR;
   148792     }
   148793     pCsr->aOffset[iOut] = iInput;
   148794 
   148795     if( iInput<nInput ){
   148796       U8_NEXT(zInput, iInput, nInput, c);
   148797     }else{
   148798       c = 0;
   148799     }
   148800   }
   148801 
   148802   pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
   148803   if( !U_SUCCESS(status) ){
   148804     sqlite3_free(pCsr);
   148805     return SQLITE_ERROR;
   148806   }
   148807   pCsr->nChar = iOut;
   148808 
   148809   ubrk_first(pCsr->pIter);
   148810   *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
   148811   return SQLITE_OK;
   148812 }
   148813 
   148814 /*
   148815 ** Close a tokenization cursor previously opened by a call to icuOpen().
   148816 */
   148817 static int icuClose(sqlite3_tokenizer_cursor *pCursor){
   148818   IcuCursor *pCsr = (IcuCursor *)pCursor;
   148819   ubrk_close(pCsr->pIter);
   148820   sqlite3_free(pCsr->zBuffer);
   148821   sqlite3_free(pCsr);
   148822   return SQLITE_OK;
   148823 }
   148824 
   148825 /*
   148826 ** Extract the next token from a tokenization cursor.
   148827 */
   148828 static int icuNext(
   148829   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
   148830   const char **ppToken,               /* OUT: *ppToken is the token text */
   148831   int *pnBytes,                       /* OUT: Number of bytes in token */
   148832   int *piStartOffset,                 /* OUT: Starting offset of token */
   148833   int *piEndOffset,                   /* OUT: Ending offset of token */
   148834   int *piPosition                     /* OUT: Position integer of token */
   148835 ){
   148836   IcuCursor *pCsr = (IcuCursor *)pCursor;
   148837 
   148838   int iStart = 0;
   148839   int iEnd = 0;
   148840   int nByte = 0;
   148841 
   148842   while( iStart==iEnd ){
   148843     UChar32 c;
   148844 
   148845     iStart = ubrk_current(pCsr->pIter);
   148846     iEnd = ubrk_next(pCsr->pIter);
   148847     if( iEnd==UBRK_DONE ){
   148848       return SQLITE_DONE;
   148849     }
   148850 
   148851     while( iStart<iEnd ){
   148852       int iWhite = iStart;
   148853       U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
   148854       if( u_isspace(c) ){
   148855         iStart = iWhite;
   148856       }else{
   148857         break;
   148858       }
   148859     }
   148860     assert(iStart<=iEnd);
   148861   }
   148862 
   148863   do {
   148864     UErrorCode status = U_ZERO_ERROR;
   148865     if( nByte ){
   148866       char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
   148867       if( !zNew ){
   148868         return SQLITE_NOMEM;
   148869       }
   148870       pCsr->zBuffer = zNew;
   148871       pCsr->nBuffer = nByte;
   148872     }
   148873 
   148874     u_strToUTF8(
   148875         pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
   148876         &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
   148877         &status                                  /* Output success/failure */
   148878     );
   148879   } while( nByte>pCsr->nBuffer );
   148880 
   148881   *ppToken = pCsr->zBuffer;
   148882   *pnBytes = nByte;
   148883   *piStartOffset = pCsr->aOffset[iStart];
   148884   *piEndOffset = pCsr->aOffset[iEnd];
   148885   *piPosition = pCsr->iToken++;
   148886 
   148887   return SQLITE_OK;
   148888 }
   148889 
   148890 /*
   148891 ** The set of routines that implement the simple tokenizer
   148892 */
   148893 static const sqlite3_tokenizer_module icuTokenizerModule = {
   148894   0,                           /* iVersion */
   148895   icuCreate,                   /* xCreate  */
   148896   icuDestroy,                  /* xCreate  */
   148897   icuOpen,                     /* xOpen    */
   148898   icuClose,                    /* xClose   */
   148899   icuNext,                     /* xNext    */
   148900 };
   148901 
   148902 /*
   148903 ** Set *ppModule to point at the implementation of the ICU tokenizer.
   148904 */
   148905 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
   148906   sqlite3_tokenizer_module const**ppModule
   148907 ){
   148908   *ppModule = &icuTokenizerModule;
   148909 }
   148910 
   148911 #endif /* defined(SQLITE_ENABLE_ICU) */
   148912 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   148913 
   148914 /************** End of fts3_icu.c ********************************************/
   148915